2008-11-20 95 views
13
File fil = new File("Tall.txt"); 
FileReader inputFil = new FileReader(fil); 
BufferedReader in = new BufferedReader(inputFil); 

int [] tall = new int [100]; 

String s =in.readLine(); 

while(s!=null) 
{ 
    int i = 0; 
    tall[i] = Integer.parseInt(s); //this is line 19 
    System.out.println(tall[i]); 
    s = in.readLine(); 
} 

in.close(); 

我想用文件「Tall.txt」將它們中包含的整數寫入名爲「tall」的數組中。爲此,它會在一定程度上,也當我運行它,它會引發以下異常(?:Java:從一個文件讀取整數到一個數組

Exception in thread "main" java.lang.NumberFormatException: For input string: "" 
    at java.lang.NumberFormatException.forInputString(Unknown Source) 
    at java.lang.Integer.parseInt(Unknown Source) 
    at java.lang.Integer.parseInt(Unknown Source) 
    at BinarySok.main(BinarySok.java:19) 

正是它爲什麼這樣做,我怎麼刪除它,因爲我看到它,我讀了文件作爲字符串,然後將其轉換爲整數,這是不是非法

+0

BTW,你應該宣佈 「我」 之外while循環。如果不是,您將總是在您的數組的索引0處插入整數。 – 2008-11-20 01:23:45

+1

順便說一句,評論「這是第19行」是「有史以來最佳評論」的候選人。你正在使用什麼IDE? – 2009-04-27 08:28:50

+0

我完全不知道那是怎麼到的。我想我從某個地方拿走了部分代碼,顯然這些評論來了。很可能是 – Northener 2009-05-10 04:12:05

回答

9

您必須在您的文件中的空行

您可能希望在一個「嘗試」塊來包裝你parseInt函數調用。:

try { 
    tall[i++] = Integer.parseInt(s); 
} 
catch (NumberFormatException ex) { 
    continue; 
} 

或s解析之前暗示支票空字符串:

if (s.length() == 0) 
    continue; 

注意,通過初始化索引變量i內循環,它始終爲0。您應該while循環之前移動的聲明。 (或使它成爲for循環的一部分。)

+1

,它是文件的最後一行。 – 2008-11-20 00:25:12

2

它看起來像Java試圖將空字符串轉換爲數字。在這一系列數字的末尾是否有空行?

你也許可以解決這樣的

String s = in.readLine(); 
int i = 0; 

while (s != null) { 
    // Skip empty lines. 
    s = s.trim(); 
    if (s.length() == 0) { 
     continue; 
    } 

    tall[i] = Integer.parseInt(s); // This is line 19. 
    System.out.println(tall[i]); 
    s = in.readLine(); 
    i++; 
} 

in.close(); 
1

代碼,您可能具有不同的行結束符之間的混亂。 Windows文件將以回車符和換行符結束每行。 Unix上的某些程序會讀取該文件,就好像它在每行之間有一個額外的空白行一樣,因爲它會將回車視爲行尾,然後將換行看作行的另一行。

40

你可能想要做這樣的事情(如果你在Java 5中&起來是)

Scanner scanner = new Scanner(new File("tall.txt")); 
int [] tall = new int [100]; 
int i = 0; 
while(scanner.hasNextInt()){ 
    tall[i++] = scanner.nextInt(); 
} 
3

爲了便於比較,這裏是另一種方式來讀取文件。它有一個好處,你不需要知道文件中有多少個整數。

File file = new File("Tall.txt"); 
byte[] bytes = new byte[(int) file.length()]; 
FileInputStream fis = new FileInputStream(file); 
fis.read(bytes); 
fis.close(); 
String[] valueStr = new String(bytes).trim().split("\\s+"); 
int[] tall = new int[valueStr.length]; 
for (int i = 0; i < valueStr.length; i++) 
    tall[i] = Integer.parseInt(valueStr[i]); 
System.out.println(Arrays.asList(tall)); 
0
File file = new File("E:/Responsibility.txt"); 
    Scanner scanner = new Scanner(file); 
    List<Integer> integers = new ArrayList<>(); 
    while (scanner.hasNext()) { 
     if (scanner.hasNextInt()) { 
      integers.add(scanner.nextInt()); 
     } else { 
      scanner.next(); 
     } 
    } 
    System.out.println(integers);