FileInputStream Javafx in .jar files - java

I am creating a Javafx application in Intelij and FileInputStream works perfectly. However, when I create a .jar file from the project and try to run it the code fails to run as it is unable to locate the file in the file input stream.
Here is my code:
ObjectInputStream os = new ObjectInputStream(new FileInputStream("src/settingStorage.bin"));
Am I doing something wrong?

There is always some issue accessing a file outside a jar, depending on where the file location is. You can check this SO question/answer to have an idea on accessing your file.
Read properties file outside JAR file

Try this:
EDIT: Look at this again, I left part out.
ObjectInputStream os = new ObjectInputStream(new FileInputStream(SomeClass.class.getResourceAsStream(“settingStorage.bin")));
This usually works for me. When I run this, it operates fine, in AND out of the development area. Don’t include /src, as when you call getResourceAsStream off a class, it already checks inside the jar.
Cheers!

Related

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.

How to create a file in src/main/resources

If I do this
fis = new FileInputStream(new File(".").getAbsolutePath() + "/sudoinput.txt");
Its trying to write to this location on the server. I am not sure if this is a writable
place.
FILE NAME (fos)::::::::::::::::::/opt/tomcat/temp/./sudoinput.txt
FILE NAME (fis)::::::::::::::::::/opt/tomcat/temp/./sudoinput.txt
I wanted to write to
webapps/sudoku/WEB-INF/classes
which is basically
C:\Users...\git\sudo-project\sudo\src\main\resources
On Eclipse Windows 7 I get this
error
src\main\resources\sudoinput.txt (The system cannot find the path specified)
if I give
fis = new FileInputStream("src/main/resources/sudoinput.txt");
I have tried this too:
fis = new FileInputStream("src\\main\\resources\\sudoinput.txt");
but doesn't work.
how should I create a fileinputstream to be able to write to src/main/resources ?
please note that I am using eclipse windows to do dev and will be uploading the .war file on to a unix server if this changes the way in which the paths need to be specified.
The src/main/resources folder is a folder that is supposed to contain resources for your application. As you noted, maven packages these files to the root of your file so that you can access them in your library.
Have a look at the Maven documentation about the standard directory layout.
In certain cases, it is possible to write to the context but it is not a good idea to try it. Depending on how your webapp is deployed, you might not be able to write into the directory. Consider the case when you deploy a .war archive. This would mean that you try to write into the war archive and this won't be possible.
A better idea would be to use a temporary file. In that way you can be sure this will work, regardless of the way your web application is deployed.
Agree with Sandiip Patil. If you didn't have folder inside your resources then path will be /sudoinput.txt or in folder /folder_name/sudoinput.txt. For getting file from resources you should use YourClass.class.getResource("/filename.txt");
For example
Scanner scanner = new Scanner(TestStats.class.getResourceAsStream("/123.txt"));
or
Scanner scanner = new Scanner(new `FileInputStream(TestStats.class.getResource("/123.txt").getPath()));`
Also look at: this
You can keep the file created under resources and call .class.getresource(your_file_name_or_path_separated_with_forward_slash);
See if it works for you.
If you like to create files in webapps/sudoku/WEB-INF/classes which is in the end within the created WAR file which can be achieved by putting the files you want into src/main/resources/
This means in other words you need to create the folder src/main/resources and put the files you like into this directory.

File path errors in eclipse? (Java Spring)

InputStream inp = new FileInputStream("src/main/resources/ExportHour.xls");
I have a file in the src/main/resources folder of my Java Spring project.
I am attempting to create an inputstream in one of my Controllers, however I always get a file not found exception. When I change the path location to point specifically to the file on my machine, it works fine.
Any way I can make it so the file can be found within the java project?
Try with spring ClassPathResource.
InputStream inp = new ClassPathResource("ExportHour.xls").getInputStream();
That is because the resources folder in maven is put in your jar file directly i.e. the ExportHours.xls file is put inside your jar in the root directory.
It sounds like you could just change the working directory of your process - it's not where you think it is, I suspect. For example, I suggest you write
File file = new File("src/main/resources/ExportHour.xls");
and then log file.getAbsolutePath(), to see what exact file it's using.
However, you should almost certainly not be using a FileInputStream anyway. It would be better to use something like:
InputStream inp = Foo.class.getResourceAsStream("/ExportHour.xls");
... for some class Foo which has a classloader which includes the resources you need.
(Or possibly /resources/ExportHour.xls", depending on your build structure.)
That way even when you've built all of this into a jar file, you'll still be able to open the resource.

Create and read an xml file outside jar file

I've been asking a lot lately, and all my posts are about the same problem, but in different stages and with different possible answers (because the specific problem is different than the previous one, but closely related). So, i'm sorry if it looks like i'm repeating my question. In fact, i'm not. I've been searching on Google and here, but none of the answers seem to solve my problem, or i'm getting them wrong.
Well, my files hierarchy is:
+ MyGame
+ build.xml
+ src
+ ThisIsWhereEclipsePutsTheXMLFile
+ build
+ manyFoldersWithClassFiles
+ aSpecialFolderWhereTheEntryPointIs
+ ThisIsWhereIWantMyXMLfileToBe.xml
+ game.jar
My problems is basically this: My program is supposed to save it's status to a file, and then read that file. This file should be outside the .jar file (there is only one), in the same folder. The file can exist or not. If it exists, it should overwrite it.
In my previous question, I asked about how to read an xml file that's in the same directory. The answer i got actually solves my problem when i'm using it from Eclipse.
But i need to create a .jar file with my whole program, and i need my program to crear such xml file whenever i ask it to do it.
My save() is like this, and it seems to be working when i run it on Eclipse, but won't work when i run it executing my .jar file:
public void save(Game game) throws IOException{
Document doc = DocumentHelper.createDocument();
doc.add(game.save());
File save=null;
save = new File("save.xml");
FileWriter writer = new FileWriter(save);
doc.write( writer);
writer.close();
}
And this is how i get the informacion back from the file:
public Game getinfofromxml() throws IOException{
Game game;
SAXReader reader = new SAXReader();
try{
URL fileWithData= new File( "save.xml" ).toURI().toURL();
Document document = reader.read(fileWithData);
Element alreadySavedGame= document.getRootElement();
game= getGameSaved(alreadySavedGame);
}catch(DocumentException ex){
throw new IOException();
}
return game;
}
Again, this works from Eclipse, but this won't work when i run it from my jar file. From Eclipse, the xml file is created in the MyGame folder, but not in the folder i have my .jar. When i execute my .jar, no XML is created at all.
Now, i've been reading that this might have something to do with the classpath. So, let me tell you how I compile it:
1) i run Ant, which makes the build directory. It doesn't create the .jar automatically.
2) I create the Manifest.txt file, where i write:
Main-Class: aSpecialFolderWhereTheEntryPointIs.MyMainClass
Class-Path: .
3) i create the .jar file on the cmd:
jar cfm myGame.jar Manifest.txt *
So, i don't think i'm making too many mistakes there...
May Ant have something to do with it?
Any idea?
Thanks beforehand (and sorry for my English)
Stop thinking about the 'current directory' and put the config. in user.home as discussed in this answer. For a long time OS manufacturers have been telling us not to put config. settings in the application directory.
See also this answer to "How can a java program use files inside the jar for read and write?" for more tips.
The way you write and read file is using relative path of the current start directory... It depends on where you started the jvm and where you expect it to write and read your file.

Netbeans Built .jar doesn't work with class file inside

I had problems while finding the path of file(s) in Netbeans..
Problem is already solved (checked answer).
Today I noticed another problem: When project is finished,
I have to execute the generated .jar to launch the program, but it doesn't work because an error occurs: NullPointer (where to load a file) when accessing/openning jar outside Netbeans.
Is it possible to open a file with the class file in Java/Netbeans which works in Netbeans and even in any directory?
I've found already some threads about my problem in site but none was helpful.
Code:
File file = new File(URLDecoder.decode(this.getClass().getResource("file.xml").getFile(), "UTF-8"));
The problem you have is that File only refer to files on the filesystem, not files in jars.
If you want a more generic locator, use a URL which is what getResource provides. However, usually you don't need to know the location of the file, you just need its contents, in which case you can use getResourceAsInputStream()
This all assumes your class path is configured correctly.
Yes, you should be able to load a file anywhere on your file system that the java process has access to. You just need to have the path explicitly set in your getResource call.
For example:
File file = new File(URLDecoder.decode(this.getClass().getResource("C:\\foo\\bar\\file.xml").getFile(), "UTF-8"));

Categories

Resources