Java

java中怎么使用io流读写文件

小亿
101
2023-08-26 04:09:14
栏目: 编程语言

在Java中,可以使用IO流来读写文件。下面是一些常见的示例:

  1. 使用FileInputStream和FileOutputStream类来读写字节流文件:
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();
}
}
  1. 使用BufferedReader和BufferedWriter类来读写文本文件:
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();
}
}
  1. 使用Scanner类来读取用户输入:
Scanner scanner = new Scanner(System.in);
System.out.print("请输入姓名:");
String name = scanner.nextLine();
System.out.println("你的姓名是:" + name);
scanner.close();

这些是一些常见的示例,你可以根据不同的需求选择合适的IO类和方法来读写文件。

0
看了该问题的人还看了