将文件作为命令行参数传递并读取它的行

问题描述:

这是我在互联网上找到的用于读取文件行并且使用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

... 
// 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 

您的new FileInputStream("textfile.txt")是正确的。如果抛出该异常,则在运行该程序时,当前目录中不存在textfile.txt。您确定该文件的名称实际上不是testfile.txt(请注意s,而不是x,位于第三位)。


题外话:但是你刚才删除的问题问到如何逐行读取一个文件行(我不认为你需要将其删除,FWIW)。假设你仍然是初学者并且掌握了一些东西,一个指针:你可能不需要想要使用FileInputStream,这是针对二进制文件,而是使用Reader套接口/类在java.io (包括FileReader)。另外,只要有可能,即使在将它们初始化为特定类时,也可以使用接口声明变量,例如,Reader r = new FileReader("textfile.txt")(而不是FileReader r = ...)。

当您刚刚指定"textfile.txt"时,操作系统将在程序的工作目录中查找该文件。

您可以指定与一些文件的绝对路径类似new FileInputStream("C:\\full\\path\\to\\file.txt")

另外,如果你想知道你的程序在运行的目录,试试这个: System.out.println(new File(".").getAbsolutePath())