Question

I want to add a text file as resource in a Java web application. I am using Netbeans as IDE.
I want to keep a file in a folder such that I can directly refer the file rather then a ABSOLUTE path.

FileInputStream fstream = new FileInputStream("resource.txt");

Where to keep that file in folder?

Was it helpful?

Solution

Relying on relative file paths is a bad idea as they are dependent on the current working directory (the currently opened directory when the Java application is been started) and you have no control over the current working directory from inside the Java application.

You should rather just put it in the classpath and get it from the classpath:

InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("resource.txt");
// ...

The above example assumes that the file is placed in classpath root. If it's in for example the package com.example.resources, then you should get it as follows:

InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("com/example/resources/resource.txt");
// ...

If the file is supposed to be editable, then you should really use an absolute disk file system path instead and document it properly in the installation guide of your web application. An alternative is to use a database.

See also:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top