2013-04-06 44 views
1

现在我有这样的错误:在线程 “主要” java.lang.ArrayIndexOutOfBoundsException读取文件从电脑

例外:4 在Lotto1.main(Lotto1.java:37)

37号线:arr [count] [0] = s.next()+“”+ s.next();

import java.io.*; 
import java.util.*; 

public static void main(String[] args) throws IOException { 

     File f = new File("D:\\Filipe\\Project Final\\src\\database_lotto.txt"); 
     Scanner s; 
     try { 
      s = new Scanner(f); 

      BufferedReader reader = new BufferedReader(new FileReader(f)); 
      int lines = 0; 
      while (reader.readLine() != null) { 
       lines++; 
      } 
      reader.close(); 

      arr = new String[lines][3]; 

      int count = 0; 
      //while theres still another line 
      while (s.hasNextLine()){ 
       arr[count][0] = s.next() + ""+ s.next(); 
       arr[count][1] = s.next(); 
       arr[count][2] = s.next(); 
       count++;     
      } 
     } catch (FileNotFoundException ex) { 
      System.out.println("File does not exist"); 
     } 
+1

将文件放在同一个文件夹,从你在哪里运行代码或将文件传递给文件读取器而不是文件的名称......所以'BufferedReader reader = new BufferedReader(new FileReader(f));' – 2013-04-06 17:46:46

+0

你为什么要读取看起来像相同的文件两次,并以两种不同的方式(扫描仪和FileReader)? – 2013-04-06 17:50:14

+0

@PaulGrime从技术上讲,他试图读取一个并打开另一个:D – 2013-04-06 17:50:54

回答

2

你没有把正确的路径进入的FileReader只进文件F,你可以通过˚F到的FileReader而不是重复的路径:

File f = new File("D:\\database_lotto.txt"); 
[...] 
BufferedReader reader = new BufferedReader(new FileReader(f)); 
+0

我改变了它现在我有另一个错误:线程“main”java.lang.ArrayIndexOutOfBoundsException中的异常:4在Lotto1.main(Lotto1.java:37) 37行:arr [count] [0] = s.next() +“”+ s.next(); – user1831131 2013-04-06 18:08:27

+0

每次调用“s.next()”时,都会导致内部的“line-index”可能导致错误,您应该只在每次调用“s.next() – 2013-04-06 18:11:47

+0

我改了它,仍然是同样的问题:( – user1831131 2013-04-06 18:19:28