2015-06-20 18 views
0

我正在嘗試讀取文件.txt,其中包含8行商店在不同地區。每行有15個字符。當我運行這段代碼,就在第一行印刷,之後它拋出這樣的:處理FileReader和子字符串

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 10 
    at java.lang.String.substring(String.java:1951) 
String line = ""; 
String region = "", name = ""; 
BufferedReader file = new BufferedReader(new FileReader("Stores.txt")); 
line = file.readLine(); 
while (line != null) { 
    region = line.substring(0, 10); 
    name = line.substring(10); 
    line = file.readLine(); 
    System.out.println("" + region + name); 
} 
file.close(); 

文件:

Montrèal 16890 

New York 27659 

Pittsburg 26657 

California 11201 

Virginia 32945 

Seattle 33981 

Colorado 10345 
+0

請過帳文本文件的內容。 –

+0

你試過調試你的代碼嗎?你確定每行至少包含10個字符嗎?沒有空行(例如在文件末尾)? – Pshemo

+1

你的文件似乎在文本行之間有空行。您需要跳過解析該行的部分。 – Pshemo

回答

2

您不會跳過空行。試試這個:

String line = ""; 
String region = "", name = ""; 
BufferedReader file = new BufferedReader(new FileReader("Stores.txt")); 
line = file.readLine(); 
while (line != null) { 
    if (!line.isEmpty()) { 
     region = line.substring(0, 10); 
     name = line.substring(10); 
     System.out.println("" + region + name); 
    } 
    line = file.readLine(); 
} 
file.close(); 
+0

非常感謝!我不知道有這種方法的字符串。 – Sandra

+1

不客氣。你也可以看一下String.split方法,你可以用它來將你的String分成兩部分而不依賴於具體的位置。例如:line.split(「」);會創建一個包含兩個元素的數組,您的區域和郵政編碼。 –

1

我已經檢查了線的長度串

String line = ""; 
String region = "", name = ""; 
BufferedReader file = new BufferedReader(new FileReader("Stores.txt")); 
line = file.readLine(); 
while (line != null) { 
    if (!line.isEmpty()&&line.length() >= 15) { 
     region = line.substring(0, 10); 
     name = line.substring(10); 
     line = file.readLine(); 
     System.out.println("" + region + name); 
    } 
} 
file.close(); 
+0

這不會起作用,因爲當您遇到空行時,不會讀取下一行。 –

+0

現在我已經檢查了這部分 – Madhan

+0

只要我試圖找到一種方法來專門使用15個或更多字符的行,這也是正確的。感謝馬漢! – Sandra