首页 > 解决方案 > 从文本文件 java 中删除单个和多个空格,但不应合并文本文件中的所有行

问题描述

考虑到 txt 文件中有 n 行,例如 4 行。

从文件输入:

ABCDE

FGHIJK

LMNOP

QRST

预期的输出文件:

ABCDE

FGHIJK

LMNOP

QRST

我设法产生的输出是:

ABCDEFGHIJKLMNOPQRST

预期的输出应如下所示,单词之间或行之间没有任何空格。

标签: javafile-io

解决方案


首先,根据您的问题,如果您可以逐行阅读,那将是最有益的。幸运的是,使用 Java-8 的 Streams 实现,您可以做到这一点!

该方法会将文件的每一行作为String, 添加到ArrayList<String>.

static ArrayList<String> readFileText (String filename){

    //ArrayList to hold all the lines
    ArrayList<String> lines = null;
    //Get lines of text (Strings) as a stream
    try (Stream<String> stream = Files.lines(Paths.get(filename))){
        // convert stream to a List-type object
        lines = (ArrayList<String>)stream.collect(Collectors.toList());
    }
    catch (IOException ioe){
        System.out.println("\nCould not read lines of text from the file.");
    }
    catch (SecurityException se){
        System.out.println("Could not read the file provided." + 
          "Please check if you have permission to access it.");
    }

    return lines;
}

通过使用上述方法,您将设法将文本文件中的每一行添加为一个数组列表String,但我们现在仍然必须从每个字符串中删除空格。

因此,一种非常简单的方法是使用以下方法编写输出文件:

static void writeFileText (String filename, ArrayList<String> linesOfText){
        // Specify file location and name
        Path file = Paths.get(filename);
        // StringBuilder will be used to create ONE string of text
        StringBuilder sb = new StringBuilder();
        // Iterate over the list of strings and append them 
        // to string-builder with a 'new line' carriage return.
        for( String line : linesOfText){
            line.replaceAll(" ", ""); // Replace all whitespace with empty string
            sb.append(line).append("\n");
        }
        // Get all bytes of produced string and instantly write them to the file.
        byte[] bytes = sb.toString().getBytes();
        // Write to file
        try{
            Files.write(file, bytes);
        }
        catch(IOException ioe){
            System.out.println("\nCould not write to file \""+filename+"\".);
        }

}

那么您的主要方法将只有 2 行长(考虑到您只是解决您发布的问题的方法,仅此而已):

public static void main(String[] args){
    ArrayList<String> lines = Class.readFileText("input.txt");
    Class.writeFileText("output.txt", lines);
}

在这里,Class是指静态方法所在的类名。

上述方法取自GitHub 存储库。


推荐阅读