2010-11-29 70 views
3

這是我在互聯網上找到的用於讀取文件行並且使用eclipse並將文件名稱作爲SanShin.txt的代碼它的論據字段。但它會打印:將文件作爲命令行參數傳遞並讀取它的行

Error: textfile.txt (The system cannot find the file specified) 

代碼:

public class Zip { 
    public static void main(String[] args){ 
     try{ 
      // Open the file that is the first 
      // command line parameter 
      FileInputStream fstream = new FileInputStream("textfile.txt"); 
      BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); 
      String strLine; 
      //Read File Line By Line 
      while ((strLine = br.readLine()) != null) { 
       // Print the content on the console 
       System.out.println (strLine); 
      } 
      //Close the input stream 
      in.close(); 
      }catch (Exception e){//Catch exception if any 
       System.err.println("Error: " + e.getMessage()); 
      } 


    } 
} 

請幫助我,爲什麼它打印此錯誤。 謝謝

+0

我有這樣一個文本文件! ! – user472221 2010-11-29 10:00:43

+0

這也是我的項目的位置:C:\ Documents and Settings \ icc \ workspace \ Hoffman Project – user472221 2010-11-29 10:02:18

回答

11
... 
// command line parameter 
if(argv.length != 1) { 
    System.err.println("Invalid command line, exactly one argument required"); 
    System.exit(1); 
} 

try { 
    FileInputStream fstream = new FileInputStream(argv[0]); 
} catch (FileNotFoundException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 

// Get the object of DataInputStream 
... 

> java -cp ... Zip \path\to\test.file 
1

您的new FileInputStream("textfile.txt")是正確的。如果拋出該異常,則在運行該程序時,當前目錄中不存在textfile.txt。您確定該文件的名稱實際上不是testfile.txt(請注意s,而不是x,位於第三位)。


題外話:但是你剛纔刪除的問題問到如何逐行讀取一個文件行(我不認爲你需要將其刪除,FWIW)。假設你仍然是初學者並且掌握了一些東西,一個指針:你可能不需要想要使用FileInputStream,這是針對二進制文件,而是使用Reader套接口/類在java.io (包括FileReader)。另外,只要有可能,即使在將它們初始化爲特定類時,也可以使用接口聲明變量,例如,Reader r = new FileReader("textfile.txt")(而不是FileReader r = ...)。

1

當您剛剛指定"textfile.txt"時,操作系統將在程序的工作目錄中查找該文件。

您可以指定與一些文件的絕對路徑類似new FileInputStream("C:\\full\\path\\to\\file.txt")

另外,如果你想知道你的程序在運行的目錄,試試這個: System.out.println(new File(".").getAbsolutePath())