How to specify filepath in java? - 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"

Related

Java can't get relative path for file

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 );

How to get the current path of a file and root project of the file?

Say I want to create a new folder somewhere in my project, so I would like to get the current working path where my code is running or the root path of the project.
I don't wanna to hardcode the path. I used getAbsolute() or getCanonicalFile() or System.property("user.dir") but it doesn't work as I want.
You can get the current working directory as
File cwd = new File("./");
If you then need to make this into an absolute path there is
cwd.getAbsolutePath();
You can create a new directory there with
File newDir = new File(cwd, "newDirectory");
newDir.mkdir();
But my code is somewhere else: /home/root/...../project/class.java
The current working directory is (usually) the directory where you start Java from. This is completely unrelated to where the jar files are, and this in turn is completely unrelated to where the source code is.
You need to set the current working directory properly when you start the Java program (not the compiler).
If you start from a shell, cd to where you need it to be. If you start from an IDE, there should be a setting.
Use like that
Path path = Paths.get("");
String s = path.toAbsolutePath().toString();
System.out.println(s);
You can use a relative path to get the root of the project. This code,
new File("myFolder").mkdir();
will create a new folder called myFolder in the root of your project. If you don't specify an absolute path, the compiler will always go to the root of your project.
If you want to work where your main class is (this is different from the root of your project), you can get the path of your main class like this:
URL mainPath = Main.class.getResource("Main.class");
(Replace Main with the name of your main class.)

Java FileOutputStream Default Creation Path

Let's say I have below code:
String fileName = "name.txt";
FileOutputStream fileOut = new FileOutputStream(fileName);
wb.write(fileOut);
This way, the file will be created under bin folder of the project.
However, if I specific fileName at a whole path:
String fileName = "c:/temp/name.txt";
this file will be created at c:\temp folder.
Am Correct? And Why this happen, how FileOutputStream work?
It's not about how FileOutputStream works, it's about the path that the operating system assigns to a process when it starts it
This path is called current working directory. From that directory all relative paths are calculated. A simple file name is a relative path (to the current working directory).
If you specify an absolute path then this path is used to create the file.
You can read more about paths on this wiki page.
If you don't specify an absolute path, e.g. if you only specify the file name, then your program or the operating system somehow needs to figure out, where to find that file. For that reason a running program always has a working directory. That happens to be the folder you start it from, by default.
Unless you specify an absolute path, the path is relative to current working directory.
If your current working directory is a bin folder in your project, it will be created there.
If you only specify the filename, it will be created in the current working directory. If you do specify an absolute path, it will of course be created at that path.
It's all about relative and absolute directories. Let's say that you specif path foo/bar. It'll create a file bar in foo directory of your working folder. The same applies for ../foo/bar it'll create a bar file in foo directory in the folder above the working dir. However, if you type C:\\Documents\ and\ Settings\User\Desktop\bar (or /home/user/Desktop/bar), it'll create a bar on your desktop. For more info take a look here.

How to get the path of a directory where my running jar file is?

I try to retrive a path of a directory where my executable jar file is situated.
That means: I have the following structure:
--> Application (this is a folder somewhere in my file system)
--> application.jar (this is my java application
--> SomeData (folder in the same directory like the application)
--> some other folders
......
When I start my application.jar via command line I want to parse some files inside the SomeData folder.
In https://stackoverflow.com/a/320595/1540630 they already showed how to get the current path of a running jar file but when I execute the statement:
System.out.println(XMLParser.class.getProtectionDomain().getCodeSource().getLocation().getPath());
...I just get the following:
/.../Application/application.jar
But I just want to have:
/.../Application/
Better to say in later steps I need
/.../Application/SomeData/SomeFolder/data.xml
Can someone help me please?
CodeSource.getLocation() gives you a URL, you can then create new URLs relative to that:
URL jarLocation = XMLParser.class.getProtectionDomain().getCodeSource().getLocation();
URL dataXML = new URL(jarLocation, "SomeData/SomeFolder/data.xml");
You can't simply do new File(...getCodeSource().getLocation().getPath()) as a URL path is not guaranteed to be a valid native file path on all platforms. You're much safer sticking with URLs and passing the URL directly to your XML parser if you can, but if you really need a java.io.File then you can use an idiom like this to create one from a URL.
Once you have the jar's location you can use
new File(new File(jarPath).getParent(), "SomeData/SomeFolder/data.xml");
Since you already have the path as a string. You can try the following
String path = XMLParser.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String parentFolder = new File(path).getParent();

Dynamic filepath in Java (writing and reading text files)

Okay, so I want to read a file name myfile.txt and let's say I'll be saving it under this directory:
home/myName/Documents/workspace/myProject/files myfile.txt
hmmm.. I want to know what I should pass on the File(filePath) as my parameter... Can I put something like "..\myfile.txt"? I don't want to hard code the file path, because, it will definitely change if say I open my project on another PC. How do i make sure that the filepath is as dynamic as possible? By the way, I'm using java.
File teacherFile = new File(filePath);
You can references files using relative paths like ../myfile.txt. The base of these paths will be the directory that the Java process was started in for the command line. For Eclipse it's the root of your project, or what you've configured as the working directory under Run > Run Configurations > Arguments. If you want to see what the current directory is inside of Java, here's a trick to determine it:
File currentDir = new File("");
System.out.println(currentDir.getAbsolutePath());
You can use relative paths, by default they will be relative to the current directory where you are executing the Java app from.
But you can also get the user's home directory with:
String userHome = System.getProperty("user.home");
You can do it:
File currentDir = new File (".");
String basePath = currentDir.getCanonicalPath();
now basePath is the path to your application folder, add it the exact dir / filename and you're good to go
You can use ../myfile.txt However the location of this will change depending on the working directory of the application. You are better off determining the base directory of you project is and using paths relative to that.

Categories