4

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?

1 Answer 1

3

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:

Sign up to request clarification or add additional context in comments.

2 Comments

Can you help me understaning this issue? Going by your approach how I can achieve my goal?
Just make sure that the file ends up in the runtime classpath. In Netbeans, that's among others the Java source folder.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.