在Java中,可以使用File类和FileInputStream、FileOutputStream、BufferedReader、BufferedWriter等类来读写文件。
读取文件的步骤如下:
示例代码如下:
File file = new File("file.txt");
FileInputStream fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
fis.close();
写入文件的步骤如下:
示例代码如下:
File file = new File("output.txt");
FileOutputStream fos = new FileOutputStream(file);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.write("Hello, world!");
bw.newLine();
bw.write("This is a test!");
bw.flush();
bw.close();
fos.close();