Java: find current working JAR - java

I know that the system property "user.dir" returns the current working directory; the directory containing that file that is currently running.
I am wondering, how would I be able to go one step farther? I need to find the current working file. I am writing a little app that is kind of like an auto-updater, and I need to know the file that needs to be updated. For example, if I run a file from C:/test.jar I want to actually know, in code, that the current location of the file that is running is C:/test.jar so that I can write (new) data to it.
I've tried an approach like this:
ClassLoader loader = Test.class.getClassLoader();
System.out.println(loader.getResource("Test.class"));
However, it prints out:
3/5/12 7:50:16.914 PM [0x0-0x31031].com.apple.JarLauncher: rsrc:Test.class
(I am running this on a Mac - I got that line from the Console).
Any help is greatly appreciated. Thanks!

With credits to Fab in the following post:
Jar path+name from currently running jar
String path = Test.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String decodedPath = URLDecoder.decode(path, "UTF-8");

This will print the current file's path.
File f = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
System.out.println(f.getPath());

Related

How to Write Output Files from a JAR Program to Directory Outside the JAR?

tl;dr I'm more used to writing command-line scripts that can just output based on the current working directory, so I'm unsure what directory to use for output files in a program that will be launched from a JAR.
Program Description:
My program builds an HTML file from data given to it from the rest of the program, and then is supposed to write it to a file that we'll call "Output.html" for simplicity.
Relevant Code:
public void outputHTML()
{
String output = buildHTML();
// Expanded to explain my confusion better
String fileDirectory = ""; // ???
String fileName = "Output.html";
String fullPath = fileDirectory + "\\" + fileName;
try (BufferedWriter writer = new BufferedWriter(new FileWriter(fullPath)))
{
writer.write(output);
writer.close();
} catch (IOException e)
{
System.out.println("File not found.");
e.printStackTrace();
}
}
Problem
I don't know what to put the file directory as. Usually I run my programs from the command line and use ".\\Output.txt" as my output path, but I don't know where to put it if it's being run from a JAR.
The desired file structure is as follows:
Encompassing Folder
Program.jar
output
Output.html
Or alternatively (not sure if this makes it easier to understand or harder):
main\
main\Program.jar
main\output\
main\output\Output.html
Everything I can find on SE only relates to reading files that are both immutable and internal, but I'm trying to output a non-static file to a location outside of my jar.
Can anyone help with this? Thanks!
Misc Details
I'm using Eclipse without Gradle currently, because I don't know what Gradle is and new things are scary. If this particular problem would be easier to solve with Gradle, let me know and I'll look up more about it.
EDIT:
Added syntax highlighting to code block.
Formatted everything a bit better
Changed title to be more descriptive
You can use an absolute path: e.g. fileDirectory = "\\project\\test\\main\\output";
using normal slash should also work even on Windows ("/project/test/main/output")
Or use a relative path - this will start from the current working directory (user directory), the one where the JVM was started in - e.g. fileDirectory = "main\\output";

How to move a directory recursively using Apache commons-io, if destination exists?

I've been trying to get the following simple code to work and I don't understand why it's failing:
File dir = new File("/foo/bar"); // A path to a directory
File destDir = new File("/blah"); // The destination dir
FileUtils.moveDirectoryToDirectory(dir, destDir, !destDir.exists());
The dir directory contains files and directories. The destDir may, or may not contain bar.
The error I get is:
Caused by: org.apache.commons.io.FileExistsException: Destination '/blah/bar' already exists
What am I doing wrong here?
Would the built-in Files.move(...) do a better job (I am using JDK 1.8)? I tried that as well, but I couldn't seem to get it to work. This is simple stuff and I can't get why it's so much of an effort to implement...
Try copyDirectoryToDirectory() instead and then delete the original source...

Java getting current paths

I am having a little issue trying to figure out the best solution to the my path problems. I am running a java test that I want to get two things.
The absolute location of the project
The absolute location to the current class file that is running
I want to proper / or \ being on the OS version so the folder structure stays intact. I am currently using this but it is not exactly what I am looking for
final String parentDir = System.getProperty("user.dir");
final String path = "src/test/java/" + method.getDeclaringClass()
.getCanonicalName().replaceAll("\\.", "/") + ".java";
Any help would be appreciated. Thanks
Update: I am trying to get the url of the precompiled code as I need access to the comments in the code. This may change some of your guys answers
Update 2: Ok I got it to work.
final String path = new File(getClass().getResource("/").getFile())
.getParent().split("target")[0] + "src/test/java/" + method
.getDeclaringClass().getCanonicalName()
.replaceAll("\\.", "/") + ".java";
Thanks Guys
Given that you are calling this from MyClass you should call
File directory = (new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath())).getParentFile();
I had the same question once. In addition to Jatin's answer I had to add an toURI() to get the correct path on all platforms (Windows, etc.) and post 1.5 JVMs.
If say you are running from jar file:
new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getParent()+"/"
returns the folder containing the jar file.
Remove the .getParent() above to get path to the exact class file

FileInputStream and FileNotFound Exception

I am trying to retrieve a jrxml file in a relative path using the following java code:
String jasperFileName = "/web/WEB-INF/reports/MemberOrderListReport.jrxml";
File report = new File(jasperFileName);
FileInputStream fis = new FileInputStream(report);
However, most probably I didn't succeed in defining the relative path and get an java.io.FileNotFoundException: error during the execution.
Since I am not so experienced in Java I/O operations, I didn't solve my problem. Any helps or ideas are welcomed.
You're trying to treat the jrxml file as an object on the file-system, but that's not applicable inside a web application.
You don't know how or where your application will be deployed, so you can't point a File at it.
Instead you want to use getResourceAsStream from the ServletContext. Something like:
String resourceName = "/WEB-INF/reports/MemberOrderListReport.jrxml"
InputStream is = getServletContext().getResourceAsStream(resourceName);
is what you're after.
You should place 'MemberOrderListReport.jrxml' in classpath, such as it being included in a jar placed in web-inf\lib or as a file in web-inf\classes.
The you can read the file using the following code:
InputStream is=YourClass.class.getClassLoader().getResourceAsStream("MemberOrderListReport.jrxml");
String jasperFileName = "/web/WEB-INF/reports/MemberOrderListReport.jrxml";
Simple. You don't have a /web/WEB-INF/reports/MemoberOrderListReport.jrxml file on your computer.
You are clearly executing in a web-app environment and expecting the system to automatically resolve that in the context of the web-app container. It doesn't. That's what getRealPath() and friends are for.
check that your relative base path is that one you think is:
File f = new File("test.txt");
System.out.println(f.getAbsoluteFile());
I've seen this kind of problem many times, and the answer is always the same...
The problem is the file path isn't what you think it is. To figure it out, simply add this line after creating the File:
System.out.println(report.getAbsolutePath());
Look at the output and you immediately see what the problem is.

Files searching in Java

Because I asked wrong question last time, I want to correct my intention. How can I find file by name in specified folder? I have a variable with a name of this file and i want to find it in specified folder. Any ideas?
Maybe the simplest thing that works is:
String dirPath = "path/to/directory";
String fileName = "foo.txt";
boolean fileExistsInDir = new File( dirPath, fileName ).exists();
File is just a placeholder for a location in the file system. The location does not have to exist.
Use Finding files in Java as a starting point. It should have everything that you are looking for - ask another specific question if you get stuck.

Categories

Resources