Java - 如何从文本文件中删除空行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34999999/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java - How to remove blank lines from a text file
提问by Nicholas Dry
I want to be able to remove blank lines from a text file, for example:
我希望能够从文本文件中删除空行,例如:
Average Monthly Disposable Salary
1
Switzerland
,301.73
2014
2
Luxembourg
,479.80
2014
3
Zambia
,330.98
2014
--To This:
——至此:
Average Monthly Disposable Salary
1
Switzerland
,301.73
2014
2
Luxembourg
,479.80
2014
3
Zambia
,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
我不确定为什么会这样,因为它们似乎都是空白字符,\n 显示换行符
回答by R.Costa
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); } }
- 您必须使用.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); } }
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);
回答by user3826636
Try org.apache.commons.ioand Iterator
尝试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();
}
回答by Peter Lawrey
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));
回答by EliasJR
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
只是添加了一个额外的空间,这并不会阻止程序继续在该空间上写入,但是,这一切都很好