I have a test data folder in my java project... something like this
Project
src Folder
testData Folder
How can I get the data folder using java, previously we have a hardcoded the in a constant, but now we are using a CI tool and I want to avoid the hardcoded path.
its is very fine to hardcode the testdata folder, but the
point is that it should be a relative path:
At the top of the test class you can just write
static final String TEST_PATH = "./testdata/";
Note that this is relative to the project.
If you want to convert such a relative path to an absoulte one:
String absoluteTestPath = new File(TEST_PATH).getAbsolutePath();
Take the input parameter and create a new File Object. The Java file object will provide getPath(), getAbsolutePath(), and getCanonicalPath(). Be careful with the file systems. If you are swapping between Windows/Linux/Mac/etc, you may have issues with translating paths between source and destination. I assume you source and destination are on the same file system in the example below.
File f = new File(pathStr);
String absPath = f.getAbsolutePath();
How about using Paths?
Paths.get("your-relative-path-here").toAbsolutePath()
Well, I solved my issue in the following way
public static final String Path_TestData = System.getProperty("user.dir") + "\\TestData\\";
For src
static String SRC_PATH = new File(".").getCanonicalPath()+System.getParameter("file.separator")+SRC;
// where SRC is the name of your source folder
For testdata:-
static String TEST_PATH = "./testdata/";
Related
private static final String FILE_PATH = "MessageCompare\\src\\main\\resources\\json\\test.json";`
File file = new File(FILE_PATH);
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file.getAbsolutePath())));`
In my computer, file.getAbsolutePath() return
D:\Dev\Tool\MessageCompare\MessageCompare\src\main\resources\json\test.json
In other computer, file.getAbsolutePath() return
D:\Dev\Tool\MessageCompare\src\main\resources\json\test.json
Why does absolute path of file return one more node than others' computer?
It could be better to use relative path to guarantee cross-platform.
Usually, two ways to get resource:
getClass().getResourceAsStream()<Non static method> & xxx.Class.getResourceAsStream()<static method>
getClass().getClassLoader().getResourceAsStream()<Non static method> & xxx.Class.getClassLoader().getResourceAsStream()<static method>
What's the difference?
Please notice this structure
About #1, it use:
InputStream in = getClass().getResourceAsStream("/json/rti.json");
For #2, it use: InputStream in = getClass().getClassLoader().getResourceAsStream("json/rti.json");
You shouldn't rely on the Absolute path of a file for this very reason, it all depends on the location from which the other person is running the code. In your case there is an additional MessageCompare directory.
Instead, use the class loader to load the file:
MyClass.class.getResourceAsStream("/myFile.txt");
That way your code will be more portable.
File file = new File(FILE_PATH);
This line creates a file. The path of the file depends on your project folder and setup. If your workstation includes another folder inside named "MessageCompare" and your project is set up in that folder, that may be the reason you are getting an extra node.
I have a URL that I get as below:
String jarFilePath = getClass().getProtectionDomain().getCodeSource().getLocation()
This would get me the complete path to the jar file. Now how do I jump one folder up and append some other path to it? For example., if the jarFilePath is something like:
c:/path/to/jar/file.jar
I want to jump one folder up and append another relative path like below:
c:/path/to/resources/path/to/resources/
Where the folders resources and jar are at the same directory level in the file system.
File f = new File("C:/path/to/jar/file.jar");
File dest = new File(f.getParentFile().getParentFile(), "resources/path/to/resources");
Just use the File-Object, that makes a lot of things easier:
import java.io.File;
String pathname = "c:/path/to/jar/file.jar";
File f = new File(pathname);
String p = f.getParent();
Try and use a File object:
File jarFile = new File(jarFilePath);
File newFolder = new File( jarFile.getParentFile().getParentFile(), "resources/path/to/resources");
If you want to use the path as a string, try using Apache Commons IO's FilenameUtils:
String resourcesPath = FilenameUtils.normalize( FilenameUtils.getPath(jarFilePath) + "/../resources/path/to/resources");
You have several ways.
You can split the path into it's elements and rebuild it until array.length -3 (-1 would be filename, -2 the last folder)
You could simple remove the file and append another ../ (which just means: "Go one directory back") (that would be something like this then: c:/path/to/jar/../resources/path/to/resources/)
You gould use a regex to get rid of the last folder and file. something like /[^/]+/[^/]+$
String dirPath = fileObj.getParentFile().getAbsolutePath();
system.out.println(dirPath);
I tried this way but its returning the Java Project Path that is Workspace path..
.getParentFile() is probably returning the parent directory, which depending on the location of your file could be the project directory. If fileObj is an object of type File, just try using fileObj.getAbsolutePath() instead.
So try this:
File fileObj = new File("myFile.xls");
String dirPath = fileObj.getAbsolutePath();
System.out.println(dirPath);
This should result in output similar to:
C:/[your project directory]/myFile.xls
JavaDoc for getParentFile():
http://docs.oracle.com/javase/1.4.2/docs/api/java/io/File.html#getParentFile()
Assume standard maven setup.
Say in your resources folder you have a file abc.
In Java, how can I get absolute path to the file please?
The proper way that actually works:
URL resource = YourClass.class.getResource("abc");
Paths.get(resource.toURI()).toFile();
It doesn't matter now where the file in the classpath physically is, it will be found as long as the resource is actually a file and not a JAR entry.
(The seemingly obvious new File(resource.getPath()) doesn't work for all paths! The path is still URL-encoded!)
You can use ClassLoader.getResource method to get the correct resource.
URL res = getClass().getClassLoader().getResource("abc.txt");
File file = Paths.get(res.toURI()).toFile();
String absolutePath = file.getAbsolutePath();
OR
Although this may not work all the time, a simpler solution -
You can create a File object and use getAbsolutePath method:
File file = new File("resources/abc.txt");
String absolutePath = file.getAbsolutePath();
You need to specifie path started from /
URL resource = YourClass.class.getResource("/abc");
Paths.get(resource.toURI()).toFile();
Create the classLoader instance of the class you need, then you can access the files or resources easily.
now you access path using getPath() method of that class.
ClassLoader classLoader = getClass().getClassLoader();
String path = classLoader.getResource("chromedriver.exe").getPath();
System.out.println(path);
There are two problems on our way to the absolute path:
The placement found will be not where the source files lie, but
where the class is saved. And the resource folder almost surely will lie somewhere in
the source folder of the project.
The same functions for retrieving the resource work differently if the class runs in a plugin or in a package directly in the workspace.
The following code will give us all useful paths:
URL localPackage = this.getClass().getResource("");
URL urlLoader = YourClassName.class.getProtectionDomain().getCodeSource().getLocation();
String localDir = localPackage.getPath();
String loaderDir = urlLoader.getPath();
System.out.printf("loaderDir = %s\n localDir = %s\n", loaderDir, localDir);
Here both functions that can be used for localization of the resource folder are researched. As for class, it can be got in either way, statically or dynamically.
If the project is not in the plugin, the code if run in JUnit, will print:
loaderDir = /C:.../ws/source.dir/target/test-classes/
localDir = /C:.../ws/source.dir/target/test-classes/package/
So, to get to src/rest/resources we should go up and down the file tree. Both methods can be used. Notice, we can't use getResource(resourceFolderName), for that folder is not in the target folder. Nobody puts resources in the created folders, I hope.
If the class is in the package that is in the plugin, the output of the same test will be:
loaderDir = /C:.../ws/plugin/bin/
localDir = /C:.../ws/plugin/bin/package/
So, again we should go up and down the folder tree.
The most interesting is the case when the package is launched in the plugin. As JUnit plugin test, for our example. The output is:
loaderDir = /C:.../ws/plugin/
localDir = /package/
Here we can get the absolute path only combining the results of both functions. And it is not enough. Between them we should put the local path of the place where the classes packages are, relatively to the plugin folder. Probably, you will have to insert something as src or src/test/resource here.
You can insert the code into yours and see the paths that you have.
To return a file or filepath
URL resource = YourClass.class.getResource("abc");
File file = Paths.get(resource.toURI()).toFile(); // return a file
String filepath = Paths.get(resource.toURI()).toFile().getAbsolutePath(); // return file path
I have this issue of accessing a file in one of the parent directories.
To explain, consider the following dir structure:-
C:/Workspace/Appl/src/org/abc/bm/TestFile.xml
C:/Workspace/Appl/src/org/abc/bm/tests/CheckTest.java
In the CheckTest.java I want to create a File instance for the TestFile.xml
public class Check {
public void checkMethod() {
File f = new File({filePath value I want to determine}, "TestFile.xml");
}
}
I tried a few things with getAbsolutePath() and the getParent() etc but was getting a bit complicated and frankly I think I messed it up.
The reason I don't want to use "C:/Workspace/Appl/src/org/abc/bm" while creating the File instance is because the C:/Workspace/Appl is not fixed and in all circumstances will be different at runtime and basically I don't want to hard-code.
What could be the easiest and cleaner way to achieve this ?
Thank you.
You should load it from Classpath in this case.
In your CheckTest.java, try
FileInputStream fileIs = new FileInputStream(CheckTest.class.getClassLoader().getResourceAsStream("org/abc/bm/TestFile.xml");
Use System.getProperty to get the base dir or you set the base.dir during application launch
java -Dbase.dir=c:\User\pkg
System.getProperty("base.dir");
and use
System.getProperty("file.separator");
What could be the easiest and cleaner way to achieve this ?
For accessing static resources use:
URL urlToResource = this.getClasS().getResource("path/to/the.resource");
If the resource is expected to change, write it to a sub-directory of user.home, where it is easy to locate later.
First of all, you can't get a reference to the source file path on runtime.
But, you can access the resrources included at your classpath (where you complied .class files will be).
Normally, your compiler will copy the xml file included at your srouce directory into the build directory, so at last, you could end up having something like this:
C:/Workspace/Appl/classes/org/abc/bm/TestFile.xml
C:/Workspace/Appl/classes/org/abc/bm/tests/CheckTest.class
Then, with your classpath pointing to the compiled classes root dir, you get the resources from this directory, using the ClassLoader.getResource method (or the equivalent Class.getResource() method).
public class Check {
public void checkMethod() {
java.net.URL fileURL=this.getClass().getResource("/org/abc/bm/tests/TestFile.xml");
File f=new File( fileURL.toURI());
}
}
One could do this:
String pathOfTheCurrentClass = this.getClass().getResource(".").getPath();
File file = new File(pathOfTheCurrentClass + "/..", "Testfile.xml");
or
String pathOfTheCurrentClass = this.getClass().getResource(".").getPath();
File filePath = new File(pathOfTheCurrentClass);
File file = new File(filePath.getParent(), "Testfile.xml");
But as Tomas Naros points out this gives you the file located in the build path.
Did you try
URL some=Test.class.getClass().getClassLoader().getResource("org/abc/bm/TestFile.xml");
File file = new File(some.getFile());