在Java中讀取文件時遇到一些問題。在讀取java文件時遇到問題
文件看起來像什麼:
Answer 1:
1. This is an apple
2. Something
Answer 2:
1. This is a cool website
2. I love banana
3. This is a table
4. Programming is fun
Answer 3.
1. Hello World
....
我想要做的就是他們分成兩個項目: 一個是回答數字;另一個是答案列表。
因此,假設我有一個對象類叫做答案: 答案號字符串 回答列表。
這是我迄今所做的調試我的代碼,我把它放到對象類之前。但我無法得到正確的結果
public void reader(String file) throws FileNotFoundException, IOException {
FileReader fR = new FileReader(file);
BufferedReader bR = new BufferedReader(fR);
String line = null;
int count = 0 ;
String blockNum = "";
String printState = "" ;
while ((line = bR.readLine()) != null) {
if(line.contains("Answer")){
//System.out.println("Contain Answer statement: " + line);
count++;
blockNum = line;
printState = "";
}
else{
//System.out.println("No Answer Statement: " + line);
printState += line + "/" ;
}
System.out.println(count + " " + blockNum + " " + printState);
}
// Close the input stream
bR.close();
fR.close();
}
我很確定我在編碼時做了一些愚蠢的事情。我不太清楚如何閱讀它,以便它將它分開。
現在輸出看起來是這樣的:
1 Answer 1:
1 Answer 1: 1. This is an apple/
1 Answer 1: 1. This is an apple/2. Something/
2 Answer 2:
2 Answer 2: 1. This is a cool website/
2 Answer 2: 1. This is a cool website/2. I love banana/
2 Answer 2: 1. This is a cool website/2. I love banana/3. This is a table/
2 Answer 2: 1. This is a cool website/2. I love banana/3. This is a table/4. Programming is fun/
3 Answer 3.
3 Answer 3. 1. Hello World/
但我所要的輸出是這樣的:
1 Answer 1: 1. This is an apple/2. Something/
2 Answer 2: 1. This is a cool website/2. I love banana/3. This is a table/4. Programming is fun/
3 Answer 3. 1. Hello World/
您可能希望將讀取內容輸出到Map中。 –
Vulcan