Java getting current paths - java

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

Related

Convert Windows style path into unix path in java code

I am working in a java code that was designed to run on windows and contains a lot of references to files using windows style paths "System.getProperty("user.dir")\trash\blah". I am in charge to adapt it and deploy in linux. Is there an efficient way to convert all those paths(\) to unix style (/) like in "System.getProperty("user.dir")/trash/blah". Maybe, some configuration in java or linux to use \ as /.
My approach is to use the Path object to hold the path information, handle concatenate and relative path. Then, call Path's toString() to get the path String.
For converting the path separator, I preferred to use the apache common io library's FilenameUtils. It provides the three usefule functions:
String separatorsToSystem(String path);
String separatorsToUnix(String path);
String separatorsToWindows(String path)
Please look the code snippet, for relative path, toString, and separator changes:
private String getRelativePathString(String volume, Path path) {
Path volumePath = Paths.get(configuration.getPathForVolume(volume));
Path relativePath = volumePath.relativize(path);
return FilenameUtils.separatorsToUnix(relativePath.toString());
}
I reread your question and realize you likely don't need help writing paths. For what you're trying to do I am not able to find a solution. When I did this in a project recently I had to take time to convert all paths. Further, I made the assumption that working out of the "user.home" as a root directory was relatively sure to include write access for that user running my application. In any case, here are some path problems I addressed.
I rewrote the original Windows code like so:
String windowsPath = "C:\temp\directory"; //no permission or non-existing in osx or linux
String otherWindowsPath = System.getProperty("user.home") + "\Documents\AppFolder";
String multiPlatformPath = System.getProperty("user.home") + File.separator + "Documents" + File.separator + "AppFolder";
If you're going to be doing this in a lot of different places, perhaps write a utility class and override the toString() method to give you your unix path over and over again.
String otherWindowsPath = System.getProperty("user.home") + "\Documents\AppFolder";
otherWindowsPath.replace("\\", File.separator);
Write a script, replace all "\\" with a single forward slash, which Java will convert to the respected OS path.

Java: find current working JAR

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

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.

getResource with parent directory reference

I have a java app where I'm trying to load a text file that will be included in the jar.
When I do getClass().getResource("/a/b/c/"), it's able to create the URL for that path and I can print it out and everything looks fine.
However, if I try getClass().getResource(/a/b/../"), then I get a null URL back.
It seems to not like the .. in the path. Anyone see what I'm doing wrong? I can post more code if it would be helpful.
The normalize() methods (there are four of them) in the FilenameUtils class could help you. It's in the Apache Commons IO library.
final String name = "/a/b/../";
final String normalizedName = FilenameUtils.normalize(name, true); // "/a/"
getClass().getResource(normalizedName);
The path you specify in getResource() is not a file system path and can not be resolved canonically in the same way as paths are resolved by File object (and its ilk). Can I take it that you are trying to read a resource relative to another path?

Categories

Resources