Skip to content
Advertisement

How to pass a text file as a argument?

Im trying to write a program to read a text file through args but when i run it, it always says the file can’t be found even though i placed it inside the same folder as the main.java that im running. Does anyone know the solution to my problem or a better way of reading a text file?

Advertisement

Answer

Do not use relative paths in java.io.File.

It will become relative to the current working directory which is dependent on the way how you run the application which in turn is not controllable from inside your application. It will only lead to portability trouble. If you run it from inside Eclipse, the path will be relative to /path/to/eclipse/workspace/projectname. If you run it from inside command console, it will be relative to currently opened folder (even though when you run the code by absolute path!). If you run it by doubleclicking the JAR, it will be relative to the root folder of the JAR. If you run it in a webserver, it will be relative to the /path/to/webserver/binaries. Etcetera.

Always use absolute paths in java.io.File, no excuses.

For best portability and less headache with absolute paths, just place the file in a path covered by the runtime classpath (or add its path to the runtime classpath). This way you can get the file by Class#getResource() or its content by Class#getResourceAsStream(). If it’s in the same folder (package) as your current class, then it’s already in the classpath. To access it, just do:

public MyClass() {
    URL url = getClass().getResource("filename.txt");
    File file = new File(url.getPath());
    InputStream input = new FileInputStream(file);
    // ...
}

or

public MyClass() {
    InputStream input = getClass().getResourceAsStream("filename.txt");
    // ...
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement