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

this is the code that I found on the Internet to read the lines of a file, and I also use eclipse, and I passed the file name as SanShin.txt in the argument field. but he will print:

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

the 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. thank

+3
source share
3 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
+11
source

Your new FileInputStream("textfile.txt")correct. If this is an exception, it is not in the current directory textfile.txtwhen the program starts. Are you sure that the file name is not in fact testfile.txt(pay attention to s, not x, in the third position).


. , ( , , 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")

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

+1
source

Source: https://habr.com/ru/post/1777418/


All Articles