This is my project structure. I want to get the data folder's absolute path(/Users/user/IdeaProjects/project/data/post/sourceData) by using relative path, but the test I'm running is inside service folder, so the absolutePath is always shows "/Users/user/IdeaProjects/project/service/data/post/sourceData".
project
-data
-post
-sourceData
-service
-test
String relativePath = "data/post/sourceData";
Path absolutePath = Paths.get(relativePath).toAbsolutePath();
System.out.println(absolutePath);
I tried to set the working directory manually, but after I run the code it still print the error result, how can I fix this?
String newWorkingDirectory = "/Users/user/IdeaProjects/project/";
System.setProperty("user.dir", newWorkingDirectory);
String relativePath = "data/post/sourceData";
Path absolutePath = Paths.get(relativePath).toAbsolutePath();
System.out.println(absolutePath); // Outputs
Related
I have a file in java under the src folder, I want to get its path at runtime relative to the source folder.
For example-
myProject
-- src
-- packageOne
-- SomeFile.java
I would like to have the result packageOne/SomeFile.java. I couldn't find a way, I tried getPath(), getAbsoultePath() and every similar method.
You want to construct a relative path. AFAIK there is no ready function to use.
Given that you have one of the ancestor nodes (src) and you have SomeFile.java, the following code might work but I did not try...
File src = new File("...");
File somefile = new File("...");
String relpath = somefile.getName();
File cursor = somefile.getParentFile();
while (!cursor.getAbsolutePath().equals(src.getAbsolutePath()) {
somefile = cursor.getName() + File.pathSeparator + somefile;
}
System.out.println("relative path: "+relpath);
I have an XML file in a folder within my Java project, and I'd like to get its absolute path, so I can load it as a File in order to parse it(DOM). Instead of using an absolute/relative path, I want to specify only the file name, and get the absolute path after that. I tried to do this in a few different ways, but there is always a folder name missing from the path I get.
I get:
C:\Users\user\workspace\projectName\Input.xml<br>
instead of:
C:\Users\user\workspace\projectName\\**Folder1**\\Input.xml
-
File input = new File(project.getFile("Input.xml").getLocation().toString());`
File input = new File(project.getFile("Input.xml").getRawLocation().makeAbsolute().toString());
File input = new File(project.getFile("Input.xml").getLocationURI().getRawPath().toString());
File input = new File(project.getFile("Input.xml").getFullPath().toFile().getAbsolutePath());
How can I get the correct path, that includes that Folder1?
Reading your question (your project are in workspace directory) I suppose you're talking of a project in Eclipse.
Well the default directory where your app run into Eclipse is right the base dir of your project.
So if you run something like this in your main:
Files.newDirectoryStream(Paths.get("."))
.forEach(path -> {
System.out.println(path);
System.out.println(path.toFile().getAbsolutePath());
});
You should see all the files and directory that are in your project.
So if what you want is just the absolute path to your project run:
System.out.println(Paths.get(".").toFile().getAbsolutePath());
If you want open the resource Input.xml specifying only the name, I suggest to move all the files you need in a directory and run a method like this:
public static File getFileByName(String name, String path) throws IOException {
ArrayList<File> files = new ArrayList<>();
Files.newDirectoryStream(Paths.get(path))
.forEach(p -> {
if (p.getFileName()
.equals(name))
files.add(p.toFile());
});
return files.size() > 0 ? files.get(0) : null;
}
I want to search for files in a directory. Therefore I want to get the directory in a File object but i'm getting a file instead of a directory. This is what I'm doing, it prints false but I want it to be true.
URL url = getClass().getResource("/strategy/viewconfigurations/");
File folder = new File(url.toString());
System.out.println(folder.isDirectory());
How can I load this way a directory?
It seems path or String you will got from the URL object cause problem.
You passed file path which you will got from the url.toString().
You need to change below line
File folder = new File(url.toString());
with this line
File folder = new File(url.getPath());
You need path of that folder which will you get from URL.getPath() function.
I hope this is what you need.
If you need an alternative for Java 7+ to Yagnesh Agola's post for finding a directory from a classpath folder, you could you also the newer java.nio.file.Path class.
Here is an example:
URL outputXml = Thread.currentThread().getContextClassLoader().getResource("outputXml");
if(outputXml == null) {
throw new RuntimeException("Cannot find path in classpath");
}
Path path = Paths.get(outputXml.toURI());
Let's say I have a package: com.example.resources and inside it I have picture.jpg and text.txt - How can I use only the package path to identify the absolute filepath of picture.jpg and text.txt?
Is this correct?
File file1 = new File("/com/example/resources/picture.jpg");
file1.getAbsolutePath();
File file2 = new File("/com/example/resources/text.txt");
file2.getAbsolutePath();
"I'm trying to reference those files within the application so that when I deploy the application to different systems I won't have to reconfigure the location of each resource "
You don't want to use a File, which will load from the file system of the local machine, you want to load through the class path, as that's how embedded resources should be read. Use getClass().getResourceAsStream(..) for the text file and getClass().getReource(..) for the image
Your current path you're referencing looks like it should work, given the package name you've provided.
Take a look at this answer and this answer as some references.
I've figured out how to do it. Here is the code that I used:
public String packagePathToAbsolutePath(String packageName, String filename) {
String absolutePath = "File not found";
URL root = Thread.currentThread().getContextClassLoader().getResource(packageName.replace(".", "/"));
File[] files = new File(root.getFile()).listFiles();
for (File file : files) {
if (file.getName().equals(filename)) {
absolutePath = file.getName();
return absolutePath;
}
}
return absolutePath;
}
This method was really useful because it allowed me to configure the resource paths within the application so that when I ran the application on different systems I didn't have to reconfigure any paths.
I create a new folder Fold inside my eclipse project Proj. How do I get the path of Fold relative to Proj ? This folder will be used as place to store serialized objects. Will I be able to serialize and de-serialize my code using this relative path ?
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL url = classLoader.getResource("path/folder");
or
URL url = getClass().getResource("path/folder");
This code gets the path -
String absolutePath = new File(".").getAbsolutePath();
System.out.println(absolutePath);// Shows you the path of your Project Folder
int last = absolutePath.length()-1;
absolutePath = absolutePath.substring(0, last);//Remove the dot at the end of path
System.out.println(absolutePath);
String filePath = "MyFolderInsideEclipseProject\\file.txt";//You know this
System.out.println(absolutePath + filePath);//Get the full path.