【问题标题】:Simplest way to concatenate multi lines of text in java through File Handling通过文件处理在java中连接多行文本的最简单方法
【发布时间】:2022-01-23 15:27:15
【问题描述】:

我尝试在给定的文本文件中连接 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

【问题讨论】:

  • 你的输入有空格吗?
  • 是的,它有两行文字
  • 里面有空格?为什么要拆分空间并重新组装字符串?
  • String result = Files.readString(Path.of(...)).replace("\n", ""); 如果没有。 replaceAll("[ \n]+", "") 如果有的话。

标签: java string concatenation filereader file-handling


【解决方案1】:

如果您使用的是 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()。

【讨论】:

    【解决方案2】:

    简答,有:

      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 doc 开头的 String 类提供的方法 - documentation。

    【讨论】:

      猜你喜欢
      • 2015-03-13
      • 2012-09-11
      • 2010-09-23
      • 2016-08-03
      • 2017-03-10
      • 1970-01-01
      • 1970-01-01
      • 2014-05-16
      • 1970-01-01
      相关资源
      最近更新 更多