下面是一個示例代碼實現Java的讀寫文件功能:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileReadWriteExample {
public static void main(String[] args) {
String fileName = "data.txt";
// 寫文件
try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
writer.write("Hello, World!");
writer.newLine();
writer.write("This is a sample file.");
} catch (IOException e) {
e.printStackTrace();
}
// 讀文件
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
這個示例中,我們首先使用BufferedWriter
類將文本寫入到名為data.txt
的文件中。然后使用BufferedReader
類從同一個文件中讀取文本并打印出來。