Java讀寫文本文件的步驟如下:
File file = new File("path/to/file.txt");
FileReader reader = new FileReader(file);
FileWriter writer = new FileWriter(file);
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
while ((line = bufferedReader.readLine()) != null) {
// 處理每一行的內容
}
bufferedReader.close();
BufferedWriter bufferedWriter = new BufferedWriter(writer);
bufferedWriter.write("Hello, World!");
bufferedWriter.newLine(); // 換行
bufferedWriter.close();
reader.close();
writer.close();
注意:在使用文件讀寫操作時,可能會拋出IOException異常,因此需要對異常進行處理。