unable to get file using classLoader.getResource(fileName).getFile() - java

I made a maven web-app project in eclipse it was working fine on the machine on which I made this. but when importing this project to other machine in eclipse it gives me this exception while getting the file:
exception:D:\Eclipse%20Workspace.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\example\WEB-INF\classes\file.txt
(The system cannot find the path specified)
I am using this code to get a file:
public File getFile (String fileName) {
//Get file from resources folder
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource(fileName).getFile());
return file;
}
the file is in the resources folder of the project:
D:\Eclipse Workspace\Sentiment Analysis\example\src\main\resources
I go the path the exception message showing and found that the file is already been there.

The getFile method of URL does not convert a URL to a file. It just returns the portion of the URL after the host and port. URLs need to percent-escape a lot of characters, including spaces, so you cannot reliably use the URL's path portion as a file name. In fact, the exception is telling you exactly that: There is no directory named D:\Eclipse%20Workspace.metadata.plugins on your computer. (Go ahead and check.)
When you have a URL, you should not be trying to convert it to a File at all. You don't need to. You can read from a URL just as easily as from a file using the openStream method of URL.
But even that is not necessary, because you can also use the getResourceAsStream method to skip the URL entirely and get a readable InputStream:
InputStream stream = getClass().getResourceAsStream("/file.txt");

The code is looking for the file in the same directory as this code class resident. What is the package structure of this code?
Also, only Maven copy the resources into the class path. So if you compile and run using Eclipse then the resources folder won't be copied automatically.

Related

Eclipse can't read text file in src folder

I am implementing a Branch Predictor for one of my classes and I am trying to read files from my src folder in Eclipse but for some reason it is not able to open the files. I have done this before with the exact same process so I'm not sure what is different.
traceFile is set from the command line and if I print "input", it will print out the correct file path and I have confirmed it is there manually.
ClassLoader loader = BiModalPredictor.class.getClassLoader();
File input = new File(loader.getResource(traceFile).getFile());
Scanner fin = new Scanner(input);
Is there any insight as to why this might be happening? I've tried restarting Eclipse, refreshing the files, and I've also tested it on another program which worked. No idea why it can't find this file.
Resources on the classpath, i.e. available through the classloaders getResource method, will not be files on the file system when your application is deployed as a jar file, or deployed in general. Do not use File with such resources, instead use getResourceAsStream to access the resource content.
Besides, your code is wrong. getResource() returns a URL. If you want a File object from a URL, you should use new File(uri), where the URI is obtained by calling url.toURI().
File input = new File(loader.getResource(traceFile).toURI());

Spring does not find file in resources

i have following line
File file = ResourceUtils.getFile("classpath:calculation.csv");
and i also tried
File file = ResourceUtils.getFile("classpath:/calculation.csv");
but both will throw an error
java.io.FileNotFoundException: class path resource [calculation.csv] cannot be resolved to absolute file path because it does not exist
but i do have calculation.csv in by resources folder..
why is this?
I need to read file from resources folder, and it should also work in server enviroment
EDIT:
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("calculation.csv").getFile());
works just as fine, so not at all..
EDIT2:
tried with folder.. i have both calculation.csv and csv/calculation.csv in my resources folder now..
none of the above work, with /csv/ added.
what kind of path does this thing want?!
EDIT3:
aaand
File file = new ClassPathResource("calculation.csv").getFile();
is also no go, what even is this..
Loading file (as FILE) wont work. You must use it as resource. Files inside JAR will not work as file anyway. This is also what your "check" code shows.
classLoader.getResource("calculation.csv") works, because you are using classloader to get resource, not filesystem to get file (which is what File api does). It could work, if you would deal with non packed application. Once you pack your app into JAR, file path will be like your/path/to/jar.jar!someResource - note ! mark (and that is what you would see as well). So basicly it will return File instance, you that you wont be able to use anyway, as file system has no access to it.
You could alternatively try to extract it first with ResourceUtiuls#extractJarFileURL(URL jarUrl) and then use extracted file.
I think, that in most cases Class#getResourceAsStream is the way to go and I think that it should fit your needs as well to read content of resource.

getClassLoader().getResource("Configuration.xml").getPath() does not work inside a jar

I've created a maven based java project which has resources directory (src/java/resources) and in it some xml files and maven copies them into target/classes/resources (target/classes is my classpath).
To know the content of an xml file, I use:
new FileInputStream(Main.class.getClassLoader().getResource("Configuration.xml").getPath());
Main.class.getClassLoader().getResource("Configuration.xml").getPath() gives me the full path of the xml: "c:\project...\Configuration.xml".
This works well on intellij.
but when I compile and package the project into a jar file I get:
Exception in thread "main" java.io.FileNotFoundException:
file:\C:\project\target\project-12.50.14-SNAPSHOT-jar-with-dependencies
.jar!\Configuration.xml
(The filename, directory name, or volume label syntax is incorrect)
That because the path: \C:\project\target\project-12.50.14-SNAPSHOT-jar-with-dependencies
.jar!\Configuration.xml cannot be a parameter into FileInputStream().
I cannot replace the getResource() to getResourceAsStream().
I need a way to adjust my jar and resources to work like it work on intellij.
I also change the xml resources files content during run-time so that is another problem with keeping them inside a jar.
Can anyone offer me a solution in which I don't have to change me code, and instead change my resources directory structure, or change the classpath, or something else that will keep my code working?
Thanks.
Update: Changed to use File, not Path.
That is because getResource returns a URL, and not all urls are files on disk, i.e. can be converted to a Path. As javadoc says "Returns [...] an empty string if [path part] does not exist".
If it absolutely must be a File or FileInputStream, because some other code you cannot change requires it, then copy the content to a temporary file:
File file = File.createTempFile("Configuration", ".xml");
try {
try {InputStream in = Main.class.getClassLoader().getResourceAsStream("Configuration.xml")) {
Files.copy(in, file.toPath()); // requires Java 7
}
// use file here, or:
try {FileInputStream in = new FileInputStream(file)) {
// use file stream here
}
} finally {
file.delete();
}
The above code could be optimized to not copy if resource is a file, but since that's only for development mode, and production mode is always a Jar and will always need the copy, using copy in development mode helps test the code.

Java code cannot find resource file after build and clean in Netbeans IDE?

I really need your help to solve my own problem. Now, I'm dealing with small code app. In that project folder contain some resource files (*.xlsx, *.png,...). I placed them in current folder with code file. I just wonder that when I run my code in netbean ide, it just worked find.
After I build code project, I get a jar file in "dist" directory. I run it. It open normally since app used JFrame as user interface. However, when I execute some function of that app, it showed me the error log. Here is the error message:
java.io.FileNotFoundException:
src\sample.xlsx (The system cannot find the path specified)
What's the matter out there?
Here is some pieces of my code:
copyFile(new File("src\\sample.xlsx"),
new File(txtout.getText()+"\\sample.xlsx"));
Node: copyFile function is used for copy file from source to dest.
Here is my project folder structure in Netbean IDE:
Project Name
Source Pakage(src)
myClass.java, sample.xlsx, etc
First, never reference src directly, the directory will not exist once the program is built. Second, you can not access resources which have been embedded within in the application context via a File reference, they simply no longer exist on the file system.
Instead, you need to use Class#getResource or Class#getResourceAsStream
URL url = getClass().getResource("/sample.xlsx");
InputStream is = getClass().getResourceAsStream("/sample.xlsx");
// Don't forget to manage your streams appropriately...
Well you can create a folder named resources under the src folder put your resources in it and use them in your code by using getResourceAsStream() and getResource() methods that can access the embedded resources.Clean and Build will compile the code and embed the contents of the resources folder into the application’s .jar file.
Ways of Accessing resources :
String pathToImage = "resources/images/filling.png";
InputStream stream= ClassName.class.getResourceAsStream(pathToImage );
String pathToImage = "resources/images/filling.png";
InputStream stream= ClassName.class.getResource(pathToImage );
please refer the link information

What is the path to resource files in a Maven project?

In my Maven project, I have the following code in the main method:
FileInputStream in = new FileInputStream("database.properties");
but always get a file not found error.
I have put the file in src/main/resources and it is properly copied to the target/classes directory (I believe that is the expected behavior for Maven resources) but when actually running the program it seems it can never find the file. I've tried various other paths:
FileInputStream in = new FileInputStream("./database.properties");
FileInputStream in = new FileInputStream("resources/database.properties");
etc. but nothing seems to work.
So what is the proper path to use?
Based on "disown's" answer below, here was what I needed:
InputStream in = TestDB.class.getResourceAsStream("/database.properties")
where TestDB is the name of the class.
Thanks for your help, disown!
You cannot load the file directly like that, you need to use the resource abstraction (a resource could not only be in the file system, but on any place on the classpath - in a jar file or otherwise). This abstraction is what you need to use when loading resources. Resource paths are relative to the location of your class file, so you need to prepend a slash to get to the 'root':
InputStream in = getClass().getResourceAsStream("/database.properties");

Categories

Resources