[英]How do I read a 2D array as it is from a .txt file?
我有以下格式和內容的 this.txt 文件(注意空格):
Apples 00:00:34
Jessica 00:01:34
Cassadee 00:00:20
我想將它們存儲到二維數組 ( holder[5][2]
) 中,同時將它們 output 存儲到JTable
中。 我已經知道如何在 java 中寫入和讀取文件,並將讀取的文件放入數組中。 但是,當我使用此代碼時:
try {
FileInputStream fi = new FileInputStream(file);
DataInputStream in = new DataInputStream(fi);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line = null;
while((line = br.readLine()) != null){
for(int i = 0; i < holder.length; i++){
for(int j = 0; j < holder[i].length; j++){
holder[i][j] = line;
}
}
}
in.close();
} catch(Exception ex) {
ex.printStackTrace();
}
我的holder[][]
數組輸出效果不如 JTable:| 請幫助? 感謝誰能幫助我!
編輯:也可以用Scanner
來做到這一點嗎? 我更了解掃描儀。
你需要的是這樣的:
int lineCount = 0;
int wordCount = 0;
String line = null;
while((line = br.readLine()) != null){
String[] word = line.split("\\s+");
for(String segment : word)
{
holder[lineCount][wordCount++] = segment;
}
lineCount++;
wordCount = 0; //I think now it should work, before I forgot to reset the count.
}
請注意,此代碼未經測試,但它應該能為您提供大致的思路。
編輯: \\s+
是一個正則表達式,用於表示一個或多個空白字符,無論是空格還是制表符。 從技術上講,正則表達式只是\s+
但我們需要添加一個額外的空格,因為\
是一個轉義字符 Java,因此您需要轉義它,因此需要額外的\
。 加號只是表示一個或多個的運算符。
第二次編輯:是的,您也可以像這樣使用Scanner
執行此操作:
Scanner input = new Scanner(new File(...));
while ((line = input.next()) != null) {...}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.