At the moment I create a file like this:
new File("C:\\Users\\user\\Projects\\javaProject\\src\\com\\javaProject\\package\\file.xml");
So far listing the whole path is the only way I can get the file to be create inside 'package' otherwise if I just use:
new File("file.xml");
it just gets created in the source directory and if I use:
new File("package\\file.xml");
it just throws errors
Have you tried using a relative path?
new File("com\\javaProject\\package\\file.xml");
Your Java code should not be creating files in your package directory.
Eventually, you're going to want to deploy your code, which usually means packaging it in a Jar file. You cannot modify a Jar file from within the code running in the Jar file.
Even if that might be physically possible, don't do it. Besides, the code to modify a Jar file is way different from your current code.
Yes I did in the same way like janos but i think File.separator is better then / or \ because someday your program might run on a platform developed in a far-off land, a land of strange things and stranger people, where horses cry and cows operate all the elevators. In this land, people have traditionally used the ":" character as a file separator, and so dutifully the JVM obeys their wishes.
Related
I am having issue running a Java program.
There's a line of code in a jar file that opens the FileInputStream to some file from "/apps/somefile" location,
however I do not have access to the root directory.
The issue is that I am unable to change the code since it is provided in a jar file, as such is there anyway to change to root directory that "/" points to when running the java program?
Here's the line for reference:
FileInputStream fileInputStream = new FileInputStream("/apps/somefile");
The line of code you present does not do anything directly. It is Java source code, and Java is ordinarily compiled to bytecode and presented in that form to the JVM. It sounds like your jar may contain source files along with the compiled class files, which is sometimes done. If that's the case then you can simply unpack the Java sources from the jar, modify them, recompile, and make a new jar from the results.
If you don't have source then you could try decompiling, as another answer suggests. That's a bit nasty, but it probably would work.
Alternatively, what you actually ask is
is there anyway to change to root directory that "/" points to when running the java program?
In fact, there may be, depending on the system on which the code is running. You could conceivably run your program under chroot, which has precisely that effect. That's a distinctly non-trivial exercise, however, and if you don't have access to the root directory (though I'm not sure how you can do anything in that case) then you very likely do not have sufficient access to set up or use a chroot environment, either.
you need to do a decompiler to that jar. You can use : http://jd.benow.ca/
Then you need to change that class that have the InputStream and then compile again and make the Jar file.
I have started getting into game programming.
My question is, that when I am working with files, either parsing data, writing to files, etc. Should I be using relative path names, or absolute pathnames, or something else which is better. I've heard about using jar files, but I am not sure
1. how that works
2. if it is a good way to do it.
So when developing a game that will be cross platform, what is the best method for managing files that the program will need to read from and write to.
there are several ways in which you can ship your code as a product. the most common are
packaging everything in one executable jar file.
having a set of folders where you place all necessary resources.
minecraft, for example, is written in java and distributed as a single executable jar file that contains all necessary class files and resources. to run the game (assuming you have java installed) all you need to do is double-click the jar file.
read this short tutorial about how to add a main class to a jar file.
either way, always treat classes and resources in your code as if they're in your classpath. for example, if you have a my.properties file on the root of the source tree then load it by using 'my.properties'. if you put it under a 'conf' folder then use 'conf/my.properties'.
i think it is the safest way not to get lost.
are you using maven?
The jar file is a zip of all your compiled *.class files and your resources. You can safely load your resources and even default data FROM a jar if you package your program, but you can NOT safely write data back to the jar. This detail is answered in depth already at
How can an app use files inside the JAR for read and write?
For information on how to package a jar see
http://docs.oracle.com/javase/tutorial/deployment/jar/
I made my java project into an executable jar using the export to jar option in eclipse. The jar runs as expected, except that it does not use any of the serialized files. I can see that clearly from the GUI. What could be the reason for this problem and how do I fix it ?
I saw this related question - Why does my JAR file not create a serialization?
But it does not tell me exactly how to get around this problem. It looks like you cannot pack a folder into a jar. Why ? Because code could accidentally/intentionally continue to add data into that folder and make the whole jar occupy the hard disk ?
How do I create some kind of structure in which I pack my executable jar and its serialization folder ?
Answering this question:
How do I create some kind of structure in which I pack my executable jar and its serialization folder ?
A common approach is to have a well-defined place to store serialized files, settings, etc, that does not depend on where the program has been executed from. Usually it is user's home directory, or Application Data in case of windows. I used this code to store my application settings:
String home = System.getenv("APPDATA");
if (StringUtils.isEmpty(home)) {
home = System.getProperty("user.home");
}
CONFIG_HOME = new File(home, ".myProgram").getAbsoluteFile();
CONFIG_HOME.mkdirs();
So on windows it will use AppData and on *nix systems it will use user's home. The dot in front of myProgram is to make it hidden on *nix platforms, which is a common practice.
EDIT For your question in your comment:
on my linux machine there is no APPDATA env variable so this code will create a directory /home/myUser/.myProgram. On windows it will be something like c:/Users/myUser/AppData/Local/.myProgram. On MacOSX, no idea.
You need your JAR to use the same path for reading the Serialized Files as your code in eclipse.
So you make a properties file containing the directory with your serialized objects.
Then, this is the same for both your JAR and our project.
See also: http://www.mkyong.com/java/java-properties-file-examples/
You can use
AClass.class.getResource(String str);
//or
AClass.class.getResourceAsStream(String str);
AClass: one of your classes.
str: file location which you want to read.
For example;
if your class hierarchy seem like this:
+src
+-com
+-test
|-AClass.java
+-util
+-PrintUtil.java
+-resources
|-Bouble.png
|-Mouse.png
+-Ocean.png
and for reading "Mouse.png" image, you can this with a lots of ways:
AClass.class.getResource("/resources/Mouse.png");
//or
PrintUtil.class.getResource("../resources/Mouse.png");
...
You can't write inside a jar file while you are using/running the jar file. When you put the jar file in you classpath or you run the program from jar directly, the jar will be locked by your jvm, hence it won't allow you to update the same jar file which you are currently using.
The solution given by people which says use resource as stream will work if your classes are there in a folder, not in an archive (which you are using).
As an archive you can't directly update it, you need to do following steps (by yourself or by 3rd party api),
Extract in temp location
update the files
re archive
Now as the jar file is locked, you won't be able to do the third operation, which is not even safe. As an example when you are running a jar file, try to rename it, it won't happen, if it happens, the jar file is not yet locked by the jvm, it gets locked whenever you call a class which is inside the jar file.
For better and secure serialization and file saving please look into this: java.util.prefs.Preferences.
I have created a program in Java using eclipse that contains a couple of folders with graphics and files that get read from and written to. What I need is a way to export the whole program in some executable format so that anyone can run my program.
I've had a look around online and I notice that people suggest creating an executable JAR file. However I have my reservations about this since I suspect it will choose to ignore the graphics & other files that the program uses, only focusing on the actual source code.
Please could someone suggest a solution to this issue, it is absolutely essential that the files and graphics are packaged up with the rest of the code.
On another related note; at present I'm referencing the files & graphics using files paths that are specific to my computer. If I were to use another solution such as creating an installable program how should I handle these filepaths? Apologies if this is a naive question, however I'm new to this sort of thing.
However I have my reservations about this since I suspect it will choose to ignore the graphics & other files that the program uses, only focusing on the actual source code.
When you think you may have a solution but it doesn't work, you should test that theory.
A jar file is absolutely the right solution for this. However, you need to make sure that Eclipse considers them as resources on the build path so that it will copy them into the jar file. Then you just need to refer to them from the jar file:
On another related note; at present I'm referencing the files & graphics using files paths that are specific to my computer. If I were to use another solution such as creating an installable program how should I handle these filepaths?
Use Class.getResource() or Class.getResourceAsStream() or the ClassLoader equivalents. That will let you load your resources directly from the jar file, without even having separate files on the file system.
I want to copy an existing .exe-file from one directory to another and launch it afterwards with Java. Like this:
FileIO.copy( new File( sourceFile ), new File( targetFile ) );
System.out.println( "Existing: " + new File( targetFile ).exists() );
System.out.println( "Launching " + targetFile );
String cmd[] = { targetFile };
Process p = Runtime.getRuntime().exec( cmd );
p.waitFor();
System.out.println( "Result: " + p.exitValue() );
The output is like this:
Existing: true
Launching C:\test\Launcher.new.exe
Result: 2
So Java says that the file is valid and existing, but Windows just can't launch the process because it thinks the file is not there. The pathes are absolute and with backslashes. I also have all permissions on the files so I'm allowed to execute them.
The Launcher.new.exe is generated by Launch4j, so it's more or less standalone. At least it doesn't depend on DLLs in the same folder. But strange: It works when I copy and launch the notepad.exe.
One more strange thing: If I don't copy the file by Java but by hand, the launching also fails with the same error.
OS is Vista with SP1.
Any clue?
Hmm... I wonder if this might be Vista's wonderful User Access Controls at play...
Are you working within Program Files? If so, move everything out into a seperate folder (c:\CopyTest) and try again - see if that helps...
Without more details, it's hard to give specific answer. Check your permissions on the c:\test directory and the permissions on target file you are trying to execute.
If your path contains forward slashes, you might want to try changing them to backslashes before execing. Also, you should try to make the path absolute, including a drive letter and colon (e.g. C:\test\myprog.exe). Note that if you code the path in a Java String, you need to double up the backslashes...
Once you get that working, you can ease up on those constraints until you figure out what broke your attempt.
EDIT 1: Some common pitfalls with exec() are mentioned in this article. I don't think any of these apply, but you may want to use the coding from the last example to run your .EXE within CMD.EXE to get decent path resolution, error handling and such.
EDIT 2: Your executable file name needs to be interpreted as a long file name. I'm not positive the API can/will handle this. Please try giving the .EXE a short, simple name (just for testing) like NEWPROG.EXE (with no second dot in the name, either!) But first definitely give it a try with CMD.EXE first.
EDIT 3: From reading comments to the other answer: Is it possible your program is indeed running, and itself returning a status of 2 because it is failing to find a file? Is there some way to verify operation of your program, perhaps by calling it from a .CMD batch script that you run from your Java program, and having it write output redirected to a file?
Maybe the problem you might me facing is not having the bundled more in the directory. Launch4j may convert your program to exe, but there just be a local directory to the jre. That folder contains the bin and lib files of any existing Java jre.
Maybe it helps...
Update
Seems like some people are having a tough time understanding what I said. No problem, I'll explain.
Let's take an example that I have created a simple Client Chat App in Java and I exported it into a runnable .../ClientChatApp.jar file. Yet, it still doesn't have the dependencies within it to run the file and needs the installation of Java in the desktop for doing so. For example here, .../ClientChatApp.jar still needs the dependencies of javax.swing.*, java.net.* and java.io.*. Hence it will locate those dependencies from the JDK/JRE it is supposed to use.
Now, when it comes to converting from .../ClientChatApp.jar to .../ClientChatApp.exe, it will work as expected, only if the desktop has Java installed, so that it can collect the dependencies from there. This is not user friendly since any user who doesn't have Java installed will have to install it first to be able to use your app.
Here's where Launch4j helps. When you are converting from jar to exe using this program, then it helps to redirect where the exe will look for the dependencies in a local folder, usually being .../jre/... in the sam directory as the .../ClientChatApp.exe file. Quick tip: To actually do that, go to the same directory as where you want to have the exe file, create a folder there called jre. Now go to C:/Program Files/Java/<<your JDK or JRE folder>>/ and then select and copy the bin and lib folders and copy them. Then go to the directory where you created the folder of jre and paste both of the folders in the folder.
Many users may have already done it, but why I explained all the above is to give a clear understanding of what the jre folder does and hence come to the main point, that you will have to also send the jre folder with the exe file to the user, otherwise there is a point of failure while execution.
You can send them into a .zip file or create an installer exe using Inno Setup. I recommend doing more research if you're wanting to use Inno Setup.
That's it. Thank You! (plz upvote me, its my first answer)