【发布时间】: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