2015-10-27 52 views
0

我的目標是讀取一個簡單的文本文件,並輸出結果。 出於某種原因,即使它位於同一文件夾中,我也會遇到無法找到指定文件的錯誤。我有點難以理解它爲什麼不起作用。while循環讀取文本文件錯誤java

import java.util.Scanner; 
import java.io.File; 
import java.io.IOException; 

class Test 
{ 
    public static void main(String[] args) 
      throws IOException   
    { 
      int number; 
      File inputFile = new File("input.txt"); 
      Scanner file = new Scanner(inputFile); 

      while(file.hasNext()) { 
       number = file.nextInt(); 
       System.out.println(number); 
      } 

      System.out.println("End of file detected"); 
    } 
} 
+0

你確定它在同一個文件夾中。 – 3kings

+2

打印'System.getProperty(「user.dir」);'並查看目錄是否是文件所在的目錄。如果沒有,使用'getAbsolutePath()' – sam

+1

use System.out.println(File.getAbsolutePath());以確保您創建的File對象指向您期望的位置 – ControlAltDel

回答

0

該文件需要立即在您的項目文件夾中。如果它仍然沒有工作,你可以使用絕對路徑代替相對路徑。 像e.g D:\\test.txt

+0

謝謝!我把它放在我的項目文件夾中,它工作。 –

+0

最受歡迎..你可以upvote,如果你想:) – Rehman

+0

我會,但我在這裏是如此新,它不會讓我因爲我的地位。 –

0

你在說哪個文件夾?如果您從Eclipse執行應用程序,則文本文件必須位於.project,.classpath等文件和文件夾所在的目錄中。

+0

我正在使用NetBeans。我將.txt文件放在與.class和.java文件相同的文件夾中。 –

0

這裏有一個方法來選擇一個文件使用圖形JOptionPane

ArrayList<String> lines = new ArrayList<>(); 

JOptionPane.showMessageDialog(null, "Please choose a file");   
JFileChooser input = new JFileChooser(); 
int a = input.showOpenDialog(null); 
String file = ""; 

if (a == JFileChooser.APPROVE_OPTION) { 
    File selectedFile = input.getSelectedFile(); 
    file = selectedFile.getPath(); 
} 

//use file input to read in line one at a time 
FileInputStream fstream = new FileInputStream(file); 
DataInputStream in = new DataInputStream(fstream); 
BufferedReader br = new BufferedReader(new InputStreamReader(in)); 
String line; 
while ((line = br.readLine()) != null) { 
    lines.add(line); 
}