簡體   English   中英

Java - 如何從文本文件中刪除空行

[英]Java - How to remove blank lines from a text file

我希望能夠從文本文件中刪除空行,例如:

Average Monthly Disposable Salary
1
Switzerland 
$6,301.73 
2014

2
Luxembourg 
$4,479.80 
2014

3
Zambia 
$4,330.98 
2014

——至此:

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

我擁有的所有代碼如下:

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

    }

}

問題是,一旦我回去再次查看該文件,該文本文件就是空的。

我不確定為什么會這樣,因為它們似乎都是空白字符,\\n 顯示換行符

你的代碼幾乎是正確的,但有一些錯誤:

  • 您必須使用.nextLine()而不是.next()
  • 您必須在讀取原始文件時寫入另一個文件
  • 你的print.close(); 應該是write.close();
  • 你忘記在寫的每一行后添加一個新行
  • 你不需要繼續; 指令,因為它是多余的。

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

如果要保留原始名稱,可以執行以下操作:

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

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

嘗試org.apache.commons.io和 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();
}

您可以復制到臨時文件並重命名。

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

這段代碼為我解決了這個問題

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
    }

}

正如代碼塊的評論中所提到的,您的示例在您的掃描儀之后聲明了打印編寫器,這意味着該程序已經覆蓋了您當前的同名文件。 因此,您的掃描儀沒有代碼可以讀取,因此程序給了您一個空白文件

System.lineSeparator()

只是添加了一個額外的空間,這並不會阻止程序繼續在該空間上寫入,但是,這一切都很好

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM