How to read .sql files internally in Java jar? - java

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.

Related

How to get file path in Java from executable JAR

I need to pass the file path to a function of an external class which uses it in the following way:
byte[] keyBytes = Files.readAllBytes((new File(pathname)).toPath());
The class cannot be edited otherwise I would have used this method to read the file ->
InputStream inputStream = getClass().getResourceAsStream("/file_name.xyz");
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
When running the code locally, it's able to retrieve the file but when the JAR is deployed on cloud it's failing to find it.
Currently I have pasted the file at src/main/resources but I can shift it to any other folder also. Just need to pass the path so that the function reads it.
Can someone help me with this? I'm stuck on it from couple of days

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.

File doesn't read after creating jar using netbeans

i have a small application which checks for values from a file and display the result in a jframe.
A file contain list of word to check. this file is placed in project folder "testing" and the main source testing.java file is present in location "testing\src\testing"
input file : c:\document..\netbeans\testing\
java file : c:\document..\netbeans\testing\src\testing\
when i place the input file inside folder "c:\document..\netbeans\testing\src\testing\
" the input file is not taken as input, it works only when kept on folder "c:\document..\netbeans\testing\"
so when a jar file is created it has not included the input file in that, even i manually input that is not taking the input file in and working.
some path setting issue? what can be done to solve this issue?
any help pls??
Once you create the jar, the file becomes an embedded resource. If you try to read it as a File it will no long be the same file system path as you originally use in the program. It must now be read from the class path.
To read the file from the class path, you will want to use getClass().getResourceAsStream(), which return an InputStream. If your file is in the same location (package) as your class file, then you should use
InputStream is = getClass().getResourceAsStream("input.txt");
Then you can read from the InputStream
BufferedReader reader = new BufferedReader (new InputStreamReader(is));
This generally happens, when you don't use absolute path...!
As when you run your program from IDE(Netbeans) then the HOME_FOLDER is your ProjectFolder. Relative to which you would have given the file_path(that has to be accessed in your program).
But after building, jar is present in ProjectFolder/dist. When you run the jar file the HomeFolder is not ProjectFolder rather it is ProjectFolder/dist.
So, to make it successful, to need to copy all files and folders from ProjectFolder/dist to ProjectFolder.
Then run the jar.. Hope it will fix the issue
Try putting double backslashes in your file paths. Like this:
c:\\document..\\netbeans\\testing\\src\\testing\\
This is the format that java normally requires it to be in

Where to place a file within a Java Web Project?

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.

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