Java does not find sql file - java

I have a Java application that uses SQLite as a Database. I want to execute some setup queries that are stored in a file called "setup.sql".
I call the following code to read the file:
BufferedReader reader = new BufferedReader(new
FileReader(Resources.SETUP.file)))
Resources.SETUP.file is an enum that stores the file paths, in this case to "sql/setup.sql" located in the resources folder of my project.
I use this scheme for other files like images and localization, which works perfectly, like the following example for the logo image (Enum is "images/logo.png"):
Image logoImage = new Image(Resources.LOGO.file);
However with the sql file I always get a FileNotFoundException.
Am I using the Readers incorrectly?
The following does not work:
getClass().getResource(Resources.SETUP.file); -> InvocationTargetException
getClass().getClassLoader().getResource(Resources.SETUP.file); -> FileNotFoundException

Related

Cannot Construct An Image Object With Relative File Path WIthout Using file: Prefix

I have been trying to create an image object like this:
Image img = new Image("images/jack.png");
or
Image img = new Image("jack.png");
or /jack.png or /images/jack.pngetc.
I have looked up the working directory using System.getProperty("user.dir") and it is indeed where I put my image file. When I use file: prefix, it does work, like so:
Image img = new Image("file:images/jack.png");
However, it is also supposed to work without using it. In the textbook it is done without file:. I've seen other codes that work without it.
At the end of a bunch of chained exceptions, it says:
Caused by: java.lang.IllegalArgumentException: Invalid URL or resource not found
I also tried to read source code from OpenJDK and I could figure anything out because many methods were native and from what I traced I didn't understand how it didn't work. Also, I can create files the same way, I just can't create images. For instance, this works:
File file = new File("fileName.txt");
What causes this problem, what should I do to fix it?
I'm using NetBeans, if that matters.
Note that System.getProperty("user.dir") does not return the working directory. It returns the user directory.
A path relative to the working directory can be specified using a relative file path in the File constructor. However it's bad practice to rely on the working directory. Starting the application from NetBeans results in the working directory being the project directory, but this is not the case, If started in a different way.
Images you need in your application should therefore be added to the jar.
In this case you can retrieve the image URL via Class.getResource(). (convert to String using toExternalForm().)
If you have a File that references a image file, you can use the File instance to get a URL:
File file = ...
String urlString = file.toURI().toURL().toExternalForm();
Those URLs can be used with the Image constructor.
Note that
File file = new File("fileName.txt");
does not create a file. It just represents a file path. This file may or may not exist. Simply invoking the File constructor does not create a new one.
File file = new File("name.txt");
creates a file somewhere. It doesn't read the existing file whereas
Image image = new Image("pathToImage.png");
tries to read the existing image. In order to be able to read an image stored somewhere you need either the absolute path, which requires the protocol (http, file, ftp etc.) or you put your image into the 'known' directory, like the resources dir of your project.
Say, you have your java sources under src/main/java. The resources dir could be src/main/resources. Put your image there and try working with relative path relative to src/main/resources.

Remove hardcoded file path from java program

i have created a simple java program in which i am creating a text file and reading the data written inside it. The problem is i don't want to hardcode the path of the file because after developing the application i have created a installer package for my program which allow users to install it on there systems. Now the problem is like end user can install the file anywhere (i.e. in there C , D or E drive) and in those cases i am getting FileNotFoundException Exception.
My code-- This is the code which i am using to create and write some text to the text file.
FileWriter file = new FileWriter("E:\\TextFile.txt",true);
BufferedWriter writer = new BufferedWriter(file);
writer.write(input);
write.newLine();
write.close();
This is the code which i am using to read text from the text file.
FileReader read = new FileReader("E:\\TextFile.txt");
BufferedReader data = new BufferedReader(read);
I have one more file for which i hardcoded the path of the file.
System.setProperty("webdriver.chrome.driver","D:\\New Folder\\chromedriver.exe");
As you can see in all my code i hardcoded the paths("E:\TextFile.txt","E:\TextFile.txt" and "D:\New Folder\chromedriver.exe").
Is there any way in java to remove them.
I went through the similar questions but was not able to figure out how to detect the location of the file.
I made the changes as per the suggetions and it worked for me-
// This give me the path of the application where it is installed
String Path = new File("").getAbsolutePath();
Then i add the file name along with the path to get the file.
// Here i am adding the name of the file to the path to read it
FileReader read = new FileReader(Path+"\\TextFile.txt");
// Here i am adding the name of the file to the path to write it
FileWriter file = new FileWriter(Path+"\\TextFile.txt",true);
You can store the file location in a properties file and then read the file location from that into a variable at runtime. Your installer would have to store the file location in the properties file as part of its installation process.
You could also have the file stored in the applications classpath and use relative pathnames to get to it.
I don't think this the answer to what you are asking, but It's a solution to your problem. What you are using there is an absolute path, meaning you specify the whole URL of the file, you can instead use relative paths, which are relative to the location of your application, just like you have .class files in your JAR, you can have a folder for your files and it will be always at the same location relative to the program location.
So instead of this:
FileReader read = new FileReader("E:\\TextFile.txt");
You can have this:
FileReader read = new FileReader("..\MyFiles\TextFile.txt");
Or something like this.

Extracting files from res folder in Executable JAR (txt files to be specific)

I would like to ask if its possible to put text files into my jar, I use them to make my map in my game, but users can get Highscores. now I want to save the Highscores with the map, so I have to save the map on the user their PC. Is there any way how I could do this? I've searched the internet for some ideas but I could not find anything that even came close to what I've wanted. I only had 3/4th of a year java so I don't know much about these things, everything that happens outside the debug of eclipse are problems for me(files are mainly one of those things, null exceptions, etc).
The main question now.
Is it possible to do? If yes, do you have any terms I could search on, or some sites/guides/tutorials? If no, is there any other way how I could save the highscores?
EDIT:
to make clear
Can I get the text file (the text inside the file) to be extracted to a different file in like the home directory of my game (where I save the settings and stuff) the basic maps are inside the jar file, so I want them to be extracted on the first start-up of the program
Greetings Carolien
"extracted to a different file in like the home directory of my game (where i save the settings and stuff) the basic maps are inside the jar file, so i want them to be extracted on the first startup of the program"
You can get the URL by using getClass().getResource()
URL url = getClass().getResource("/res/myfile.txt");
Then create a File object from the URI of the URL
File file = new File(url.toURI());
Then just perform your normal file operations.
if (file.renameTo(new File(System.getProperty("user.home") + "\\" + file.getName()))) {
System.out.println("File is moved successful!");
} else {
System.out.println("File is failed to move!");
}
Assuming your file structure is like below, it should work fine
ProjectRoot
src
res
myfile.txt
Note: the above is moving the entire file. If you want to extract just the data inside the file, then you can simple use
InputStream is = getClass().getResourceAsStream("/res/myfile.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
The just do normal IO operation with the reader. See here for help with writing the file.

Reading files: File name not working

In the following the code I keep getting the error "(No such file or directory)"
public void readFile() throws IOException {
reader = new BufferedReader(new FileReader("map1.txt"));
while(true) {
String line = reader.readLine();
System.out.println(line);
if(line == null) {
reader.close();
break;
}
}
}
I get this same error when I try to read images / anything really. But in the examples I've seen of how to use file readers they all just put in the name of the files and nothing else. In this case the map is in a separate folder in the src file called Maps. I've tried various specifications of "/Maps/map1.txt" but nothing seems to work. How do I get this file to read?
(I'm on a mac as well. I don't know if that changes things.)
Update
Seems like it is netBeans' fault. It only looks the project folder. I think I'll start another topic asking how to remedy this later. Thank you for all the help everyone.
In this case the map is in a separate folder in the src file called Maps.
I assume you have a folder named src which has your java files; in this same folder there is a folder named Maps which has map1.txt.
Now,
reader = new BufferedReader(new FileReader("map1.txt"));
Is going to to try to open the file map1.txt in the current directory. Which directory this is depends on the IDE you use; but you should be able to change it.
If you change it to the folder which has the file it should work.
/Maps/map1.txt is an absolute path, starting at the top directory. Try ./Maps/map1.txt, as long as you are running the java app from the directory above Maps.
I extracted some pieces of my program that may be helpful:
FileInputStream configFile = new FileInputStream("javalogging.properties");
In the case above, the file is on the same level of the src folder (which means, out of the source folder)
FileInputStream configFile = (FileInputStream)
MyClass.class.getResourceAsStream("/javalogging.properties");
In the case above, sure you are going to replace MyClass by your class name, and put the file inside the source folder (useful if you're planning to deploy your application in a way the properties is inside the jar file)
Using the bufferedReader, I used the entire path, as you can see below:
File file = new File(filePath+fileName);
BufferedReader r = new BufferedReader (new FileReader(file.getAbsoluteFile()));

Reading File In JAR using Relative Path

I have some text configuration file that need to be read by my program. My current code is:
protected File getConfigFile() {
URL url = getClass().getResource("wof.txt");
return new File(url.getFile().replaceAll("%20", " "));
}
This works when I run it locally in eclipse, though I did have to do that hack to deal with the space in the path name. The config file is in the same package as the method above. However, when I export the application as a jar I am having problems with it. The jar exists on a shared, mapped network drive Z:. When I run the application from command line I get this error:
java.io.FileNotFoundException: file:\Z:\apps\jar\apps.jar!\vp\fsm\configs\wof.txt
How can I get this working? I just want to tell java to read a file in the same directory as the current class.
Thanks,
Jonah
When the file is inside a jar, you can't use the File class to represent it, since it is a jar: URI. Instead, the URL class itself already gives you with openStream() the possibility to read the contents.
Or you can shortcut this by using getResourceAsStream() instead of getResource().
To get a BufferedReader (which is easier to use, as it has a readLine() method), use the usual stream-wrapping:
InputStream configStream = getClass().getResourceAsStream("wof.txt");
BufferedReader configReader = new BufferedReader(new InputStreamReader(configStream, "UTF-8"));
Instead of "UTF-8" use the encoding actually used by the file (i.e. which you used in the editor).
Another point: Even if you only have file: URIs, you should not do the URL to File-conversion yourself, instead use new File(url.toURI()). This works for other problematic characters as well.

Resources