Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 828
user472221 Avatar asked Dec 08 '22 00:12

user472221


2 Answers

...
// 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
like image 73
khachik Avatar answered Dec 09 '22 14:12

khachik


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())

like image 32
daveb Avatar answered Dec 09 '22 13:12

daveb