I'm having a problem with relative paths in my program. The absolute path to the file which I want to use is:
C:\Users\User\Documents\Projects\Project1\src\files\test.txt
Now, I'm unsure of how to make this a relative path, I've tried:
.\files\test.txt
Which throws an error at me, I don't know how to make this go up a folder and read from the test.txt file.
.\files\test.txt is correct, if and only if you run your program from the src directory, and use file IO to read the file, and not resource loading using the class loader.
Related
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 );
I'm trying to read a text file located in src/main/resources/test/file.txt. I'm trying to get the path of the file using String path = getClass().getResource("/text/file.txt").getFile(); but when I try to read it I get a FileNotFoundException. I tried putting many different paths, all of which failed. How can I go about doing this?
The idea of putting something into the src/main/resources tree is that it will be copied into the JAR file that you build from your project. It will then be available to your application via the Class methods getResource(String) and getResourceAsStream(String) methods.
When you are running in your application in the development environment, it is certainly possible to use FileInputStream etcetera to access the resource. But this won't work in production. In production, the resources will then be inside your app's JAR file. FileInputStream cannot open a JAR file and its contents by name.
When you do this:
getClass().getResource("/text/file.txt");
you get a URL for the resource, which will look something like this:
jar:file:/path/to/your.jar!/text/file.txt"
It is not possible to turn that into a pathname the FileInputStream will understand. Whatever you try will give you a FileNotFoundException ... or something that is not the resource you want to read.
So what to do?
You have a few options, depending on your application's requirements.
You can use getResourceAsStream and use the resulting input stream directly.
You can copy the contents of getResourceAsStream to a temporary file, and then use the pathname of the temporary file.
You can create an application specific directory (e.g. in the user's home directory) and extract the file you need from the JAR into the directory. You might do this the first time the application runs.
You could open the JAR file as a JarFile and use that API to open an InputStream for the resource. But this assumes that that the resources are in a JAR ... and on some platforms (e.g. Windows) you may encounter problems with file locking. (And it would be a bad idea to attempt to update the resource in the JAR.)
Try giving complete path of the file from the disk.
C:\Users\MyUser\Desktop\file name with extension
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
What is the best way to find a path relative to the folder where a java application is "installed"?
I have a class with a static method: public static void saveToFile(String fileName)
When I call it with an absolute path, it works, but what I really want is the relative path to where the application is run from, and a folder.
I have not deployed my application, but right now I want to find a path relative to the (Netbeans) project root, and a folder within called data: ProjectName\data\file.dat. Should I use the File class or make it into a URI or something?
Note that I prefer it to be system-independent and will still work if the application is deployed. Eventually the (relative) pathname will be stored in a properties file.
Sorry if this question is a duplicate, any help is appreciated.
What is the best way to find a path relative to the folder where a java application is "installed"?
OS manufacturers have been saying for a long time not to save files in the application directory.
Note that I prefer it to be system-independent and will still work if the application is deployed.
Instead put the File in a sub-directory of user.home. User home is where it should be possible to establish a file object that can be read or written. It is also a place that is reproducible across runs, and platform independent.
If you deploying as a jar, its possible to obtain the jar file name and path the current code is working in like this:
new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());
(from How to get the path of a running JAR file?)
Here you go:
String path = System.getProperty("user.dir");
To find relative path to current working directory say new File(".").
If you want to know absolute path of current working directory you can write new File(".").getAbsolutePath() or File(".").getAbsoluteFile()`.
I hope this answers your question. I am sorry if I did not understand you correctly.
To get the absolute path to a file use new File().getCanonicalFile().
new FileOutputStream(new File(".\\target\\dataset.xml").getCanonicalFile())
Given the following directory structure:
working-directory
subfolder1
file1.wav
file2.wav
file3.wav
subfolder2
file4.wav
file5.wav
file6.wav
subfolder3
file7.wav
file8.wav
file9.wav
jar-that-im-running.jar
I need to get the path to each wav file. I figured that since the folder is in the working directory, and is thus part of the classpath (if my assumption is wrong, I'd just add the working directory to the classpath), I could just run:
String path = ClassLoader.getSystemResource("file1.wav");
or
String path = ClassLoader.getSystemResource("/file1.wav");
but it wouldn't work, unless I specified the folder the wave file was in. This would be fine, but I wouldn't know what folder each wave file is in; I only know their names. I'm going to process all the files one way or another, but the order that I do depends on a config file. Also, I am not going to edit these files directly. Instead, I'm going to be passing them off as arguments to a ProcessBuilder. Since some of the directories in the path may have spaces, which get converted to %20 in URLs, I figured I could convert them with path.replaceAll("%20", " "). Will I be better off using files, or is there a way to get a specific wav file, without knowing its parent folder.
Did you try getting from the class loader as a system resource? Here's a snippet of code to illustrate:
String path = ClassLoader.getSystemResource("subfolder1/file1.wav");