简体   繁体   中英

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. 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. 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 . 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.replace("?", "-");

does the same thing, but this time also replacing any ? with -. You may as well scan line just once:

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. 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. 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 "?" character. You need to add the line to the ArrayList whether or not it contains "?"

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

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM