You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java文件处理:如何在文件每行后添加指定文本行

Java读取文件并在每行后添加"Hello World"的实现方案

核心思路是逐行读取原文件内容,每读取一行就将该行与"Hello World"依次写入目标文件。注意不要直接覆盖原文件,建议写入新文件避免数据丢失。以下提供两种适合初学者的实现方式:

方式一:Java 8+ 流式API(简洁写法)

利用Java 8引入的流式API和NIO工具类,代码更简洁且自动处理资源关闭:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class AddHelloWorld {
    public static void main(String[] args) {
        // 替换为你的实际输入文件路径
        String inputPath = "input.txt";
        // 替换为你的实际输出文件路径
        String outputPath = "output.txt";

        try (Stream<String> lines = Files.lines(Paths.get(inputPath))) {
            // 将每一行转换为「原行 + Hello World」的流
            var modifiedLines = lines.flatMap(line -> Stream.of(line, "Hello World"))
                                    .collect(Collectors.toList());
            
            // 把处理后的内容写入新文件
            Files.write(Paths.get(outputPath), modifiedLines);
            System.out.println("处理完成,结果已写入" + outputPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  • Files.lines:以流的形式读取文件,配合try-with-resources语法自动关闭资源
  • flatMap:将单一行扩展为包含原行和"Hello World"的两个元素,实现每行后新增一行的效果
  • Files.write:批量写入处理后的内容到目标文件

方式二:传统IO流写法(适合理解基础逻辑)

用缓冲流逐行读写,更直观展示文件操作的底层逻辑:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class AddHelloWorldBasic {
    public static void main(String[] args) {
        String inputPath = "input.txt";
        String outputPath = "output.txt";

        // try-with-resources自动关闭流,无需手动调用close()
        try (BufferedReader reader = new BufferedReader(new FileReader(inputPath));
             BufferedWriter writer = new BufferedWriter(new FileWriter(outputPath))) {
            
            String line;
            // 循环读取每一行,直到文件末尾(返回null)
            while ((line = reader.readLine()) != null) {
                // 先写入原行并换行
                writer.write(line);
                writer.newLine();
                // 再写入Hello World并换行
                writer.write("Hello World");
                writer.newLine();
            }
            System.out.println("处理完成,结果已写入" + outputPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  • BufferedReader/BufferedWriter:缓冲流提升文件读写效率
  • while ((line = reader.readLine()) != null):标准的逐行读取循环逻辑
  • 每次读取一行后,按顺序写入原内容和新增内容,保证格式符合要求

注意事项

  • 替换代码中的文件路径为你本地的实际路径
  • 运行前确保输入文件存在,否则会抛出FileNotFoundException
  • 绝对不要将输出路径设置为原文件路径,否则会直接覆盖原文件内容
  • 两种方式都适合处理大文件,不会一次性将所有内容加载到内存

内容的提问来源于stack exchange,提问作者SWETHAN DEEKONDA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 22:22:48