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

移除文本文件非数字字符及Java文件差异对比程序技术问询

Hey there! Let's break down your two file-processing tasks and solve them properly:

需求一:移除仅含数字的文本文件中的非数字字符

If you need to strip all non-digit characters from a text file that's supposed to only contain numbers, here's a straightforward Java implementation:

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

public class DigitCleaner {
    public static void main(String[] args) throws IOException {
        // Replace these paths with your actual file locations
        String inputFile = "your_input_file.txt";
        String outputFile = "cleaned_digits_only.txt";

        BufferedReader reader = new BufferedReader(new FileReader(inputFile));
        BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile));
        String currentLine;

        while ((currentLine = reader.readLine()) != null) {
            // Regex to replace anything that's not a 0-9 digit with empty string
            String cleanedLine = currentLine.replaceAll("[^0-9]", "");
            writer.write(cleanedLine);
            writer.newLine();
        }

        // Always close resources to avoid leaks
        reader.close();
        writer.close();
        System.out.println("Cleanup done! Check " + outputFile + " for the result.");
    }
}
  • This program reads your input file line by line, uses the regex [^0-9] to target and remove all non-digit characters, then writes the cleaned content to a new file.
  • Don't forget to swap out your_input_file.txt and cleaned_digits_only.txt with your actual file paths.
需求二:对比两个文本文件并找出独有行

The Java program you found has a solid core idea—let's complete it, clean up the code, and add explanations to make it work reliably:

package Exercise1;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

// Renamed to follow Java naming conventions (class names start with uppercase)
public class FileLineComparator {
    public static void main(String[] args) throws IOException {
        // Update these paths to match your files
        String firstFilePath = "migratielijst.txt";
        String secondFilePath = "complete.txt";

        // Read both files into Sets (automatically handles duplicates and enables fast comparisons)
        Set<String> firstFileLines = readFileContents(firstFilePath);
        Set<String> secondFileLines = readFileContents(secondFilePath);

        // Find lines unique to the first file
        Set<String> uniqueToFirst = new HashSet<>(firstFileLines);
        uniqueToFirst.removeAll(secondFileLines);

        // Find lines unique to the second file
        Set<String> uniqueToSecond = new HashSet<>(secondFileLines);
        uniqueToSecond.removeAll(firstFileLines);

        // Print out the results in a readable format
        System.out.println("Lines only present in " + firstFilePath + ":");
        uniqueToFirst.forEach(line -> System.out.println("- " + line));

        System.out.println("\nLines only present in " + secondFilePath + ":");
        uniqueToSecond.forEach(line -> System.out.println("- " + line));
    }

    // Helper method to avoid code duplication when reading files
    private static Set<String> readFileContents(String filePath) throws IOException {
        Set<String> lineSet = new HashSet<>();
        BufferedReader reader = new BufferedReader(new FileReader(filePath));
        String currentLine;

        while ((currentLine = reader.readLine()) != null) {
            // Use line.trim() if you want to ignore leading/trailing whitespace differences
            // Remove .trim() if exact whitespace matching is required
            lineSet.add(currentLine.trim());
        }

        reader.close();
        return lineSet;
    }
}

Key improvements & notes:

  • Renamed the class to FileLineComparator to follow standard Java naming rules.
  • Used HashSet for storing lines: this automatically removes duplicate lines from each file and makes the removeAll() comparison operation very efficient.
  • Added a reusable helper method readFileContents() to avoid repeating file-reading code.
  • Included options for handling whitespace: if you don't care about leading/trailing spaces, keep currentLine.trim(); remove the trim() call if you need exact matches including whitespace.
  • The output clearly lists which lines are unique to each file, making it easy to review the differences.

内容的提问来源于stack exchange,提问作者Benjamin Josso

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:24:31