我嘗試在給定的文本檔案中連接 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
uj5u.com熱心網友回復:
如果您使用的是 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()。
uj5u.com熱心網友回復:
簡短的回答,有:
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();
}
}
首先閱讀資源嘗試,當您使用它時,您不需要手動關閉資源(檔案,流等),它會為您完成。比如這個。
您不需要在 StringBuffer 中包裝讀取行,在這種情況下您不會從中得到任何東西。另請閱讀從 java doc- documentation開始的 String 類提供的方法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/419853.html
標籤:
下一篇:帶前導零的編號字串到Int
