简体   繁体   English

读取文件,替换字符串并创建一个包含所有内容的新文件

[英]Read file, replace string and create a new one with all content

I am trying to replace ? 我要更换? with - in my text document but just the ArrayList<String> is being written in the new file without all lines of the old one. 在我的文本文档中带有- ,但是只有ArrayList<String>被写入新文件,而没有旧文件的所有行。 How can I fix that? 我该如何解决?

File file = new File("D:\\hl_sv\\L09MF.txt");

ArrayList<String> lns = new ArrayList<String>();
Scanner scanner;
try {

    scanner = new Scanner(file);

    int lineNum = 0;
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        lineNum++;
        if (line.contains("?")) {
            line = line.replace("?", "-");
            lns.add(line);

            // System.out.println("I found it on line " + lineNum);
        }
    }
    lines.clear();
    lines = lns;
    System.out.println("Test: " + lines);

    FileWriter writer;
    try {
        writer = new FileWriter("D:\\hl_sv\\L09MF2.txt");
        for (String str : lines) {
            writer.write(str);
        }

        writer.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

I don't understand why you're storing the lines in a List to begin with. 我不明白您为什么要将这些lines存储在List中。 I would perform the transform and print while I read. 我在阅读时会执行转换和打印。 You don't need to test for the presence of the ? 您无需测试是否存在? (replace won't alter anything if it isn't present). (如果不存在,则替换不会改变任何内容)。 And, I would also use a try-with-resources . 而且,我还将使用try-with-resources Something like 就像是

File file = new File("D:\\hl_sv\\L09MF.txt");
try (PrintWriter writer = new PrintWriter("D:\\hl_sv\\L09MF2.txt");
        Scanner scanner = new Scanner(file)) {
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        writer.println(line.replace('?', '-'));
    }
} catch (Exception e) {
    e.printStackTrace();
}

Examine this code: 检查以下代码:

if (line.contains("?")) {
    line = line.replace("?", "-");
    lns.add(line);
}

You are only adding the current line (with the replacement) if it had a ? 如果当前行有?,则仅添加当前行(带有替换行)。 in it, ignoring other lines. 在其中,忽略其他行。 Restructure it to always add the existing line. 对其进行重组以始终添加现有行。

if (line.contains("?")) {
    line = line.replace("?", "-");
}
lns.add(line);

Additionally, the part 此外,该部分

if (line.contains("?"))

scans line to look for a ?, and then the code 扫描line以查找?,然后执行代码

line.replace("?", "-");

does the same thing, but this time also replacing any ? 做同样的事情,但是这次也替换了吗? with -. 与-。 You may as well scan line just once: 你不妨扫描line只有一次:

lns.add(line.replace("?", "-"));

Note that creating an ArrayList just to hold the new lines wastes a fair amount of memory if the file is large. 请注意,如果文件很大,创建仅用于容纳新行的ArrayList会浪费大量内存。 A better pattern would be to write each line, modified if necessary, right after you read in the corresponding line. 更好的模式是在阅读相应的行之后立即编写每行,并根据需要进行修改。

Within your while loop you have an if statement checking the line which adds the altered line to the array. 在while循环中,您具有if语句,用于检查将更改后的行添加到数组的行。 You also need to add the unaltered lines to the array. 您还需要将未更改的行添加到数组。

This should fix your issue: 这应该可以解决您的问题:

        int lineNum = 0;
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            lineNum++;
            if (line.contains("?")) {
                line = line.replace("?", "-");
                lns.add(line);

                // System.out.println("I found it on line " + lineNum);
            }
            else{
                lns.add(line);
            }

Previously, you were only adding the line to your ArrayList if it contained a "?" 以前,您仅将行添加到ArrayList中(如果其中包含“?”)。 character. 字符。 You need to add the line to the ArrayList whether or not it contains "?" 您需要将行添加到ArrayList中,无论它是否包含“?”

I would use a different approach if I'm trying to work on the functionality you want to implement, please check this approach and tell me if this helps you :) 如果我尝试使用要实现的功能,我会使用其他方法,请检查此方法并告诉我这是否对您有帮助:)

public void saveReplacedFile() {
    //1. Given a file in your system
    File file = new File("D:\\hl_sv\\L09MF.txt");

    try {
        //2. I will read it, not necessarily with Scanner, but use a BufferedReader instead
        BufferedReader bufferedReader = new BufferedReader(new FileReader(file));

        //3. Define a variable that will hold the value of each line
        String line = null;
        //and also the information of your file
        StringBuilder contentHolder = new StringBuilder();
        //why not get your line separator based on your O.S?
        String lineSeparator = System.getProperty("line.separator");

        //4. Check your file line by line
        while ((line = bufferedReader.readLine()) != null) {
            contentHolder.append(line);
            contentHolder.append(lineSeparator);
        }

        //5. By this point, your contentHolder will contain all the data of your text
        //But it is still a StringBuilder type object, why not convert it to a String?
        String contentAsString = contentHolder.toString();

        //6. Now we can replace your "?" with "-"
        String replacedString = contentAsString.replace("?", "-");

        //7. Now, let's save it in a new file using BufferedWriter :)
        File fileToBeSaved = new File("D:\\hl_sv\\L09MF2.txt");

        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(fileToBeSaved));

        bufferedWriter.write(replacedString);

        //Done :)


    } catch (FileNotFoundException e) {
        // Exception thrown if the file does not exist in your system
        e.printStackTrace();
    } catch (IOException e) {
        // Exception thrown due to an issue with IO
        e.printStackTrace();
    }
}

Hope this is helpful. 希望这会有所帮助。 Happy coding :) 快乐的编码:)

If you can use Java 8 then your code can be simplified to 如果可以使用Java 8,则可以将代码简化为

try (PrintStream ps = new PrintStream("D:\\hl_sv\\L09MF2.txt");
    Stream<String> stream = Files.lines(Paths.get("D:\\hl_sv\\L09MF.txt"))) {
    stream.map(line -> line.replace('?', '-')).forEach(ps::println);
} catch (IOException e) {
    e.printStackTrace();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 读取 POST 请求正文 PDF 内容并创建新的 PDF 文件 - Read POST request body PDF content and create new PDF File 将一个字符串的内容替换为另一个? - Replace content of one string with another? 如果指定的文件不存在,RandomAccessFile 是否会创建一个新文件? 如果文件确实存在,它会用新文件替换文件吗? - Does RandomAccessFile create a new file, if the specidied one does not exist? Does it replace the file with a new one if it does exist? 读取类文件并替换类文件的内容 - Read the class file and replace content of the class file 用新文件内容替换文件中的单词 - Replace a word in a file with a new file content 用新String替换字符串中的所有UpperLetters - Replace all UpperLetters in a string with a new String 拥有一个字符串,替换然后执行拆分或拥有一个字符串数组并创建一个新的更改它更有效? - More efficient to have one string, replace and then perform a split or have an array of strings and create a new one changing it? 如何读取jar文件,将其转换为字符串并从该字符串创建新的jar文件? - How to read a jar file, convert it to a string and create a new jar file from that string? 如何用用户输入的变量替换文本文件中多次出现的字符串并将其全部保存到新文件中? - How to replace multiple occurences of a string in a text file with a variable entered by the user and save all to a new file? 如何读取文件夹中存在的所有 Zip 文件并创建包含所有内容的新文本文件 - How do i read all the Zip files present in the folder and create a new text file with all the contents
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM