java如何输入txt
读取txt文件的方法
使用BufferedReader和FileReader组合读取文本文件内容。这种方法适合逐行读取大文件,避免内存溢出。
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
使用Files类读取
Java 7及以上版本可以使用Files类快速读取小文件内容为字符串或字节数组。
Path path = Paths.get("file.txt");
String content = Files.readString(path); // 读取为字符串
List<String> lines = Files.readAllLines(path); // 按行读取为列表
Scanner类读取
Scanner类提供更灵活的文本解析功能,适合需要按特定分隔符处理的情况。
try (Scanner scanner = new Scanner(new File("file.txt"))) {
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
写入txt文件的方法
使用BufferedWriter写入文本文件,支持追加模式。
try (BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) {
bw.write("要写入的文本内容");
bw.newLine(); // 换行
} catch (IOException e) {
e.printStackTrace();
}
使用Files类写入
Java 7+版本可用Files.write快速写入内容。
Path path = Paths.get("output.txt");
Files.write(path, "内容".getBytes(), StandardOpenOption.CREATE);
注意事项
处理文件路径时建议使用Paths.get()或new File()的绝对路径。相对路径基于程序启动目录。
IO操作必须处理IOException,推荐使用try-with-resources语句自动关闭资源。

大文件应使用流式处理(如BufferedReader),避免一次性读取全部内容导致内存不足。






