Fahad
Fahad

Reputation: 378

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

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.

Upvotes: 0

Views: 2470

Answers (2)

VGR
VGR

Reputation: 44338

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

Upvotes: 1

Minh Kieu
Minh Kieu

Reputation: 475

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.

Upvotes: 0

Related Questions