2008-11-20 94 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);