How do I load a file from resource folder?

匿名 (未验证) 提交于 2019-12-03 02:10:02

问题:

My project has the following structure:

/src/main/java/ /src/main/resources/ /src/test/java/ /src/test/resources/ 

I have a file in /src/test/resources/test.csv and I want to load the file from a unit test in /src/test/java/MyTest.java

I have this code which didn't work. It complains "No such file or directory".

BufferedReader br = new BufferedReader (new FileReader(test.csv)) 

I also tried this

InputStream is = (InputStream) MyTest.class.getResourcesAsStream(test.csv)) 

This also doesn't work. It returns null. I am using Maven to build my project.

回答1:

Try the next:

ClassLoader classloader = Thread.currentThread().getContextClassLoader(); InputStream is = classloader.getResourceAsStream("test.csv"); 

If the above doesn't work, various projects have been added the following class: ClassLoaderUtil (code here).

Here are some examples of how that class is used:

src\main\java\com\company\test\YourCallingClass.java src\main\java\com\opensymphony\xwork2\util\ClassLoaderUtil.java src\main\resources\test.csv
// java.net.URL URL url = ClassLoaderUtil.getResource("test.csv", YourCallingClass.class); Path path = Paths.get(url.toURI()); List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8); 
// java.io.InputStream InputStream inputStream = ClassLoaderUtil.getResourceAsStream("test.csv", YourCallingClass.class); InputStreamReader streamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8); BufferedReader reader = new BufferedReader(streamReader); for (String line; (line = reader.readLine()) != null;) {     // Process line } 


回答2:

Try:

InputStream is = MyTest.class.getResourceAsStream("/test.csv"); 

IIRC getResourceAsStream() by default is relative to the class's package.



回答3:

Here is one quick solution with the use of Guava:

import com.google.common.base.Charsets; import com.google.common.io.Resources;  public String readResource(final String fileName, Charset charset) throws IOException {         return Resources.toString(Resources.getResource(fileName), charset); } 

Usage:

String fixture = this.readResource("filename.txt", Charsets.UTF_8) 


回答4:

Try Flowing codes on Spring project

ClassPathResource resource = new ClassPathResource("fileName"); InputStream inputStream = resource.getInputStream(); 

Or on non spring project

 ClassLoader classLoader = getClass().getClassLoader();  File file = new File(classLoader.getResource("fileName").getFile());  InputStream inputStream = new FileInputStream(file); 


回答5:

Now I am illustrating the source code for reading a font from maven created resources directory,

scr/main/resources/calibril.ttf

Font getCalibriLightFont(int fontSize){     Font font = null;     try{         URL fontURL = OneMethod.class.getResource("/calibril.ttf");         InputStream fontStream = fontURL.openStream();         font = new Font(Font.createFont(Font.TRUETYPE_FONT, fontStream).getFamily(), Font.PLAIN, fontSize);         fontStream.close();     }catch(IOException | FontFormatException ief){         font = new Font("Arial", Font.PLAIN, fontSize);         ief.printStackTrace();     }        return font; } 

It worked for me and hope that the entire source code will also help you, Enjoy!



回答6:

ClassLoader loader = Thread.currentThread().getContextClassLoader(); InputStream is = loader.getResourceAsStream("test.csv"); 

If you use context ClassLoader to find a resource then definitely it will cost application performance.



回答7:

Does the code work when not running the Maven-build jar, for example when running from your IDE? If so, make sure the file is actually included in the jar. The resources folder should be included in the pom file, in <build><resources>.



回答8:

The following class can be used to load a resource from the classpath and also receive a fitting error message in case there's a problem with the given filePath.

import java.io.InputStream; import java.nio.file.NoSuchFileException;  public class ResourceLoader {     private String filePath;      public ResourceLoader(String filePath)     {         this.filePath = filePath;          if(filePath.startsWith("/"))         {             throw new IllegalArgumentException("Relative paths may not have a leading slash!");         }     }      public InputStream getResource() throws NoSuchFileException     {         ClassLoader classLoader = this.getClass().getClassLoader();          InputStream inputStream = classLoader.getResourceAsStream(filePath);          if(inputStream == null)         {             throw new NoSuchFileException("Resource file not found. Note that the current directory is the source folder!");         }          return inputStream;     } } 


回答9:

getResource() was working fine with the resources files placed in src/main/resources only. To get a file which is at the path other than src/main/resources say src/test/java you need to create it exlicitly.

the following example may help you

import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL;  public class Main {     public static void main(String[] args) throws URISyntaxException, IOException {         URL location = Main.class.getProtectionDomain().getCodeSource().getLocation();         BufferedReader br = new BufferedReader(new FileReader(location.getPath().toString().replace("/target/classes/", "/src/test/java/youfilename.txt")));     } } 


回答10:

Just use InputStream inputStream = ClassLoader.getSystemResourceAsStream("xmls/employee.xml")

Here there's a xmls folder having a files employee.xml.



回答11:

I get it to work without any reference to "class" or "ClassLoader".

Let's say we have three scenarios with the location of the file 'example.file' and your working directory (where your app executes) is home/mydocuments/program/projects/myapp:

a)A sub folder descendant to the working directory: myapp/res/files/example.file

b)A sub folder not descendant to the working directory: projects/files/example.file

b2)Another sub folder not descendant to the working directory: program/files/example.file

c)A root folder: home/mydocuments/files/example.file (Linux; in Windows replace home/ with C:)

1) Get the right path: a)String path = "res/files/example.file"; b)String path = "../projects/files/example.file" b2)String path = "../../program/files/example.file" c)String path = "/home/mydocuments/files/example.file"

Basically, if it is a root folder, start the path name with a leading slash. If it is a sub folder, no slash must be before the path name. If the sub folder is not descendant to the working directory you have to cd to it using "../". This tells the system to go up one folder.

2) Create a File object by passing the right path:

File file = new File(path); 

3) You are now good to go:

BufferedReader br = new BufferedReader(new FileReader(file)); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!