簡體   English   中英

BufferedReader 多行作為一個字符串

[英]BufferedReader multiple lines as one String

我正在嘗試將文件中的多行作為字符串讀取到 ArrayList 中。

我的目標是讓程序一行一行地從文件中讀取,直到讀者看到一個特定的符號( -在這種情況下)並將這些行保存為一個字符串。 下面的代碼使每一行成為一個新字符串,稍后將其添加到列表中。

BufferedReader br = null;
br = new BufferedReader(new FileReader(file));
String read;
while ((read = br.readLine()) != null) {
    String[] splited = read.split("-");
    carList.add(Arrays.toString(splited));
}
for (String carList2 : carList) {
    System.out.println(carList2);
    System.out.println("x");
}

首先,您需要檢查讀取行是否包含“-”。

  • 如果沒有,則將該行與之前的行連接起來。
  • 如果是,則僅將行的第一部分與前一行連接起來。

這是一個快速實現:

BufferedReader br = null;
br = new BufferedReader(new FileReader(file));
String read;
String concatenatedLine = "";
while ((read = br.readLine()) != null) {
    String[] splited = read.split("-");
    // if line doesn't contains "-", splited[0] and read are equals
    concatenatedLine += splited[0]; 
    if (splited.length > 1) {
        // if read line contains "-", there will be more than 1 element
        carList.add(Arrays.toString(splited)); // add to the list
        // store the second part of the line, in order to add it to the next ones
        concatenatedLine = splited[1];
    }
}

請注意,如果一行包含多個-則輸出可能不是預期的。

此外,使用+連接 String 並不是最好的方法,但我讓您了解更多相關信息。

我不太清楚你想要的輸出是什么。 如果您希望每個客戶都在一個沒有“-”的字符串上,那么您可以嘗試以下代碼:

while ((read = br.readLine()) != null) {
String splited = read.replace("-", " ");
carList.add(splited);
   }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM