Where to place a file within a Java Web Project? - java

I have a small java program that reads a file in, in eclipse i have the file in the main project dir and the class file is within the src dir. This works fine.
I want to you this small piece of code within a web project im working on, currently i have the class file in src/tools/, but im lost on where to put the file?
I have tried it in a few places yet it throws file not found.
Where is the best place to store this file? and how can i ensure i have the right path when using the following code?
FileInputStream fstream = new FileInputStream("file.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));

You either need to load the file as a resource (e.g., getResourceAsStream(), use a path relative to the app (getRealPath()), or put it in an absolute location and use a full path.

If you put the resource file in the root of your classpath (so if your source path for java files is src/main/java then put the resource file in there) then you can do this.
BufferedReader br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("myresource.txt")));
Now if you want you can put it in a package, so the file would be in src/main/java/com/sksamuel
BufferedReader br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("com/sksamuel/myresource.txt")));
Finally, if you're using maven or something similar, then you would put the file into src/main/resources and not src/main/java, and at compile time the two paths are combined, so you would use the same code as above.
My answer assumes the file will be packaged up with your java code and is something that would change by a developer. If it's generated, or needs to be changed outside the jar/war then this isn't the best way.

Related

File can find the file but FileReader can't

I am trying to read a .txt file in java.
I placed the file in the root folder of the project.
When I do this:
URL url = getClass().getResource("/test.txt");
System.out.println(url);
File file = new File(url.getPath());
System.out.println(file.getAbsolutePath());
I get the correct path back.
But when i want to use the File in a FileReader it can't find the file.
Scanner scan = new Scanner(new BufferedReader(new FileReader(file)));
Even when I place a test file on my desktop and use a absolut path the FileReader can't find the file.
I don't know what to do, I have tried a lot of stuff.
Can someone help me.
Resources (Class.getResource) cannot generally be dealt with File, they are files on the class path, possibly packed in a .jar file. You can get a reader as follows:
new InputStreamReader(getClass().getResourceAsStream("/test.txt"), StandardCharsets.UTF_8)
The above uses an InputStream of the resource. As you know the Charset of the file, specify it for a Reader.
That it worked was a working directory issue in combination with your IDE's settings.
There are two things to try here:
Use the full path instead of using a relative path use the full path e.g. something like "/Users/BlueDragon709/Desktop/test.txt" instead of "/test.txt"
If that fails check the file permissions.
When you are currently using File you aren't attempting to access it until you instantiate the Scanner so it not going to fail until you hit that line of code.

How to read .sql files internally in Java jar?

I currently have a folder of schema files in SQL that get executed when the application is executed. This is what I use to read and execute these files:
private static String getSchemaFromFile(String filename) throws IOException {
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new FileReader("src/schema/" + filename + ".sql"));
String queryString;
.....
}
The problem I think is to do with the path of the schema folder. I tried looking at getResourceAsStream but I can't seem to get it working.
It works fine when I run from eclipse but when I compile it into a JAR it says file not found. How do I ensure the path is correct?
Something along these lines. BTW this will probably fail unless you are running your jar (executing it in eclipse probably won't work).
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("src/schema/" + filename + ".sql")));
From eclipse it works because eclipse enable java code to search from src/schema/ directory.But when you are using jar it requires an absolute path.
I will suggest store the absolute path where you place your .sql file in a property file so that you can change whenever you need it.Suppose you from property file you have get the location absolutePath. Then you can do this -
BufferedReader bufferedReader = new BufferedReader(new FileReader(absolutePath + filename + ".sql"));
If the schema is in a jar file, then src/schema is probably not valid, more likely it will be in schema/. First you need to confirm this. The jar file is actually a zip file, so you can unzip it with utility like winzip to examine the contents.
Once confirmed where the schema files are located, they cannot be accessed using FileReader, as they are not in the file system but inside your jar. To access a file from within the jar file, getResourceAsStream is the correct approach. You probably defined the wrong folder when you tried it last time.

Modifying BufferedWriter argument in order to make JAR file

I am using BufferedReader and BufferedWriter in a progect in order to export it as Jar and use it,
My code using the streams is the following
br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/data/score.scr")));
bw= new BufferedWriter(new FileWriter("src/data/score.scr"));
I tried to use getClass().getResourceAsStream(); inside BufferedWriter but it doest work, the program works well but it seems ... that the file read is not the one written ... I save a score (BufferedWriter) when I get to the scorepanel (BufferedReader) it is not there
all this in order to export my project as a JAR so I need to modify the second line of my core
In general you cannot write inside a jar file but here is a more detailed answer How can my Java program store files inside of its .jar file?
You could try using your IDE to do this.
eclipse
or through command line
jar cf jar-file input-file(s)
From what it looks like your doing, you don't necessarily need to store data in the jar itself. Just write the data to the same directory or folder as your jar and have your user transfer the entire folder as part of your program.

Java getting file as resource when it's in the project folder

I currently have a project in Java set up with the following directory structure in Eclipse:
And in my code I have the following lines:
InputStream is = this.getClass().getClassLoader().getResourceAsStream("resources/config");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
However, the InputStream is always gets assigned to null, which causes a crash when it gets to the second line. I know it has something to do with how I set up the path that it's looking for, but I can't figure out exactly why it isn't working.
Your config file is in your project, somewhere on the file system.
However, Eclipse isn't putting it on the classpath. To force it to be on the classpath, right click your folder and add it as a source folder. Eclipse will then add it to the root of the classpath. You can retrieve it with
InputStream is = this.getClass().getResourceAsStream("/config");
Eclipse puts everything in resources source folder starting at the root of the classpath. Therefore
resources/config
will appear in classpath as
/config
/qbooksprintfix/FileChecker
/qbooksprintfxi/FilePurgeHandler
/...
Try whit InputStream is = this.getClass().getClassLoader().getResource("/resources/config").openStream();
or InputStream is = this.getClass().getClassLoader().getResourceAsStream("/resources/config");
In both cases make sure to put "/" before the "resources"

Where does Java put resource files when I JAR my program?

Been looking for this for the past 2 hours and can't find anything (I've found solutions to the same problem but with images, not text files).
Pretty much, I made a program that reads a text file. The file is a list of names and IDs. Using Eclipse, I put the file in my src folder and in the program put the path file to it. Like this:
in = new BufferedReader(new FileReader(curDir+"\\bin\\items.txt"));
Where curDir is the user's current directory (found with System.getProperty("user.dir")).
Now, problem is, the program runs fine when I run it from Eclipse, but when I try to make it a runnable JAR and then run it, the program runs, but the info from the text file does not load. It look like Eclipse is not putting the text file with the JAR.
EDIT: Solved-ish the problem? So the JAR file needs to the in a folder with all the original files? I am so confused, what is a JAR file then?
A more robust way to get a file whether you are running from Eclipse or a JAR is to do
MyClass.getResource("items.txt")
where MyClass is a class in the same package (folder) as the resource you need.
If Eclipse is not putting the file in your JAR you can go to
Run -> Run Configurations -> -> Classpath tab -> Advanced -> Add Folders
Then add the folder containing your file to the classpath. Alternatively, export the Ant script and create a custom build script.
To the point, the FileReader can only read disk file system resources. But a JAR contains classpath resources only. You need to read it as a classpath resource. You need the ClassLoader for this.
Assuming that Foo is your class in the JAR which needs to read the resource and items.txt is put in the classpath root of the JAR, then you should read it as follows (note: leading slash needed!):
InputStream input = Foo.class.getResourceAsStream("/items.txt");
reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
// ...
Or if you want to be independent from the class or runtime context, then use the context class loader which operates relative to the classpath root (note: no leading slash needed!):
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("items.txt");
reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
// ...
(UTF-8 is of course the charset the file is encoded with, else you may see Mojibake)
Get the location of your jar file
Firstly create a folder(say myfolder) and put your files inside it
Consider the following function
public String path(String filename)
{
URL url1 = getClass().getResource("");
String ur=url1.toString();
ur=ur.substring(9);
String truepath[]=ur.split("myjar.jar!");
truepath[0]=truepath[0]+"myfolder/";
truepath[0]=truepath[0].replaceAll("%20"," ");
return truepath[0]+filename;
}//This method will work on Windows and Linux as well.
//You can alternatively use the following line to get the path of your jar file
//classname.class.getProtectionDomain().getCodeSource().getLocation().getPath();
Suppose your jar file is in D:\Test\dist
Then path() will return /D:/Test/dist/myfolder/filename
Now you can place 'myfolder' inside the folder where your jar file is residing
OR
If you want to access some read-only file inside your jar you should copy it to one
of your packages and can access it as
yourClassname.getResource("/packagename/filename.txt");

Categories

Resources