简体   繁体   中英

Java - How to remove blank lines from a text file

I want to be able to remove blank lines from a text file, for example:

Average Monthly Disposable Salary
1
Switzerland 
$6,301.73 
2014

2
Luxembourg 
$4,479.80 
2014

3
Zambia 
$4,330.98 
2014

--To This:

Average Monthly Disposable Salary
1
Switzerland 
$6,301.73 
2014
2
Luxembourg 
$4,479.80 
2014
3
Zambia 
$4,330.98 
2014

All of the code I have is below:

public class Driver {

    public static void main(String[] args) 
    throws Exception {

        Scanner file = new Scanner(new File("src/data.txt"));

        PrintWriter write = new PrintWriter("src/data.txt");

        while(file.hasNext()) {
            if (file.next().equals("")) {
                continue;
            } else {
                write.write(file.next());
            }
        }
        print.close();
        file.close();

    }

}

The problem is that the text file is empty once I go back and look at the file again.

Im not sure why this is acting this way since they all seem to be blank characters, \\n showing line breaks

Your code was almost correct, but there were a few bugs:

  • You must use .nextLine() instead of .next()
  • You must write to a different file while reading the original one
  • Your print.close(); should be write.close();
  • You forgot to add a new line after each line written
  • You don't need the continue; instruction, since it's redundant.

     public static void main(String[] args) { Scanner file; PrintWriter writer; try { file = new Scanner(new File("src/data.txt")); writer = new PrintWriter("src/data2.txt"); while (file.hasNext()) { String line = file.nextLine(); if (!line.isEmpty()) { writer.write(line); writer.write("\\n"); } } file.close(); writer.close(); } catch (FileNotFoundException ex) { Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex); } }

If you want to keep the original name, you can do something like:

File file1 = new File("src/data.txt");
File file2 = new File("src/data2.txt");

file1.delete();
file2.renameTo(file1);

Try org.apache.commons.io and Iterator

try
{
    String name = "src/data.txt";
    List<String> lines = FileUtils.readLines(new File(name));

    Iterator<String> i = lines.iterator();
    while (i.hasNext())
    {
        String line = i.next();
        if (line.trim().isEmpty())
            i.remove();
    }

    FileUtils.writeLines(new File(name), lines);
}
catch (IOException e)
{
    e.printStackTrace();
}

You could copy to a temporary file and rename it.

String name = "src/data.txt";
try(BufferedWriter bw = new BufferedWriter(name+".tmp)) {
    Files.lines(Paths.get(name))
         .filter(v -> !v.trim().isEmpty())
         .forEach(bw::println);
}
new File(name+".tmp").renameTo(new File(name));

This piece of code solved this problem for me

package linedeleter;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

public class LineDeleter {

    public static void main(String[] args) throws FileNotFoundException, IOException {
        File oldFile = new File("src/data.txt"); //Declares file variable for location of file
        Scanner deleter = new Scanner(oldFile); //Delcares scanner to read file
        String nonBlankData = ""; //Empty string to store nonblankdata
        while (deleter.hasNextLine()) { //while there are still lines to be read 
            String currentLine = deleter.nextLine(); //Scanner gets the currentline, stories it as a string
            if (!currentLine.isBlank()) { //If the line isn't blank
                nonBlankData += currentLine + System.lineSeparator(); //adds it to nonblankdata
            }
        }
        PrintWriter writer = new PrintWriter(new FileWriter("src/data.txt"));
        //PrintWriter and FileWriter are declared, 
        //this part of the code is when the updated file is made, 
        //so it should always be at the end when the other parts of the 
        //program have finished reading the file
        writer.print(nonBlankData); //print the nonBlankData to the file
        writer.close(); //Close the writer
    }

}

As mentioned in the comments, of the code block, your sample had the print writer declared after your scanner meaning that the program had already overwritten your current file of the same name. Therefore there was no code for your scanner to read and thus, the program gave you a blank file

the

System.lineSeparator()

Just adds an extra space, this doesn't stop the program from continuing to write on that space, however, so it's all good

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