通过文件处理连接 java 中多行文本的最简单方法

Simplest way to concatenate multi lines of text in java through File Handling

我尝试在给定的文本文件中连接 2 行文本并将输出打印到控制台。我的代码很复杂,有没有更简单的方法,利用FileHandling的基本概念来实现?

import java.io.*;


public class ConcatText{

    public static void main(String[] args){
    
        BufferedReader br = null;
        try{
            String currentLine;
            br = new BufferedReader(new FileReader("C:\Users\123\Documents\CS105\FileHandling\concat.file.text"));
            
            StringBuffer text1 = new StringBuffer (br.readLine());
            StringBuffer text2 = new StringBuffer(br.readLine()); 
            text1.append(text2);
            String str = text1.toString();
            str = str.trim();
            String array[] = str.split(" ");
            StringBuffer result = new StringBuffer();
            for(int i=0; i<array.length; i++) {
               result.append(array[i]);
              }
              System.out.println(result);
            }
        catch(IOException e){
            e.printStackTrace();
        }finally{
            try{
                if(br != null){
                    br.close();
                }
                }catch(IOException e){
                    e.printStackTrace();
                    
                }
            }   
                
        }
        
    
    
    }

The text file is as follows :
GTAGCTAGCTAGC
AGCCACGTA

the output should be as follows (concatenation of the text file Strings) :
GTAGCTAGCTAGCAGCCACGTA

如果您使用的是 java 8 或更高版本,最简单的方法是:

List<String> lines = Files.readAllLines(Paths.get(filePath));
String result = String.join("", lines);

如果你正在使用 java 7,至少你可以使用 try with resources 来减少代码中的混乱,像这样:

try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
   StringBuffer text1 = new StringBuffer (br.readLine());
   StringBuffer text2 = new StringBuffer(br.readLine()); 
   // ...
}catch(IOException e){
   e.printStackTrace();
}

这样,资源将自动关闭,您无需调用 br.close()。

简答,有:

  public static void main(String[] args) {
    //this is called try-with-resources, it handles closing the resources for you
    try (BufferedReader reader = new BufferedReader(...)) {
      StringBuilder stringBuilder = new StringBuilder();
      String line = reader.readLine();
      //readLine() will return null when there are no more lines
      while (line != null) {
        //replace any spaces with empty string
        //first argument is regex matching any empty spaces, second is replacement
        line = line.replaceAll("\s+", "");
        //append the current line
        stringBuilder.append(line);
        //read the next line, will be null when there are no more
        line = reader.readLine();
      }
      System.out.println(stringBuilder);
    } catch (IOException exc) {
      exc.printStackTrace();
    }
  }

首先阅读尝试使用资源,当你使用它时你不需要手动关闭资源(文件,流等),它会为你做。 This 例如。

您不需要在 StringBuffer 中包装读取的行,在这种情况下您不会从中得到任何东西。 另请阅读从 java 文档开始的 String class 提供的方法 - documentation.