在Java中,可以使用IO流来读写文件。下面是一些常见的示例:
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("input.txt");
fos = new FileOutputStream("output.txt");
int ch;
while ((ch = fis.read()) != -1) {
fos.write(ch);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
BufferedReader reader = null;
BufferedWriter writer = null;
try {
reader = new BufferedReader(new FileReader("input.txt"));
writer = new BufferedWriter(new FileWriter("output.txt"));
String line;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
if (writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Scanner scanner = new Scanner(System.in);
System.out.print("请输入姓名:");
String name = scanner.nextLine();
System.out.println("你的姓名是:" + name);
scanner.close();
这些是一些常见的示例,你可以根据不同的需求选择合适的IO类和方法来读写文件。