Java-如何从文本文件中删除空行

Java-如何从文本文件中删除空行,java,Java,我希望能够从文本文件中删除空行,例如: 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 {

我希望能够从文本文件中删除空行,例如:

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显示换行符

您可以复制到临时文件并重命名它

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

您可以复制到临时文件并重命名它

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

您的代码几乎正确,但存在一些错误:

  • 必须使用.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);

您的代码几乎正确,但存在一些错误:

  • 必须使用.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);
尝试和迭代器

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”;
列表行=FileUtils.readLines(新文件(名称));
迭代器i=lines.Iterator();
while(i.hasNext())
{
字符串行=i.next();
if(line.trim().isEmpty())
i、 删除();
}
FileUtils.writeLines(新文件(名称),行);
}
捕获(IOE异常)
{
e、 printStackTrace();
}
尝试使用迭代器

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”;
列表行=FileUtils.readLines(新文件(名称));
迭代器i=lines.Iterator();
while(i.hasNext())
{
字符串行=i.next();
if(line.trim().isEmpty())
i、 删除();
}
FileUtils.writeLines(新文件(名称),行);
}
捕获(IOE异常)
{
e、 printStackTrace();
}

这段代码为我解决了这个问题

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
    }

}
正如在代码块的注释中提到的,您的示例在扫描仪之后声明了print writer,这意味着程序已经覆盖了当前同名文件。因此,扫描仪无法读取任何代码,因此,程序会给您一个空白文件


只是添加了一个额外的空间,这不会阻止程序继续在该空间上编写,但是,这一切都很好

这段代码为我解决了这个问题

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
    }

}
正如在代码块的注释中提到的,您的示例在扫描仪之后声明了print writer,这意味着程序已经覆盖了当前同名文件。因此,扫描仪无法读取任何代码,因此,程序会给您一个空白文件


只需添加一个额外的空间,这不会阻止程序继续在该空间上写入,但是,这样做很好

源文件和目标文件是同一个文件吗?在这种情况下,您在能够读取文件之前覆盖了该文件。关闭printwriter无效。是的,它们都指向同一个位置。您的源文件和目标文件是同一个文件吗?在这种情况下,您在能够读取文件之前覆盖了该文件。关闭printwriter不起作用,是的,它们都指向同一个位置您是指path.get??您是指path.get??