2016-07-22 30 views
0

我是Java初學者,我試圖從現有的文本文件中讀取一個程序。我已經盡力了,但它仍然在說「File Not Found!」。我已將我的「Test.txt」複製到我的包的兩個文件夾 - src和bin。 請幫助我解決這個問題。我會非常感謝。這裏的代碼 -閱讀Java中現有的文本文件

package readingandwritingfiles; 
import java.io.*; 

public class ShowFile { 

    public static void main(String[] args) throws Exception{ 
     int i; 
     FileInputStream file_IN; 
     try { 
      file_IN = new FileInputStream(args[0]); 
     } 
     catch(FileNotFoundException e) { 
      System.out.println("File Not Found!"); 
      return; 
     } 
     catch(ArrayIndexOutOfBoundsException e) { 
      System.out.println("Usage: ShowFile File"); 
      return; 
     } 
     do { 
      i = file_IN.read(); 
      if(i != -1) 
       System.out.print((char)i); 
     } while(i != -1); 
     file_IN.close(); 
     System.exit(0); 
    } 

} 
+0

它看起來像程序試圖在'args [0]'中找到文件 - 當你運行程序時,你有文件路徑/名稱作爲命令行參數嗎? –

+0

它似乎是通過命令行參數'(args [0])'得到文件的名稱'..你在用什麼IDE? – XDProgrammer

+0

您必須將文件名作爲第一個參數。如果您使用IDE,請檢查傳遞參數的方式。 – Elvermg

回答

0

如果你只是把Test.txt,然後程序正在項目的根文件夾中查找。例如: 項目 -src --package ---類 -bin -Test.txt Test.txt的需要在同一個目錄src和垃圾桶,裏面沒有他們

+0

我在包的src文件夾中添加了「Test.txt」,因爲它也是包含「ShowFile.java」和「ShowFile.class」。但是當我在bin文件夾中添加文件時,這些程序正常工作。謝謝! –

0

山口的字符串(或文件)與相對路徑到您的項目文件夾(如果你有你的文件在src文件夾中,這個應該是「src/Test.txt」,而不是「Test.txt」)。

對於讀取文本文件,您應該使用FileReader和BufferedReader,BufferedReader有讀取完成行的方法,您可以閱讀,直到找到null。

一個例子:

String path = "src/Test.txt"; 
try { 
    FileReader fr = new FileReader(path); 
    BufferedReader br = new BufferedReader(fr); 
    String line = br.readLine(); 
    while(line != null) { 
     System.out.println(line); 
     line = br.readLine(); 
    } 
    br.close(); 
} catch (Exception ex) { 
} 
+0

這是另一種方式來做到這一點。謝謝! –

0

如果你的文件夾結構是這樣的(src文件夾內的文件──test.txt文件)

+src 

     +Text.txt 

然後使用此代碼

 ClassLoader classLoader = ShowFile.class.getClassLoader(); 
     File file = new File(classLoader.getResource("Text.txt").getFile()); 
     file_IN = new FileInputStream(file); 

或者如果你的folde [R結構是這樣的

+src 

     +somepackage 

       +Text.txt 

然後用這個代碼的方式

 ClassLoader classLoader = ShowFile.class.getClassLoader(); 
     File file = new File(classLoader.getResource("/somepackage/Text.txt").getFile()); 
     file_IN = new FileInputStream(file); 
0

噸做到這一點!我注意到你指定了args [0],爲什麼?

// Java Program to illustrate reading from Text File 
// using Scanner Class 
import java.io.File; 
import java.util.Scanner; 
public class ReadFromFileUsingScanner 
{ 
    public static void main(String[] args) throws Exception 
    { 
    // pass the path to the file as a parameter 
    File file = 
     new File("C:\\Users\\test.txt"); 
    Scanner sc = new Scanner(file); 

    while (sc.hasNextLine()) 
     System.out.println(sc.nextLine()); 
    } 
}