开发者

Passing a file as a command line argument and reading its lines

this is the code that i have found in the internet for reading the lines of a file and also I use eclipse and I passed the name of files as SanShin.txt in its argument field. but it will print :

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

Code:

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;
            /开发者_JAVA百科/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());
            }


    }
}

please help me why it prints this error. thanks


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


When you just specify "textfile.txt" the operating system will look in the program's working directory for that file.

You can specify the absolute path to the file with something like new FileInputStream("C:\\full\\path\\to\\file.txt")

Also if you want to know the directory your program is running in, try this: System.out.println(new File(".").getAbsolutePath())


Your new FileInputStream("textfile.txt") is correct. If it's throwing that exception, there is no textfile.txt in the current directory when you run the program. Are you sure the file's name isn't actually testfile.txt (note the s, not x, in the third position).


Off-topic: But your earlier deleted question asked how to read a file line by line (I didn't think you needed to delete it, FWIW). On the assumption you're still a beginner and getting the hang of things, a pointer: You probably don't want to be using FileInputStream, which is for binary files, but instead use the Reader set of interfaces/classes in java.io (including FileReader). Also, whenever possible, declare your variables using the interface, even when initializing them to a specific class, so for instance, Reader r = new FileReader("textfile.txt") (rather than FileReader r = ...).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜