Reputation: 41
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);
Upvotes: 4
Views: 28031
Reputation: 137312
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
Upvotes: 1
Reputation: 20333
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");
Upvotes: 3
Reputation: 533492
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.
Upvotes: 0
Reputation: 72039
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());
Upvotes: 5