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.
Related
Possibly a duplicate, though I doubt so since I have not seen anything so far completely answering my criteria in a way that I can complete my program
Background
What I need is to access another jar, from a seperate jar, read and write files to that jar. So far what I have done is change the jar to a zip and then I can delete files, but the problem I am having is with writing files back in, specifically image files (.txt works perfectly fine)
Question
How do I write image files to a zip (that was originally a jar) from another java program (in the end product another jar)
Note
I have looked around and most sources say this is not possible, but those questions dealt with this during the running of a program, my special case is that the other program is not running, but in file format. All I want to do is write and image in and convert it back to a jar and not have any problems with running that jar in the end.
Thank you!
Use FileSystems to access, write and replace the contents of the jar file:
try (FileSystem fs = FileSystems.newFileSystem(Paths.get("path/file.jar"), null)) {
Files.copy(Paths.get("path/to/image"), // path to an external image
fs.getPath("image.jpg"), // path inside a jar file
StandardCopyOption.REPLACE_EXISTING);
}
I've just installed IntelliJ on OSX and I'm trying to write a project where I'm trying to read a text file (among other things).
In this project there's a very essential feature that I need:
It has to be able to open, read and write a text file at some arbitrary given path on the filesystem. In other words, making any changes to the working directory other than from the main source file is not an option.
I have the following code that produces the following output:
String musicPath = "/Users/test/Desktop/testfolder/";
File file = new File(musicPath + "filelist.txt");
System.out.println(file.canExecute());
System.out.println(file.canRead());
System.out.println(file.canWrite());
System.out.println(file.getAbsolutePath());
The output is:
false
true
true
/Users/test/Desktop/testfolder/
However, when I'm adding the line
FileReader filelist = new FileReader(file);
I'm getting a file not found exception. Needless to say, the file exists.
I've set the permissions such that anybody can read/write that file or folder but I'm still getting the same thing.
Could anybody tell me if there is a way to make the program recognise the file I have on the system? From every place this question is asked I see 3 types of replies: either check if the file exists, check the permissions or change the working directory from the project config.
I am trying to execute a windows command inside java code using Runtime.exec() command. It is working fine when put all the necessary batch file and properties file on the root directory. But when i am exporting this is as jar, the java program is throwing error, which is becuase it is not able to find all those dependent .bat and .properties files. Can some one please tell me, where should i keep all the .bat and .properties files in side the folder. Thanks in Advance.
You can do so
Something like
Runtime.getRuntime().exec("cmd /c start yourFile.bat");
You should be able to keep it in the root of your jar if you want
EDIT :
On second thought I don't think you can run bat files inside a JAR
you would have to extract it and then run it
Please give more information on what it is you want the bat file to be doing and I can update this answer maybe there is another way?
Your problem can be divided into two parts: get the bat from the jarand run it.
To get the bat from the jar, you will have to use the ClassLoader to get a resource. you can achieve this by using the method Class.getResource to get the URL or Class.getResourceAsStream to get an InputStream
Anyway, i dont' think you can run the bat from inside the jar. If you try and fail, my advice is to create a temp file, copy your bat into your temp file and run that file.
P.S: Class.getResource finds file in the classpath. If your file is not in your classpath, you won't be able to find it this way.
EDIT: i add the code i'm using to get resources from a general relative path, given the path exist both starting from you working directory and from the home of your jar. It works, i've been able to just pack every folder i need into the jar and ship the jar to another compute rwhere eveything worked fine.
public static URL getResource(String name) {
if ("jar".equals(Main.class.getResource("Main.class").getProtocol())) {
return Main.class.getResource(("\\" + name).replace('\\', '/'));
} else {
try {
return (new File(System.getProperty("user.dir") + "\\" + name)).toURI().toURL();
} catch (MalformedURLException ex) {
return null;
}
}
}
Main is a known class, in this case the class where this static method is. I first use it to get a known url, and see if i am executing from a jar. If i am, i use the getResource, otherwise i use the File api.
the structure i use is this
main_folder\
res\
src\
package\
and, in the jar
file.jar\
package\
res\
and i need to use both File api and getResource since in the rist case the res folder is not in my classpath. with a different structure probably only the getResource method is fine.
This should solve your problem of getting the bat file, you still need to see if you are able to run it, and if you are not, copy everything into a temp file and run the temp file instead.
Working directory in Eclipse looks like this:
I am trying to append to happyPreview.scm and have to call this method from SpeechPreview.java. I tried:
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(getClass().getResource("previews" + File.separator + "happyPreview.scm").toString(), true)));
I thought this would work since they're all in the same 'bash' package but it doesn't work? Nothing is appending!
class.getResource() -> root is the project folder, it is not the class current package folder..
try this
getClass().getResource("/bash/previews/happyPreview.scm")
You can't write to a class resource, only read, and even then, only streaming.
This is because your code will be packaged in a .jar file, that is on the classpath. The deployed .jar file is read-only. Sure, it's not packaged in a .jar file while developing, but it will be when you are done and need to deploy it.
If you want your code to ship with a default/initial resource, and update it, the updated file must be stored elsewhere. When next you try to read it, you first check that other location, and if not found, then you load from resource file.
I am trying to make a mess management application in Java using NetBeans. I want to save images of Members in a specified folder inside my src directory. I just created folder named EmpImgs for storing employees images. Here is my code:
File srcDir = new File(file); // current path of image
File dstDir = new File("src\\J_Mess_Mgnt\\EmpImgs\\"+Txt_C_G_M_M_ID.getText());
objm.copyFile(srcDir, dstDir);` // copy image from srcDir to dstDir
Here I use another class for copying images to predefined folders and renaming the images based on their ID.
Everything is working properly in Java IDE.
But unfortunately after making an executable .jar file, this code will not work. I cannot save or access any image file in that directory.
I just went through this site, but I didn't find a suitable answer.
All I need is saving and editing images inside jar folder
Hehe hi mate you need some help. This is a duplicate but I will cut you some slack and maybe you should delete this later. So back to basics, the jvm runs byte code, which you get from compiling java source code to .class files. Now this is different to C and C++ were you just get a .exe. You don't want to give your users a bunch of .class files in all these folders which they can edit and must run a command on the command line, but instead give them what is known as an 'archive' which is just an imutable file structure so they can't screw up the application, known as a jar in java. They can just double click on the archive (which is a jar), and the jvm will call the main method specified in the MetaInf directory (just some information about the jar, same as a manifest in other programming languages).
Now remember your application is now a jar! It is immutable! for the resasons I explained. You can't save anymore data there! Your program will still work on the command line and in IDEs because it is working as if you used your application is distrubuted as bunch of folders with the .class files, and you can write to this location.
If you want to package resources with your application you need to use streams (google it). BUT REMEMBER! you cant then save more resources into the jar! You need to write somewhere else! Maybe use a user.home directory! or a location specified from the class path and the photos will be right next to the jar! Sometimes you might need an installer for your java application, but usually you don't want to create the extra work if you don't need to.
At last I find an answer suit for my question.It is not possible to copy images or files to a executive jar folder.So I used a different Idea.Create some folders(as per our requirement),Where my executable jar folder is located(No matter which drive or where the location is).The code is..
String PRJT_PATH=""; //variable to store path of working directory.
private void getdire() throws IOException{
File f=new File(".");
File[] f1=f.listFiles();
PRJT_PATH=f.getCanonicalPath(); //get path details.for eg:-E:/java/dist
}
private void new_Doc_folder(){ //function for creating new folders
try{
String strManyDirectories="Docs"+File.separator+"Bil_Img"; //i need to create 2 folders,1st a folder namedDocs and In Docs folder another folder named Bil_Img
String SubDirectories="Docs"+File.separator+"EmpImgs"; //same as above but keep in mind that It will not create a Same folder again if already exists,
// Create one directory
boolean success = (new File(strManyDirectories)).mkdirs(); //create more than one directory
boolean success1 = (new File(SubDirectories)).mkdir(); //Creates a single directory
if (success && success1) {
}
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
It works Successfully.
Regds