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.
Related
I am trying to use file, when running application as JAR.
When I run application through Intelij, everything is fine. However when I try to run it via jar, I cannot access the file.
I tried to read few topics containing similar matter, but non of them help
(like Reading a resource file from within jar or How do I read a resource file from a Java jar file?
)
Here is my target tree, and resources:
When I use
String path = String
.join("", "classpath:static\assets\config\", fileName);
File file = ResourceUtils.getFile(path);
InputStream targetStream = new FileInputStream(file)
During intelij run, everything works.
In the case of jar, I tried:
String path = String
.join("", "static\assets\config\", fileName).replace("\\","/")).toExternalForm();
String path2 = String
.join("", "static\assets\config\", fileName).replace("\\","/")).getFile();
String path3 = String
.join("", "static\assets\config\", fileName).replace("\\","/")).getPath();
and many other. They result in correct path, for example:
file:/D:/Projects/myProject/target/classes/static/assets/config/fileName (in case of toExternalForm)
/D:/Projects/myProject/target/classes/static/assets/config/fileName (in case of getFile)
However all of them results in null InputStream, when I try:
InputStream in = getClass().getResourceAsStream(everyPath);
I get an error:
java.io.FileNotFoundException: D:\Projects\myProject\target\project-app-1.0.jar\BOOT-INF\classes\static\assets\config\fileName (The system cannot find the path specified)
When the path in the project-app-1.0.jar when I open it by 7zip is exactly:
D:\Projects\myProject\target\project-app-1.0.jar\BOOT-INF\classes\static\assets\config\fileName
This is how my resource handler looks like:
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
"classpath:/resources/", "classpath:/static/"};
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations(
CLASSPATH_RESOURCE_LOCATIONS);
}
forget about "files" when you want to use something inside your jar, its just a simple "Resource" that your have to use with getResource.
If you use a standard packaging system, everything inside "resources" folder are put at the root of your JAR, so if you want to read your "foo.txt" file inside "static\assets\config\" folder you have to do use method:
InputStream in = ClassLoader.getSystemResourceAsStream("static/assets/config/foo.txt");
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'm a beginner in programming and I have a class that requires a path to some folder in its constructor. For example:
SomeClass class = new SomeClass(c:/folder);
I need to get a String value of resources folder (only path to folder without specific file names). A method in that class will add a filename to path from constructor and do some operations with a specific file.
I'm trying to do this (bad code!), but just have npe:
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("src/main/resources").getFile());
String path = file.getAbsolutePath();
So, the question is: how to get String value of resources folder?
What solved my problem:
File file = new File("src/main/resources");
String path = file.getAbsolutePath();
So, I got String path to resources folder.
I have a project with 2 packages:
tkorg.idrs.core.searchengines
tkorg.idrs.core.searchengines
In package (2) I have a text file ListStopWords.txt, in package (1) I have a class FileLoadder. Here is code in FileLoader:
File file = new File("properties\\files\\ListStopWords.txt");
But I have this error:
The system cannot find the path specified
Can you give a solution to fix it?
If it's already in the classpath, then just obtain it from the classpath instead of from the disk file system. Don't fiddle with relative paths in java.io.File. They are dependent on the current working directory over which you have totally no control from inside the Java code.
Assuming that ListStopWords.txt is in the same package as your FileLoader class, then do:
URL url = getClass().getResource("ListStopWords.txt");
File file = new File(url.getPath());
Or if all you're ultimately after is actually an InputStream of it:
InputStream input = getClass().getResourceAsStream("ListStopWords.txt");
This is certainly preferred over creating a new File() because the url may not necessarily represent a disk file system path, but it could also represent virtual file system path (which may happen when the JAR is expanded into memory instead of into a temp folder on disk file system) or even a network path which are both not per definition digestable by File constructor.
If the file is -as the package name hints- is actually a fullworthy properties file (containing key=value lines) with just the "wrong" extension, then you could feed the InputStream immediately to the load() method.
Properties properties = new Properties();
properties.load(getClass().getResourceAsStream("ListStopWords.txt"));
Note: when you're trying to access it from inside static context, then use FileLoader.class (or whatever YourClass.class) instead of getClass() in above examples.
The relative path works in Java using the . specifier.
. means same folder as the currently running context.
.. means the parent folder of the currently running context.
So the question is how do you know the path where the Java is currently looking?
Do a small experiment
File directory = new File("./");
System.out.println(directory.getAbsolutePath());
Observe the output, you will come to know the current directory where Java is looking. From there, simply use the ./ specifier to locate your file.
For example if the output is
G:\JAVA8Ws\MyProject\content.
and your file is present in the folder "MyProject" simply use
File resourceFile = new File("../myFile.txt");
Hope this helps.
The following line can be used if we want to specify the relative path of the file.
File file = new File("./properties/files/ListStopWords.txt");
InputStream in = FileLoader.class.getResourceAsStream("<relative path from this class to the file to be read>");
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
try .\properties\files\ListStopWords.txt
I could have commented but I have less rep for that.
Samrat's answer did the job for me. It's better to see the current directory path through the following code.
File directory = new File("./");
System.out.println(directory.getAbsolutePath());
I simply used it to rectify an issue I was facing in my project. Be sure to use ./ to back to the parent directory of the current directory.
./test/conf/appProperties/keystore
While the answer provided by BalusC works for this case, it will break when the file path contains spaces because in a URL, these are being converted to %20 which is not a valid file name. If you construct the File object using a URI rather than a String, whitespaces will be handled correctly:
URL url = getClass().getResource("ListStopWords.txt");
File file = new File(url.toURI());
Assuming you want to read from resources directory in FileSystem class.
String file = "dummy.txt";
var path = Paths.get("src/com/company/fs/resources/", file);
System.out.println(path);
System.out.println(Files.readString(path));
Note: Leading . is not needed.
I wanted to parse 'command.json' inside src/main//js/Simulator.java. For that I copied json file in src folder and gave the absolute path like this :
Object obj = parser.parse(new FileReader("./src/command.json"));
For me actually the problem is the File object's class path is from <project folder path> or ./src, so use File file = new File("./src/xxx.txt"); solved my problem
For me it worked with -
String token = "";
File fileName = new File("filename.txt").getAbsoluteFile();
Scanner inFile = null;
try {
inFile = new Scanner(fileName);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while( inFile.hasNext() )
{
String temp = inFile.next( );
token = token + temp;
}
inFile.close();
System.out.println("file contents" +token);
If text file is not being read, try using a more closer absolute path (if you wish
you could use complete absolute path,) like this:
FileInputStream fin=new FileInputStream("\\Dash\\src\\RS\\Test.txt");
assume that the absolute path is:
C:\\Folder1\\Folder2\\Dash\\src\\RS\\Test.txt
String basePath = new File("myFile.txt").getAbsolutePath();
this basepath you can use as the correct path of your file
if you want to load property file from resources folder which is available inside src folder, use this
String resourceFile = "resources/db.properties";
InputStream resourceStream = ClassLoader.getSystemClassLoader().getResourceAsStream(resourceFile);
Properties p=new Properties();
p.load(resourceStream);
System.out.println(p.getProperty("db"));
db.properties files contains key and value db=sybase
If you are trying to call getClass() from Static method or static block, the you can do the following way.
You can call getClass() on the Properties object you are loading into.
public static Properties pathProperties = null;
static {
pathProperties = new Properties();
String pathPropertiesFile = "/file.xml";
// Now go for getClass() method
InputStream paths = pathProperties.getClass().getResourceAsStream(pathPropertiesFile);
}
How do I get the directory name for a particular java.io.File on the drive in Java?
For example I have a file called test.java under a directory on my D drive.
I want to return the directory name for this file.
File file = new File("d:/test/test.java");
File parentDir = file.getParentFile(); // to get the parent dir
String parentDirName = file.getParent(); // to get the parent dir name
Remember, java.io.File represents directories as well as files.
With Java 7 there is yet another way of doing this:
Path path = Paths.get("d:/test/test.java");
Path parent = path.getParent();
//getFileName() returns file name for
//files and dir name for directories
String parentDirName = path.getFileName().toString();
I (slightly) prefer this way, because one is manipulating path rather than files, which imho better shows the intentions. You can read about the differences between File and Path in the Legacy File I/O Code tutorial
Note also that if you create a file this way (supposing "d:/test/" is current working directory):
File file = new File("test.java");
You might be surprised, that both getParentFile() and getParent() return null. Use these to get parent directory no matter how the File was created:
File parentDir = file.getAbsoluteFile().getParentFile();
String parentDirName = file.getAbsoluteFile().getParent();
File file = new File("d:/test/test.java");
String dirName = file.getParentFile().getName();
Say that you have a file called test.java in C:\\myfolder directory. Using the below code, you can find the directory where that file sits.
String fileDirectory = new File("C:\\myfolder\\test.java").getAbsolutePath();
fileDirectory = fileDirectory.substring(0,fileDirectory.lastIndexOf("\\"));
This code will give the output as C:\\myfolder