如何在java中逐行读取文本文件并打印到另一个文件到Windows目录中可用的同一文件夹中?

问题描述 投票:0回答:1

如何在java中逐行读取文本文件并打印到另一个文件到Windows目录中可用的同一文件夹中?

还需要使用配置文件查找并替换几行。

我在 dos 批处理文件中尝试过,它可以工作,但需要在 java 中。

java replace find readfile writefile
1个回答
0
投票

您可以使用 Java 7 中引入的

java.nio.file.Files
类来进行高效的文件处理。要使用配置文件替换特定行,您可以使用
HashMap
来存储配置:

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

public class FileProcessor {
    /**
     * Reads a file line by line, replaces specified lines, and writes to another file.
     *
     * @param inputFilePath  Path to the input file.
     * @param outputFilePath Path to the output file.
     * @param configFilePath Path to the configuration file with replacements.
     */
    public static void processFile(String inputFilePath, String outputFilePath, String configFilePath) {
        // Load configurations
        HashMap<String, String> configs = loadConfigurations(configFilePath);

        try {
            // Read all lines from the input file
            List<String> lines = Files.readAllLines(Paths.get(inputFilePath));

            // Process and replace lines based on configurations
            List<String> processedLines = lines.stream()
                    .map(line -> configs.getOrDefault(line, line))
                    .collect(Collectors.toList());

            // Write the processed lines to the output file
            Files.write(Paths.get(outputFilePath), processedLines);
            System.out.println("File processing complete. Output saved to: " + outputFilePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Loads configurations from a file into a HashMap.
     *
     * @param configFilePath Path to the configuration file.
     * @return HashMap with configurations.
     */
    private static HashMap<String, String> loadConfigurations(String configFilePath) {
        HashMap<String, String> configurations = new HashMap<>();
        try {
            List<String> configLines = Files.readAllLines(Paths.get(configFilePath));
            for (String line : configLines) {
                String[] parts = line.split("=", 2);
                if (parts.length == 2) {
                    configurations.put(parts[0], parts[1]);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return configurations;
    }

    public static void main(String[] args) {
        // Specify the file paths
        String inputFilePath = "path/to/input.txt";
        String outputFilePath = "path/to/output.txt";
        String configFilePath = "path/to/config.txt";

        // Process the file
        processFile(inputFilePath, outputFilePath, configFilePath);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.