Getting the current user's path rather than application path in java - java

I am trying to get the current users path in a giant command line application that has multiple dependencies. Every time a "." is used, it gives me the application path (where the jar exists), rather than the current user path(where the call is being made).
So, when this is ran:
File file = new File(".");
System.out.println(file.getCanonicalPath());
Gives me the path that the application exists in.
But when I create a separate small application, and use the same code. Call the jar from a different directory, it gives the current user path.
I am using JSAP command line parser for the command line arguments, its acting the same way. How can this be solved? I want my big application to get the current user path, not application path.
What would cause them to behave differently?

I think you'll find that the batch file (/shell script) which launches your "big application" is changing directory to the main jar file's directory before kicking off Java, which is why your simple test application returns the user's working directory for new File(".") while the big app returns the jar file's directory.
Try storing the user's CWD early in the batch file and then passing it to Java:
set savedcwd=%cd%
... later on ...
java "-Dsavedcwd=%savedcwd%"
then in your application
String savedcwd = System.getProperty("savedcwd");

http://www.mindspring.com/~mgrand/java-system-properties.htm
you want "user.home" property, like
System.getProperty("user.home");

String currentDir = new File(".").getAbsolutePath();
OR
System.getProperty("user.dir")

1) As stated above, if you want to get "current directory", one way is to use File(".").getAbsolutePath()
2) If you want to get the user's $PATH variable (or any environment variable), use System.getenv():
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/System.html

Related

Windows 10 - ObjectOutputStream can't find relative paths because current working directory is System32

When I call method
System.out.print(new File("").getAbsolutePath())
from main I get the project workspace
C:\Users\darkr\Desktop\NuovoWorkSpace\ProjectName.
When it gets called by our save() method, which serializes what we need, suddenly the absolute path given from
new File("").getAbsolutePath()
becomes System32 (for me) and Desktop directory for my colleagues.
We're using gitHub to share our changes but this makes it almost impossible.
The code you have new File("").getAbsolutePath() is commonly used to determine the current directory from where you launched your application's main(String[]) method. So it looks like you are running from C:\Windows\System32 not on desktop folder.
The easiest way to fix your issue is to edit your application shortcut (see .lnk file and set "Start in" folder), or cd to be in an appropriate writable directory before running your application, or change your application to use file chooser to pick the target location for saves.
Alternatively pick sensible output paths for writing to instead of "", some good candidates are:
// Local user profile
File folder = new File(System.getenv("LOCALAPPDATA"), "myfolder");
// Roaming user profile
File folder = new File(System.getenv("APPDATA"), "myfolder");
// Temp folder:
File folder = new File(System.getProperty("java.io.tmpdir"), "myfolder")
Some sites suggest one of the following lines to locate Desktop, but this is unreliable because it will not work if the folder has been moved or run on some non-English installations:
File maybeDesktop = new File(System.getProperty("user.home"), "Desktop");
Path maybeDesktop = Path.of(System.getProperty("user.home"), "Desktop");
If you want to read the exact location of user Desktop from Java, you need to use JNI/JNA/Panama call to Windows API functions SHGetFolderPath or SHGetKnownFolderPath.

How can I get the path of the compiled jar file via code?

I want to use image files for my java program, and for that I need File objects. But I have the problem that when I build my project, the project name has a .jar at the end of the name, making a File object like new File("..\\Project\\src\\ImageDirectory\\Image.png") useless, since the directory doesn't exist.
I've found out I could tecnically iterate through all the directorys on the computer but I don't want to do that because that could take some time with high amounts of directories and harddrives.
So, is there a reliable and easy way to get the directory the jar file is currently in?
My IDE is InellijIDEA
You can use Path to do this:
Path path = Paths.get(YourMainClass.class.getProtectionDomain().getCodeSource().getLocation().toURI());
Path have several methods to get more information.
For example, i have this JAR in Desktop and i am printing this:
System.out.println(path);
System.out.println(path.getRoot());
System.out.println(path.getParent());
The results are:
java -jar C:\Users\gmunozme\Desktop\Test.jar
C:\Users\gmunozme\Desktop\Test.jar
C:\
C:\Users\gmunozme\Desktop
Check that out,
Hope you can use it.

Where does .jar file look for input files?

I create a .jar file on my local computer (with ant/eclipse) then upload it to a server (foo/usr/share/java). I want my .jar file to read in a file called "example.txt". Where on my server do I need to save "example.txt" so that this happens? Alternatively, how should I alter the filepath in my code? I am happy hardcoding this one filepath as neither the file nor filepath will change. Thanks!
If you running your application at console, then save your text file at current folder. If your application works inside application server, then file will be searched in current folder of application server.
Best way to open exact file you need - use program argument.
In the Java programming language, every application must contain a main method whose signature is:
public static void main(String[] args)
This array is the mechanism through which the runtime system passes information to your application. For example:
java MyApp arg1 arg2
Each string in the array is called a command-line argument. Command-line arguments let users affect the operation of the application without recompiling it.
If you supply a relative pathname, it is relative to the user's current working directory when he executed the .jar file. If you provide an absolute filename, job done.
You should put the file in the same directory as your .jar file and your program should find it, but as chrylis mentioned, a command-line argument is the best.

relative path in Java

My program has to use certain files that reside in another directory. Right now I am using absolute path to specify the location of the files. But I know that the relative position of these files will remain the same compared to where my program is residing. How I can use relative path in Java to specify the location of these files?
For example my program is residing in
/home/username/project/src/com/xyz/
..and the target files are in..
/home/username/project/secure/
For example my program is residing in /home/username/project/src/com/xyz/
and the target files are in /home/username/project/secure/
Knowing the place where your program's source code resides does not help. What you need to know is the current directory of the program when it is executed. That could be literally anything. Even if you are launching the application from (for example) Eclipse, the application launcher allows you to specify the "current directory" for the child process in the Run configuration.
Your current path.
currentPath= /home/username/project/src/com/xyz/;
Relative path to "/home/username/project/secure/" folder is
relativePath= ../../../secure;
In Java you can use getParentFile() to traverse up the tree.
File currentDir = new File(".");
File parentDir = currentDir.getParentFile();
This will be safe as you are not using system dependent file separator (../)

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