Eclipse project can not reference a file using relative paths - java

My file is located under the src directory. However, when I try to call it using "src/readme.txt" the file is not found.
In fact, it states that java is looking for "C:\Documents and settings\john\My Documents\Downloads\eclipse-win32\eclipse\coolCarsProject\src\readme.txt".
How do I fix this? I do not want to put in the absolute path all the time.
Do I need to fix the classpath, buildpath, or change the project root, etc? It is not at all obvious from the roughly 1000 settings in Eclipse for a newbie.

First, you have to decide if you want to load the file from the file system, or if the file will in fact be bundled with your application code.
If the former, then you should really think about how your application will be launched when actually deployed, because using a relative file path means that the program should always be started from the same location: a relative path is relative to the location from where the program is started (the current directory). If this is really what you want, then edit your launch configuration in Eclipse, go to the Arguments tab, and set the working directory you want. But the src directory is not where you should put this file, since this will copy the file to the target directory, along with the classes, that will probably be put in a jar once you'll deploy the application.
If the latter, then you should not treat the file as a file, but as a resource that is loaded by the ClassLoader, using ClassLoader.getResourceAsStream() (or Class.getResourceAsStream()). Read the javadoc of those methods to understand the path to pass. If you put the file directly under src, it will be copied by Eclipse to the target directory, along with your classes, in the default package. And you should thus use SomeClass.class.getResourceAsStream("/readme.txt") to load it.

Using paths relative to the current working directory is not a good idea in general, as it's often quite hard to establish what your current working directory will be. In Eclipse, it will be your project folder (unless you set it to something different in your launch configuration), in webapps it will be the webapp's root directory, in a command line app it could be anything.

Try this one:
String filePath = ".\\userFiles\\data.json";
where «.\» is a root for the Eclipse project, «userFiles» is a folder with the user's files inside of Eclipse project. Since we are talking about Windows OS, we have to use «\» and not «/» like in Linux, but the «\» is the reserved symbol, so we have to type «\\» (double backslash) to get the desired result.

Related

Will my executable jar include files I added in the file structure?

I'm trying to comprehend how creating executable jars and file paths work, so please bear with me.
I have a small program, which is supposed to upload some Firmware to Servers. These Firmwares have a combined size of about 650MB. All in all, the Project Folder takes up about 2.2GB of space.
In the program itself, I have some Strings that refer to the name of the folder that contains the firmware.
"src\\com\\java\\myProgram\\data\\bios_fw\\"+biosFWPath+"\\"+biosFW
When testing in the IDE, this works without problem.
So here's my question(s): Will this still work if I build the program as executable jar? I have already noticed that the jar I created holds only about 450MB. Does it even contain the firmware then? And if it does, will the program be able to find the path specified?
Furthermore, what would be the proper way of "installing" these folders together with the jar on a Users PC?
Thanks!
As a .jar file is a java archive file, you can open it and look yourself as we don't know how you build your .jar.
But considering the future, I would remove the absolute path and use a relative path to a directory where you can insert the firmware in case the fw got updated, so you don't have to build your program each time.
The proper way, when you want to keep the FW in your project is using ClassLoader.

Confusion over current working directory in File’s getAbsolutePath method

The file’s getAbsolutePath has the tendency that if a relative path or just the file name is provided in the file constructor, then it will resolve the absolute path by prefixing the current working directory.
The definition of current working directory is the directory where we run our Java Program.
In my example, my java program resides inside D:\my-app\src\App.java
When I do a System.out.println(System.getProperty("user.dir"));
Then it should ideally print D:\my-app\src
But it is actually printing D:\my-app
Why is it so?
When you start an application from IntelliJ, its working directory is set according to what's set in "Working directory" in the "Run/Debug Configurations" dialog.
There, you can set the working directory to a fixed value such as D:\my-app\src. Another option is to use a path variable. The list of variables that are available apparently can depend on many things - open the dialog and see what's available. One option that I see is $FileDir$ which I imagine would be the directory of the source code file.
I think I found the solution. Intellij was actually causing the issue by implicitly setting the src folder as the source folder. I found it by going to the module setting within Intellij.
When I ran the same from a command prompt, the correct working directory i.e. D:\my-app\src\ is selected.

Adding external jar in classpath placed in home dir

I am working on a java project which consumes an external jar from another project. This external jar cannot be checked-in in lib folder as it evolves continuously. So we have planned to keep the latest jar inside a folder,say 'ExtJar', under User's Home dir.
The question is how do I modify classpath to point to this jar from home dir?
So, I was looking for something like and should work for all OS platforms-
classpathentry kind="lib" path="MyHomeDir/ExtJar/myExternalJar.jar"
where MyHomeDir is a variable I defined as per the link -
- Use Eclipse classpath variable to replace absolute "sourcepath" path?
I looked into above link to add a variable but apart from this I also want this variable to point to appropriate home dir depending on OS, i.e C:\Users\\ExtJar\ for Windows OR /home//ExtJar for linux etc.
Is there any way to programatically modify value of this variable to point to home dir after evaluating which OS its being run on?
The point of a Classpath Variable is that it's value is not the same for all workspaces; each workspace defines where the variable points to.
You can still use a Classpath Variable to solve your problem, though. For example, create a variable called EXT_JAR_HOME and point it to your C:\Users\your.name\ExtJar folder. Then in the project build path, use Add Variable... to select and **Extend...* it, selecting the actual JAR file. That will result in the project's build path having an entry like EXT_JAR_HOME/ExternalJar.jar. Then each developer workspace will just need to, one time, defineEXT_JAR_HOME` and point it to the correct path. Linux users' actual location will look different than Windows users, obviously.
The point is, Classpath Variables must be defined in each workspace, that's how they're designed to work.

Create folder in jar file dir

Im looking for a solution to create a new folder in the folder, where the .jar file is located.
So if i have a test.jer file in C:\test\temp I would like to be able to create a new folder (newFolder) : C:\test\temp\newFolder.
Anyone know how to do this.
I have tried to use
System.getProperty("user.dir").
But this only gives me the correct, if i double click the jar file.
I need it to be run from a scheduler and then the location is changed.
In general you cannot easily figure out where your JAR file is at runtime. The execution environment of your VM can tell you the user directory (as you said), but that is the directory from which the VM was started. So if you double click your JAR, that's actually the directory where the JAR is. But if you call java on the commandline, for example
c:\some\directory> java -cp c:\temp\test.jar main.Class
then "user.dir" will contain "c:\some\directory".
This lack of information is intentional, because it allows the VM to transparently load classes from different locations.
Your best choice to do what you want would be to pass the directory of choice as a commandline argument. And in the worst case, you could use "user.dir" as default. But what the best solution really is depends on why you want to place the directory where the JAR is.

Java can't find file when running through Eclipse

When I run a Java application that should be reading from a file in Eclipse, I get a java.io.FileNotFoundException, even though the file is in the correct directory. I can compile and run the application from the command line just fine; the problem only occurs in Eclipse, with more than one project and application. Is there a setting I need to change in the run configurations or build paths to get it to find the file correctly?
The problem is most likely that your application is using a relative pathname. As #BalusC says, relative pathnames can be problematic. But IMO, he goes way too far when he says "[y]ou should never use relative paths in java.io stuff".
When an application opens a file using (for example) the FileInputStream(File) constructor, relative pathnames are resolved relative to the "current directory" in a process described as follows in the javadoc for File.getAbsolutePath().
[...] Otherwise this pathname is resolved in a system-dependent way. On UNIX systems, a relative pathname is made absolute by resolving it against the current user directory. On Microsoft Windows systems, a relative pathname is made absolute by resolving it against the current directory of the drive named by the pathname, if any; if not, it is resolved against the current user directory.
So immediately, we see that the notion of "current directory" has different nuances on Windows and UNIX platforms. The second issue is that in pure Java you cannot definitively find out what the current directory is, and you certainly cannot change it for the current JVM using pure Java. (When the JVM starts, the "user.dir" system property is set to the current directory, but there is nothing stopping an application from changing the property so you cannot entirely rely on it. Furthermore, changing "user.dir" only changes the way that the empty path is resolved, not relative paths in general.)
So what should you do about this?
One option is to use absolute pathnames to refer to files. This is reliable in (almost) all cases, but using absolute pathnames can be problematic if the user has to enter the pathname, or
if you need to avoid hard-wired (or configured) absolute pathnames.
A second option is to use classpath relative pathnames and locate files relative to the application's installation directory. This works if that is what you need to do, but presents a problem if you need to pass a File to some library method. It also doesn't help if you are trying to find the user's application preferences. (In general, putting user preferences into the installation directory is a mistake ...)
A third option is to name a file relative to some absolute directory that you get from somewhere else; e.g. new File(System.getProperty("home.dir"), "foo/bar");.
The final option is to use relative pathnames, and assume that the user knowing what the current directory. For many applications that the user runs from the command line, this is the right solution.
In the particular case of Eclipse, there is a simple solution. Go to the "run configuration" that you are using to launch your application, open the "Arguments" tab, and click the "Other" radio button. Then enter an absolute pathname as the working directory for the launched application. When the child JVM is launched, it will have the specified working directory as its current directory.
Another option is to simply figure out what directory the "current path" points to in your environment -- whatever that is. Once you figure out, you can choose your solution from there. Maybe that is to use an appropriate relative path to your file's location or relocating the file.
File testFile = new File("");
String currentPath = testFile.getAbsolutePath();
System.out.println("current path is: " + currentPath);
When you create a default Java application in Eclipse, you get this directory structure:
./ProjectName/ - root directory
./ProjectName/bin/ - output directory, containing .class files
./ProjectName/src/ - source directory, containing .java files
If your application requests "./data.txt" it will search for it relative to the root directory. This is the "working directory" and can be configured in the arguments tab as per Martin's reply above.
You say it works from the command line? This is likely because you're inside either the bin or src folders when you run the java binary. The working directory in this case is whichever directory the command prompt is currently inside. If, for example, you go into the /src/ directory, say javac *.java then run the files from there, it will search for "./data.txt" within the /src/ directory. If you go inside the /bin/ directory and run your application from there, it will look for the file relative to the /bin/ directory.
I was having a similar problem , I placed my files in a folder named cobolcopybooks inside the src folder and tried to access them inside my project using classloader.getResource("cobolcopybooks/demostud.cob")
but i was getting null pointer exception,i tried it several times by cleaning and building the workspaces after several failed attempts i realised that i was not refreshing the project to allow the files to get built along with the project. i.e these files should be visible along with other class files as at runtime the root directory will be bin directory and it's searching for those files there.
Assuming the user does not enter the full file path to the file
and enter something like "myfilenameonly".
File file = new File(".", args[0]) is necessary in this case to
locate the file (paying attention to the first argument passed).
All platforms: File.getParent() does not return the parent directory,
it should return ".." or the name of the parent directory in a file-system
specific way.
If you create the File "myfilenameonly" without specifying the full path
to the directory where it is located, the File.getParent(), for example,
will return null.
See further: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=1228537

Categories