2013-04-06 77 views
0

我試圖從與源代碼位於同一文件夾的計算機讀取文件,並在運行代碼時說:文件不存在 您能幫助我嗎?從主機讀取文件

import java.io.*; 
import java.util.*; 
public class Lotto1 { 
    static String[][] arr; 
    static String name, number; 
    public static void main(String[] args) throws IOException { 
    File f = new File("D:\\Filipe\\Project Final\\src\\database_lotto.txt.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"); 
    } 
+4

database_lotto.txt.txt?你確定它不應該是database_lotto.txt? – stevenelberger 2013-04-06 22:39:43

+1

是不是這個問題 - http://stackoverflow.com/questions/15854085/reading-a-file-from-the-computer – 2013-04-06 22:43:21

+0

即使與database_lotto.txt這是同樣的問題。 – user1831131 2013-04-06 22:44:05

回答

0

我推測你正在嘗試做什麼並重新編碼它,但是如果這個實現是你說的地方,這個實現將讀取這個文件。

public static void main(String[] args) { 
    final String filename = "database_lotto.txt"; 
    final File lottoFile = new File(filename); 

    try (final Scanner scanner = new Scanner(lottoFile)) { 
     final List<String[]> storage = new ArrayList<String[]>(); 
     while (scanner.hasNextLine()) { 
      storage.add(scanner.nextLine().split(" ")); 
     } 
    }catch (FileNotFoundException ex) { 
     System.out.println("File not found :("); 
    } 
} 
0

你在Unix/Linux機器上嗎?

這是更好地使用文件分割符,而不是\,因爲文件分割符使用系統字符的目錄(\在Win,/在Linux等)

使用File.exists()來檢查如果有文件,在使用之前。

+0

**我正在使用Win7 ** – user1831131 2013-04-06 23:21:30

+0

然後雙反斜槓應該可以工作。因此,你的路徑似乎不正確。 – 2013-04-06 23:23:45

+0

**它沒有工作:(** – user1831131 2013-04-06 23:38:38