FileSystem error when trying to close it - java

Currently I'm trying to make a level editor for a Java game that I created.
My problem is that my program doesn't save the edited levels.
Here is the code that I made so far:
Path path = Paths.get(gameFile.getAbsolutePath());
FileSystem fs = FileSystems.newFileSystem(path, null);
Path p = fs.getPath("rpg"+fs.getSeparator()+"levels"+fs.getSeparator()+"level"+(short)level+".png");
OutputStream os = Files.newOutputStream(p);
ImageIO.write(img, "png", os);
os.close();
fs.close();
gameFile is the .jar file of my game which contains the levels and
the levels are saved as .png files.
I have tried to save my picture outside of the jar and it worked so i guess i made a mistake with the FileSystem or the Path.
The Path in the jar is rpg/levels/level*.png
Edit:
I changed
OutputStream os = Files.newOutputStream(p);
to
OutputStream os = Files.newOutputStream(p,StandardOpenOption.CREATE,StandardOpenOption.TRUNCATE_EXISTING);
but now I get an error when closing the fileSystem
java.nio.file.FileSystemException: G:\RPG.jar: The process cannot access the file because it is being used by another process.
at sun.nio.fs.WindowsException.translateToIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsFileSystemProvider.implDelete(Unknown Source)
at sun.nio.fs.AbstractFileSystemProvider.delete(Unknown Source)
at java.nio.file.Files.delete(Unknown Source)
at com.sun.nio.zipfs.ZipFileSystem.sync(ZipFileSystem.java:1294)
at com.sun.nio.zipfs.ZipFileSystem.close(ZipFileSystem.java:277)
at de.jorolf.editor.LevelEditor$5.actionPerformed(LevelEditor.java:213)

You can not save anything inside of a running jar-File (related: updating-a-jar-whilst-running).
Also, if you want to save something inside of a not running jar-File, then you also need to save the file compressed. For this task you can simply add a ZipOutputStream to your stream-queue (Java-Doc: ZipOutputStream.html). Also java.util.jar.JarFile and java.util.jar.JarEntry may be helpful.
For your general task, you should save the level file outside of the jar. You may distribute the game in a folder game with /game/theGame.jar and /game/firstLevel.lvl. Then the level is outside of the jar and you can modify it.
Also you may use common directories as other games do, like Windows Documents or AppData for game specific settings and data.
MyDocuments in Java: FileSystemView.getFileSystemView().getDefaultDirectory().getPath()
AppData in Java: System.getenv("APPDATA")

Related

java.io.FileNotFoundException when accessing json file in jar

I'm using this code File serviceAccountFile = new File(Main.class.getResource("/serviceAccountKey.json").getFile()); to access a json file inside my "resources" folder. It works fine when I'm running it from intellij. But i get this error when running the program from the jar.
java.io.FileNotFoundException: file:\C:\Users\Ashirwada\Documents\IIT\JAVA\POS\target\POS-0.6-jar-with-dependencies.jar!\serviceAccountKey.json (The filename, directory name, or volume label syntax is incorrect)
at java.base/java.io.FileInputStream.open0(Native Method)
at java.base/java.io.FileInputStream.open(Unknown Source)
at java.base/java.io.FileInputStream.<init>(Unknown Source)
at ashirwada.pos.Firebase.initializeFirebase(Firebase.java:27)
at ashirwada.pos.Main.init(Main.java:33)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(Unknown Source)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(Unknown Source)
at java.base/java.lang.Thread.run(Unknown Source)
I have other files like fxml files and jpg inside my resource file. They get detected and runs fine. This json file is the only thing thats giving me problems. I opened the Jar with winrar and the json file is there with the rest of the fxml files and the jpg. I'm using maven to compile my jar with the dependencies i need.
That's because after you package your resource into a jar, the string you get by URL.getFile() would be invalid for the constructor File(String path).Use getResourceAsStream instead may solve your problem.
System cannot resolve file C:\Users\Ashirwada\Documents\IIT\JAVA\POS\target\POS-0.6-jar-with-dependencies.jar!\UI\serviceAccountKey.json due to the file is in jar file
You should extract the jar in to a folder and read json file from there
Or you can read file as a resource
InputStream in = etClass().getResourceAsStream("/UI/serviceAccountKey.json");
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
try this
File(Main.class.getClassLoader().getResource("/serviceAccountKey.json").getFile());

Trouble with playing .wav files from JAR

I'm having some strange trouble with playing a WAV file from a JAR.
First, I can simply read it using ClassLoader when working in Eclipse. Everything works fine there.
Then I export my project to a JAR file. But now it says that no such files exists although I can see it with an archivator; for non-WAV files it works fine.
When I decided to export it to an external directory first the WAV file exports corrupted (while other files are not damaged, again).
What should be my problem then? I've made a research, but I couldn't find anything related to any trouble with WAV files or heavy files.
How do I do it correctly and why does it work for small files but not the big ones (or sound files)?
Thank you for your awnsers.
EDIT:
The package explorer in Eclipse:
http://i.imgur.com/7TTyQit.png
The code used to actually get the file:
private static MusicPlayer music = new MusicPlayer(new InputStream[]{MusicPlayer.class.getResourceAsStream("default/Final.wav")}, new InputStream[]{});
Finally, the exception:
java.io.IOException: mark/reset not supported
at java.util.zip.InflaterInputStream.reset(Unknown Source)
at java.io.FilterInputStream.reset(Unknown Source)
at com.sun.media.sound.SoftMidiAudioFileReader.getAudioInputStream(Unknown Source)
at javax.sound.sampled.AudioSystem.getAudioInputStream(Unknown Source)
at ru.windcorp.game.music.Music.run(Music.java:31)
at ru.windcorp.game.music.MusicPlayer.playMenu(MusicPlayer.java:29)
at ru.windcorp.game.GameMain.main(GameMain.java:152)
Don't make your AudioInputStream from an InputStream. Make it from a URL.
(1) URL's can "see" into jars.
(2) getAudioInputStream(InputStream inputStream) likely runs a Markability or Resetability test (or both) on the audio file when it is converted to an InputStream. Most audio files seem to fail at this stage.
(3) getAudioInputStream(URL url) does NOT run a Markability test on the audio, thus circumventing the issue.
Check out the API for the different input parameters of this method, for the AudioSystem object.
Whoa! Why are you using com.sun.media.sound code? I think that has mostly been deprecated, hasn't it? SoftMidiAudioFileReader is no where to be found in the Java 7 SE API. A slew of people are using this and generating errors. Where did you get the suggestion to use this?

Java - read file from directory for jar

I have an application that creates a temporary mp3-file and puts it in a directory like C:\
File tempfile = File.createTempFile("something", ".mp3", new File("C:\\));
I'm able to read it by just using that same tempfile again.
Everything works fine in the Eclipse IDE.
But when I export my project for as a Runnable jar, my files are still being made correctly (I can play them with some normal music player like iTunes) but I can't seem to read them anymore in my application.
I found out that I need to use something like getClass().getResource("/relative/path/in/jar.mp3") for using resource files that are in the jar. But this doesn't seem to work if I want to select a file from a certain location in my file system like C:\something.mp3
Can somebody help me on this one?
It seems you dont have file name of the temp files . When you was running your program in eclipse that instance was creating a processing files, but after you made a runable you are not able to read those file that instance in eclipse created, You runable file can create its own temp file and can process them,
To make temp files globe put there (path + name ) entries in some db or property file
For example of you will create a temp file from the blow code
File tempfile = File.createTempFile("out", ".txt", new File("D:\\"));
FileWriter fstream = new FileWriter(tempfile);//write in file
out = new BufferedWriter(fstream);
the out will not be out.txt file it will be
out6654748541383250156.txt // it mean a randum number will be append with file
and you code in runable jar is no able to find these temp files
getClass().getResource() only reads resources that are on your classpath. The path that is passed to getResource() is, in fact, a path relative to any paths on your current classpath. This sounds a bit confusing, so I'll give an example:
If your classpath includes a directory C:\development\resources, you would be able to load any file under this directory using getResource(). For example, there is a file C:\development\resources\mp3\song.mp3. You could load this file by calling
getClass().getResource("mp3/song.mp3");
Bottom line: if you want to read files using getResource(), you will need those files to be on your classpath.
For loading from both privileged JARs and the file system, I have had to use two different mechanisms:
getClass().getClassLoader().getResource(path), and if that returns null,
new File(path).toURI().toURL();
You could turn this into a ResourceResolver strategy that uses the classpath method and one or more file methods (perhaps using different base paths).

Netbeans - Reading a data file in src folder

I have a scanner that's trying to read a file named info.data in the src folder.I get Exception in thread "main" java.io.FileNotFoundException: info.data (The system cannot find the file specified). What's the address I should put in the scanner?
If the input file is always part of your application (i.e. you also put this into the .jar file later) you should use getResourceAsStream() in order to read its contents.
InputStream in = getClass().getResourceAsStream(filename);
Scanner scanner = new Scanner(in);
In netbeans, the src folder isn't the destination of the compiled classes, so if you are using a relative path, the location your program launches is not going to be the src folder.
That means you typically should "extend" your build to copy a non-source file into the build path if you want it to operate in the manner you imply. Many files already copy over to the build path (like properties files), but if you are including a data file that doesn't have a rule for being place in the build path, you need to add the rule yourself.
Try putting the path to it.
File f = new File("C:\\path\\src\\info.data");

Running a Jar file alone

Hai
I have an application which is designed in netbeans6.0.1 where i need to display an image as an logo.My coding is as below
mLogo = new JLabel();
URL lUrlLogo = getclass().getResource("/com/images/image.gif");
Image lLogoimage = Toolkit.getDefaultToolkit().getImage(lUrlLogo);
ImageIcon licon = new ImageIcon(lLogoimage);
mLogo.setIcon(licon);
My code works fine when i execute it in netbeans but when I try to run my jar file which is created by netbeans in dist folder,it gives me an exception
Uncaught error fetching image:
java.lang.NullPointerException
at sun.awt.image.URLImageSource.getConnection(Unknown Source)
at sun.awt.image.URLImageSource.getDecoder(Unknown Source)
at sun.awt.image.InputStreamImageSource.doFetch(Unknown Source)
at sun.awt.image.ImageFetcher.fetchloop(Unknown Source)
at sun.awt.image.ImageFetcher.run(Unknown Source)
Whats the problem with my jar
Can some one help me to run my jar
Thanking u
Your jar file will need to include the image.
See this tutorial or this one for instructions for how to do that. Basically if you include the file in a source folder (with the appropriate path) it should be okay.
If you think you've already got the image there, run
jar tvf file.jar
to show the contents. Make sure everything's where you expect it to be in terms of directories.
EDIT: As per the comments, the problem turned out to be due to case sensitivity.
Finding resources in a jar file is always case-sensitive, whereas loading them from a file system is only case-sensitive if the file system is. So if your file is image.GIF but you're looking for image.gif then it'll work when you're loading from the file system in Windows, but not in the jar file.
And you have checked that the JAR file contains the path "/com/images/image.gif"?
Also, I'm not really sure about the leading slash, I always used relative paths to access resources (but I guess it should work anyways).
As an example from class it.lapo.example.Main I use getClass().getResource("resources/logo.png") and in the JAR files are this way:
it/lapo/example/Main.class
it/lapo/example/resources/logo.png
I know... not much different from your own example, but it does work... so I guess yours is quite close to being correct too.

Categories

Resources