Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a text file as a argument?

Tags:

java

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?

like image 641
Victor Avatar asked Jul 22 '10 14:07

Victor


3 Answers

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");
    // ...
}
like image 64
BalusC Avatar answered Oct 31 '22 17:10

BalusC


Try giving an absolute path to the filename.

Also, post the code so that we can see what exactly you're trying.

like image 23
chimeracoder Avatar answered Oct 31 '22 17:10

chimeracoder


When you are opening a file with a relative file name in Java (and in general) it opens it relative to the working directory.

you can find the current working directory of your process using

String workindDir = new File(".").getAbsoultePath()

Make sure you are running your program from the correct directory (or change the file name so that it will be relative to where you are running it from).

like image 32
Omry Yadan Avatar answered Oct 31 '22 17:10

Omry Yadan