Java can't get relative path for file - java

Image DescriptionTrying to access a test.txt file that is in the same location as my HelloController.java file but for some reason, it is showing that the file does not exist. I've tried moving the file around but it does not work.
Using the absolute path works, but this is a shared project so it will be ran on other computers. Any suggestions would be much appreciated.

Your best bet is to add it to the class path and reading it as a class path resource.

The relative path root is your "working directory". Which means if you try to access "." you will start at your working directory. This directory is only set once for your application and is normally the folder which was opened when you started it.
When working with IDEs (like in your case) the working directory will be the root folder of your project (So the folder in which the pom.xml and src folders are located.
If you want to access the file via the normal file API you are currently using, just put the file in that diretory and it should work (given you share it with the other people in the same location).
If you need the file to be inside your generated output jar-file, you will need to use the File as a resource (See duffymo's answer), as the file does not exist by itself on the file system, but as a file inside your jar-file.
If you want to know your current working directory, you can create a File refrence to "." and expand it to an absolute path (Which will replace refrences like "." and ".." and generate a file path from your root) and then write it to the console. This would look something like this:
// Get refrence to the current working directory
File workingDirectoryReference = new File(".");
// Convert it to an absolute path string
String absolutePath = workingDirectoryReference.getAbsolutePath();
// Output to console
System.out.println(absolutePath );

Related

How to get absolute path of files outside the current working directory [java]

I'm trying to read a file outside my current working directory using File and URL classes in Java. I know that the current working directory is 'represented' by a . by default.
Assuming my Java class is under /folders/Desktop/MyClass.java, if I want to read a file file1.txt in /folders/Desktop/file1.txt, I can do the following:
URL url = getClass().getResource("./file1.txt"); /* or "./anotherFolder/../file1.txt", or simply "file1.txt"*/
File f = new File(url.getPath());
and everything works as expected.
But what should I do to read a file that is not inside the current working directory and that is not inside a subdirectory of it? For example, if the file's path is /folders/file1.txt? I searched everywhere, but can't find anything. I tried ../file1.txt, ./../file1.txt and others, but nothing works. Maybe I missed something, or maybe I haven't searched in the right places.
If you don't give a path to the file name, then java is searching in the directory where the app is running.
Example:
This will print true if the file is in the main folder of the project...
public static void main(String[] args) {
final File foo = new File("asd.txt");
System.out.println(foo.exists());
}
EDit:
if the file if not in that folder then you can go "up" in the folder structure with the "./" or "../" operators...
or go deeper in the folders File("/src/asd.txt") for example is the file were inside the src folder..
If you want to access a file that is not below the current working directory you would either traverse the file system programmatically or you would get an absolute path by user input and construct the java.io.File object with new File(absolutePathAsString). You might also consider using the newer java.nio.file API.

Where the file will be located while using IO Streams in Java In Eclipse IDE?

I want to print the output in a file. I am using PrintWriter IO stream to add the data to file. When I want to check it, I don't know where the file is located. I am using Eclipse IDE.
PrintWriter writer=new PrintWriter("output.txt","UTF-8");
writer.println("Barcode Reader");
So can any one point me to where the file will be located?
I had this problem initially when I switched to using Eclipse. The current relative path is set to the project directory. The following code snippet will explain this better.
Path currentRelativePath = Paths.get("");
String myPath = currentRelativePath.toAbsolutePath().toString();
System.out.println("Current relative path is: " + myPath);
Note that the Path object is received from a get method in Paths((plural)). They are located in java.nio.file.
Further information about this can be found in the Path Operations page.
Does that solve your problem?
It will be present in your project's root folder.
Just open your project folder from your workspace using Explorer and it will be there.
With a filename like "output.txt" it will be placed into the current working directory.
Unless you specify otherwise, in Eclipse that will be the root directory of your project.
You may have to click "Refresh" for it to show up in the File Explorer.
If you give you file name directly like C:\java\workspace\ocpjp7 (a Windows
directory) or /home/nblack/docs (the docs directory of user nblack on UNIX), you can find your file in those directories. But if you don't give the full path, it will be in your current working directory.
"output.txt" -> root
"src/resources/output.txt" -> in resources package
At first you should create this file with File in directory you want.Next step to write data into the file. Your file will be located in directory you want , you set when file has created.
Also check this class FileInputStream

How to fix this java.io.FileNotFoundException?

I'm trying to load a .csv file in a program but for some reason, it's unable to find the file. Where should I place the file?
Console
It looks like the file is in the src directory... which almost certainly isn't the working directory you're running in.
Options:
Specify an absolute filename
Copy the file to your working directory
Change the working directory to src
Specify a relative filename, having worked out where the working directory is
Include it as a resource instead, and load it using Class.getResourceAsStream
The file is located in the src directory so in order to access it you should use
src/Elevator.csv
As long as files are located inside your project folder you can access them using relative paths.
For example if a file is located under the Elevator folder then you access the file by using only its filename.
Elevator.csv
A good principle when using additional files in your project is creating separate folders from the ones that the source files are located. So you could create a folder resources under the project folder and place your file there. You can access then the file by using
resources/Elevator.csv
the path which it is trying to read is surely not exact as the path in which that file is actually present.Try printing absolute path of that file and compare it with actual path of your file.
I tried with all the above mention solution, but it didn't work..
but i went to my project folder and delete the target and tried to compile the project again. it then worked successfully

Java JAR: Writing to a file

Currently, in my eclipse project, I have a file that I write to. However, I have exported my project to a JAR file and writing to that directory no longer works. I know I need to treat this file as a classpath resource, but how do I do this with a BufferedWriter?
You shouldn't have to treat it as a classpath resource to write to a file. You would only have to do that if the file was in your JAR file, but you don't want to write to a file contained within your JAR file do you?
You should still be able to create and write to a file but it will probably be relative to the working directory - the directory you execute your JAR file from (unless you use an absolute path). In eclipse, configure the working directory from within the run configuration dialog.
You're probably working in Linux. Because, in Linux, when you start your application from a JAR, the working directory is set to your home folder (/home/yourname/). When you start it from Eclipse, the working directory is set to the project folder.
To make sure you really know the files you are using are located in the project folder, or the folder where your JAR is in, you can use this piece of code to know where the JAR is located, then use the File(File parent, String name) constructor to create your files:
// Find out where the JAR is:
String path = YourClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
path = path.substring(0, path.lastIndexOf('/')+1);
// Create the project-folder-file:
File root = new File(path);
And, from now on, you can create all your File's like this:
File myFile = new File(root, "config.xml");
Of course, root has to be in your scope.
Such resources (when altered) are best stored in a sub-directory of user.home. It is a reproducible path that the user should have write access to. You might use the package name of the main class as a basis for the sub-directory. E.G.
our.com.Main -> ${user.home}/our/com/

How to specify filepath in java?

I have created a java application for "Debian Linux." Now I want that that application reads a file placed in the directory where the jar file of that application is specified. So what to specify at the argument of the File Object?
File fileToBeReaded = new File(...);
What to specify as argument for the above statement to specify relative filepath representing the path where the jar file of the application has been placed?
If you know the name of the file, of course it's simply
new File("./myFileName")
If you don't know the name, you can use the File object's list() method to get a list of files in the current directory, and then pick the one you want.
Are you asking about escape character issues?
If that is the case then use forward slashes instead of backward slashes like
"C:/Users/You/Desktop/test.txt"
instead of
"C:\Users\You\Desktop\test.txt"
Using relative paths in java.io.File is fully dependent on the current working directory. This differs with the way you execute the JAR. If you're for example in /foo and you execute the JAR by java -jar /bar/jar/Bar.jar then the working directory is still /foo. But if you cd to /bar/jar and execute java -jar Bar.jar then the working directory is /bar/jar.
If you want the root path where the JAR is located, one of the ways would be:
File root = new File(Thread.currentThread().getContextClassLoader().getResource("").toURI());
This returns the root path of the JAR file (i.o.w. the classpath root). If you place your resource relative to the classpath root, you can access it as follows:
File resource = new File(root, "filename.ext");
Alternatively you can also just use:
File resource = new File(Thread.currentThread().getContextClassLoader().getResource("filename.ext").toURI());
I think this should do the trick:
File starting = new File(System.getProperty("user.dir"));
File fileToBeRead = new File(starting,"my_file.txt");
This way, the file will be searched in the user.dir property, which will be your app's working directory.
You could ask your classloader to give you the location of the jar:
getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
...but I'd suggest to put the file you are looking for inside your jar file and read it as a resource (getClass().getResourceAsStream( "myFile.txt" )).
On IntelliJIDEA right click on the file then copy the absolute path, then in the double quotation paste the path as filePath.
for example it should be something like this:
"C:\\Users\\NameOfTheComputerUser\\IdeaProjects\\NameOfTheProject\\YourSubFolders\\name-of-the-file.example"

Categories