How to get directory of a .java file [duplicate] - java

This question already has answers here:
How to get the current working directory in Java?
(26 answers)
Closed 3 years ago.
Part of my (java) code needs to access a database. When opening a connection it checks if the actual database file exists (I use sqlite). I want to make my code portable, so I want to avoid hard coding the path of the database file. Is there anyway in java to get the path of the .java file? Because I know exactly where the database is from the .java file accessing it.
I've tried using current directory with File but it doesn't give me the path of the actual .java file. When I use android studio the current directory is different than when I simply use a terminal.

The best way to get the path information would be using Paths and Path class from the java.nio. You can input an absolute path or relative path to the Paths.get(String str) to get the Path.
To get the project directory, you can use:
Paths.get(System.getProperty(“user.dir”))
Paths.get(“”)
It will get the complete absolute path from where your application was initialized.
The Paths.get() method will return a Path Object, on which you can call toString() or toUri() to get the path. Hope this helps.
Javadocs - Paths

Related

How to read from resource file outside jar [duplicate]

This question already has answers here:
How to read text file from classpath in Java?
(17 answers)
Closed 3 years ago.
I want to read the configuration file outside the jar, how should I do?
I tried classloader.getResourceAsStream("config.xml") and succeeded while I am running the code inside Intellij. Now I want to build the jars to a folder and place the config.xml under the same folder, not inside the jar, but the program fails to detect the config.xml.
Is there a graceful way of reading the config.xml instead of using File with relative path in the code, which doesn't work while debugging/running inside the IDE?
Yes, turn it into a system property, and provide it to anything running any Java process/application.
Let's say you have a config.xml file located inside /some/path/down/the/line/, then you can do: java --classpath ... -Dapp.config=/some/path/down/the/line/config.xml tld.domain.Application.
Then all you have to do in your Java code is to reference that name/path: final String configFile = System.getProperty("app.config");, and use any well-known routine to read it from there.
Basically, you have to make sure the file/path/location is provided somehow to the Java classpath.

What is the path in the memory for new File("test") [duplicate]

This question already has answers here:
Get the filePath from Filename using Java
(5 answers)
Closed 6 years ago.
What is the exact location in the memory when we write
File file = new File("test");
Instead we know that
File file = new File("C:\test");
will create it in C drive
It is gonna be your workspace by default. You can see it with this;
System.out.println(file.getAbsolutePath());
Unless you do anything to put it in a different directory or change Java's current working directory, the File object corresponds to a logical path underneath
System.getProperty("user.dir")
However, File doesn't necessarily correspond to a file on the file system; creating a new File(...) doesn't actually create a file on the file system. For example, you can call
file.exists()
and that may return false.
Ideone demo
The default is the workspace of your Java project.
If you somehow want to know where the default is you can show it with the following:
file.getAbsolutePath();
This returns a String object that you can then use to display in the Console.
See this list for future refrencens:
File file = new File("./../eclipse.ini");
file.createNewFile();
System.out.println(file.getAbsolutePath());// prints "C:\work\java\WS\java-io\.\..\eclipse.ini"
System.out.println(file.getCanonicalPath());// prints "C:\work\java\WS\eclipse.ini"
System.out.println(file.getParent()); // prints ".\.."
System.out.println(file.getAbsoluteFile().getParent());// prints "C:\work\java\WS\java-io\.\.."
System.out.println(file.getName()); // prints "eclipse.ini"
System.out.println(file.getPath());// prints ".\..\eclipse.ini"
System.out.println(file.isAbsolute());// prints "false"
Link to source: Click here
Assumptions
I assume that by in memory, you mean in disk.
Definitions
There are two types of paths. Quoting the definition from the wiki:
Absolute paths:
An absolute or full path points to the same location in a file system
regardless of the current working directory. To do that, it must
contain the root directory.
and, Relative Paths:
By contrast, a relative path starts from some given working directory,
avoiding the need to provide the full absolute path. A filename can be
considered as a relative path based at the current working directory.
If the working directory is not the file's parent directory, a file
not found error will result if the file is addressed by its name.
In order to help, we need to know which one you need (the absolute path, or the relative one).
Examples / Answer
For example, if you want to know the absolute path of your test.txt file, we need to know your working directory as well as its structure.
Imagining that you have a working directory like the following:
MyProject
---- Code
---- ----Main.c
---- Assets
---- ---- MyImage.png
---- Text.txt
In windows, it could look something like this:
C:\User\Aakash\Desktop\Myproject\text.txt
If you want to know the relative path, we just need to know the structure of your working directory:
text.txt
Hope it helps!

Change the Current Working Directory in Java [duplicate]

This question already has answers here:
Changing the current working directory in Java?
(14 answers)
Closed 7 years ago.
I have an eclipse rcp application, which i am launching by setting the working directory in the arguments tab of the debug configuration.
Meanwhile i needed to change the current working directory upon application start.
I've tried the following options : System.setProperty("user.dir", this.strDestination);
But it doesn't work if we use relative file path, as it refers to the older working directory. Only solution that is working in this regard is using getAbsoluteFile or getAbsolutePath (which is not a feasible option as relative paths is used in a number of location).
Any approach in this regard is highly appreciated.
I'm pretty sure you can't modify the current process' working directory. Instead you can use the File(String, String) constructor which creates a new File instance from a parent pathname string and a child pathname string.
Is your this.strDestination variable an absolute path?
According to this answer, you should use an absolute path in System.setProperty for the "user.dir" changes to take effect.
Note: I didn't have enough rep to add a comment. Hence adding as an answer.

Java getting a .wav file to run inside a .jar [duplicate]

This question already has answers here:
Load a resource contained in a jar
(3 answers)
Closed 8 years ago.
I am trying to get my .wav file to run from inside a .jar file once I have exported the program, and have researched extensively on the solution, but have found nothing that works.
Here is my current code:
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(new File("soundfile.wav")));
clip.start();
What can I do to fix this?
A resource contained within the context of a Jar file is commonly known as an embedded resource.
These resources can not be accessed like normal file system resources (ie via the File class), instead, you need to use Class#getResource, which will return a URL, which can be, in you case, passed to AudioSystem.getAudioInputStream
You could use something like...
clip.open(AudioSystem.getAudioInputStream(getClass().getResource("/path/to/resources/soundfile.wav")));
In this example, the path is relative to the package location of the class instance. That means if the resource is in another directory, you will need to to provide a full path to the resource

Read a file, which is included inside a jar [duplicate]

This question already has answers here:
Java resource as File
(6 answers)
Closed 9 years ago.
I have a jar file, say archive1.jar, resides in /home/ext/libs. This has a couple of classes, and also a text file (data.txt) at the root of the hierarchy of the jar. One of the classes of this jar (say Data.java) reads the file to initiate some internal data structure.
Now, the archive1.jar is included as a library of another program, called Parsing, which is executed in a completely different directory /home/progs (archive1.jar is specified in the classpath of the execution command of the program).
The problem I am facing is that now Data.java cannot understand the path of data.txt anymore, because it assumes that data.txt resides in /home/progs instead of being inside archive1.jar in /home/ext/libs.
My question is what change should I make inside Data.java in order for it to understand that the data.txt is inside the archive1.jar? In short, how to make Data.java be able to read data.txt inside archive1.jar, no matter where the calling program is.
Note: In thread Java resource as file, thing was a bit different, and also there was no answer to how to read the file inside the jar. One said it might be impossible.
The way to access resource files inside JAR archives is by using getClass().getResourceAsStream() . Using this ensures that the resource is loaded from the archive not from the filesystem. For example if you have data.txt in the same location as Data.java within the JAR archive, then you would access the data.txt in this way
InputStream is=getClass().getResourceAsStream("data.txt");
Once you have got an InputStream to the resource proceed with the way you like.

Categories

Resources