Dynamic filepath in Java (writing and reading text files) - java

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.

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

Trying to use Java file.getAbsolutePath() to get the absolute path of a file

I'm working on a simple project, and i'm trying to get the absolute path of a file. This is what i'm trying:
String s = "file.txt";
System.out.println(new File(s).getAbsoluteFile().getAbsolutePath());
The output is:
C:\Users\Marcello\Desktop\Java Workspace\Simple Project\file.txt
Where "Simple Project" is the name of the project where the code is.
But the output should be:
C:\Users\Marcello\Desktop\file.txt
That is where i created the .txt file.
I also tryed with file.getCanonicalFile() and "file.getCanonicalPath()". And i've had the same issue.
In this project i'm using a text file, but i want it to work with folders too. So if someone knows a solution also for folder, i'd like to see it.
Sorry for my english but it's not my mother-tongue, thanks in advance.
EDITED:
I think the absolute path should be:
C:\Users\Marcello\Desktop\file.txt
Because i created the .txt file by right-clicking on the desktop....
Here is a screenshot of my desktop:
File is not an actual file, it is just a reference to a file path which may or may not exist. The file you created on your desktop has nothing to do with the File object you created in Java. The output is telling you, not where your expected file is, but where the File object's reference is going to go looking for it if you try to open the file.
To find an actual path to a file in an unknown location, you'll have search for it, as in "Recursively list files in Java".
Since you say that the file is in your current location, File just adds that in front of it. If you execute your program in another directory, the path would be something else. Java does not check if the file exists and java can't know where you created a file named that - and there might be multiple files named so.
If you want to access a file that is not in your current work directory (you can see that using System.getProperty("user.dir)), you need to give it a path in front of it - no matter if relative or absolute, but java can't guess where your file is.
The easiest way to do this for any file whether it be on the desktop or wherever would be to first browse for the file.
Second, select the file.
Third, use code to get the absolute file path of the file you selected.
To do that, you can use something like this:
JFileChooser choose = new JFileChooser();
choose.showOpenDialog(null);
File f = choose.getSelectedFile();
String filePath = f.getAbsolutePath();
Otherwise, IF AND ONLY IF your file is located on the desktop or if the desktop is somewhere in the file path, then you can use this:
File f = new File(System.getProperty("user.home") + "/Desktop" + "\\file.txt");
if(f.exists())
String filePath = f.getAbsolutePath();
Hope this helps!!
This code goes directly to the desktop and then gets the file you hardcoded in.

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

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"

Trying to update the file in src/web/prod folder (jsp)

I am using jboss, eclipse and svn together. I have to files in my test folder: test/create.jsp and test/data.txt . What I want to do is when I call my create.jsp it will update my data.txt . Obviously I want my data.txt to stay where it is as other scripts are tryong to read from it.
I have tried dozens of new ways to put the path to my File object but for some reason it creates the file under jboss war folders.
Tried:
ServletContext app = getServletContext();
String path1 = app.getRealPath("/");
File f = new File(path1);
// AND
File f = new File("../../data.txt");
Assuming that /test folder is located in the webcontent, then you need the following:
String absolutePath = getServletContext().getRealPath("/test/data.txt");
File file = new File(absolutePath);
or
String webcontentRoot = getServletContext().getRealPath("/");
File file = new File(webcontentRoot, "test/data.txt");
Do you see it? The Java IO only understands local disk file system paths, not URL's or paths outside the context. The ServletContext#getRealPath() is to be used to convert a relative web path to an absolute local disk file system path which in turn can be used further in the usual Java IO stuff. You should never use relative paths in Java IO stuff. You will be dependent on the current working directory which may differ per environment/situation.
That said, you normally don't want to write files to the webcontent. They will get lost whenever you redeploy the WAR. Rather create a fixed disk file system path somewhere else outside the webapp and make use of it. Or even better, make use of an independent SQL database :)

Categories