下面是一个示例代码实现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
类从同一个文件中读取文本并打印出来。