Java - loading file for ImageIO.write doesn't work in .jar

前端 未结 1 729
别那么骄傲
别那么骄傲 2021-01-28 05:10

I\'m making a game in Java and I want to save the randomly generated map on an image and then load it. My code work without a problem in Eclipse, but when I export it to a .jar/

相关标签:
1条回答
  • 2021-01-28 05:31

    You seem to think you could treat the jar as a directory structure, thats not exactly true. You should not even think of writing to the jar file your code is running from (its possible, but involves many pitfalls).

    Assuming your directory structure looks something like this:

    MyProgram
       MyProgram.jar
    

    and MyProgram is the working directory, you see there is no res directory. The "res" directory you created in Eclipse in the source tree is inside the jar. You cannot access it using the File API, and you will certainly not be able to write anything to it.

    I'm not clear with the code shown what the purpose behind it is; if you are creating the file each time the program is run, and use it in only that run, I would not save it at all. Just return the BuffereImage you created an use it directly where you need it.

    If the idea is to create it on the first run and simply load it on subsequent runs, you need to specifiy a location you can be sure exists and is writeable with your programs privileges. You could attempt to write it directly into the program folder (or create another "res" folder there), but that may not be writeable depending on under which user your program runs. You would normally set up proper structures and permissions during program installation.

    0 讨论(0)
提交回复
热议问题