How do I load a file from resource folder?

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. 122k 47 47 gold badges 242 242 silver badges 302 302 bronze badges asked Apr 1, 2013 at 18:23 codereviewanskquestions codereviewanskquestions 13.9k 31 31 gold badges 101 101 silver badges 168 168 bronze badges Doesn't work how? What is your error? Commented Apr 1, 2013 at 18:24 try this this.getClass().getResource("/test.csv") Commented Apr 1, 2013 at 18:28 Commented Apr 1, 2013 at 18:28

@SRy it worked (cause this will give absolute path url in return ) however the moment i make jar file it's not working as its inside a jar and absolute path becomes invalid, is there a way to play with relative path itself

Commented May 12, 2020 at 10:33

@SRy, somewhere between now and 2013, this seems to have been fixed. I am today able to load root resources without the initial / . However, I do getClass().getClassLoader().getResourceAsStream(filename) . maybe that's the difference?

Commented Dec 28, 2020 at 21:37

25 Answers 25

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 1 (code here). 2

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 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 >
  1. See it in The Wayback Machine.
  2. Also in GitHub.
107k 218 218 gold badges 149 149 silver badges 207 207 bronze badges answered Apr 1, 2013 at 18:29 Paul Vargas Paul Vargas 41.9k 16 16 gold badges 107 107 silver badges 148 148 bronze badges

thx for the answer, could you please explain why we should use this very specific loader but not that of the class ?

Commented Oct 29, 2015 at 9:05

great, I'm so stupid that I was using Object.class.getClassLoader(); , from a static context which didn't work - this suggestion does - well almost, it injects %20 for spaces which gives me a FileNotFoundException

Commented Mar 7, 2016 at 20:03

@ycomp Because getResource returns a URL, not a file. The getFile method of java.net.URL does not convert a URL to a file; it just returns the path and query portions of the URL. You shouldn't even try to convert it to a File; just call openStream and read from that.

Commented Apr 7, 2016 at 13:15 Check this project, solves resources folder scanning: github.com/fraballi/resources-folder-scanner Commented Mar 13, 2020 at 18:36

The one liner suggested by @prayagupa only works in Java 9 or higher, see stackoverflow.com/questions/54269211/…

Commented Feb 1, 2022 at 20:33
InputStream is = MyTest.class.getResourceAsStream("/test.csv"); 

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

As @Terran noted, don't forget to add the / at the starting of the filename

11.6k 10 10 gold badges 69 69 silver badges 120 120 bronze badges answered Apr 1, 2013 at 18:27 9,883 2 2 gold badges 32 32 silver badges 34 34 bronze badges

For those seeking sanity, this post brings you all the way to getting the resource as a String stackoverflow.com/a/35446009/544045

Commented May 17, 2018 at 18:14 The "/" is the key. Commented Feb 7, 2019 at 16:06

Try following 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); 
189k 20 20 gold badges 140 140 silver badges 260 260 bronze badges answered Apr 14, 2017 at 16:35 1,767 15 15 silver badges 12 12 bronze badges Should the InputStream not be closed? Commented Feb 18, 2018 at 14:36 This answer works on a war file not for a jar file. Commented Feb 12, 2022 at 0:03

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
String fixture = this.readResource("filename.txt", Charsets.UTF_8) 
answered Mar 4, 2016 at 19:53 26.5k 6 6 gold badges 68 68 silver badges 72 72 bronze badges

The docs say that this about the getResource method: 'getResource(java.lang.String)' is declared in unstable class 'com.google.common.io.Resources' marked with @Beta . Should people really be using methods from an unstable class?

Commented Dec 14, 2021 at 21:32 what is this in your usage example? why people cannot attach the whole code needed? Commented Dec 7, 2023 at 8:23

Non spring project:

String filePath = Objects.requireNonNull(getClass().getClassLoader().getResource("any.json")).getPath(); Stream lines = Files.lines(Paths.get(filePath)); 
String filePath = Objects.requireNonNull(getClass().getClassLoader().getResource("any.json")).getPath(); InputStream in = new FileInputStream(filePath); 

For spring projects, you can also use one line code to get any file under resources folder:

File file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "any.json"); String content = new String(Files.readAllBytes(file.toPath())); 
answered Dec 9, 2019 at 21:13 1,742 2 2 gold badges 21 21 silver badges 26 26 bronze badges

For java after 1.7

 List lines = Files.readAllLines(Paths.get(getClass().getResource("test.csv").toURI())); 

Alternatively you can use Spring utils if you are in Spring echosystem

final val file = ResourceUtils.getFile("classpath:json/abcd.json"); 

To get to more behind the scene, check out following blog

answered Oct 4, 2019 at 5:36 453 4 4 silver badges 9 9 bronze badges I must use "/test.csv" (note the slash). Commented Dec 20, 2019 at 4:31

The file was not found by a class loader, which means it was not packed into the artifact (jar). You need to build the project. For example, with maven:

mvn clean package 

So the files you added to resources folder will get into maven build and become available to the application.

I would like to keep my answer: it does not explain how to read a file (other answers do explain that), it answers why InputStream or resource was null. Similar answer is here.

answered Mar 29, 2019 at 2:16 Yan Khonski Yan Khonski 12.9k 16 16 gold badges 82 82 silver badges 117 117 bronze badges Thanks, saved me from thinking I was losing my mind! Commented Jun 2, 2020 at 16:22
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.

131 8 8 bronze badges answered Nov 30, 2014 at 1:18 Bimales Mandal Bimales Mandal 331 3 3 silver badges 4 4 bronze badges

Programmers should always be concerned about performance. While premature optimization is certainly to be avoided, knowing the more efficient approach to take is always good. It's like knowing the difference between LinkedList and ArrayList and when to use one or the other.

Commented Jun 18, 2015 at 18:52

@Marvo: Programmers must always be concerned about quality, capabilities and ease of maintenance, performance is at the queue.

Commented Aug 26, 2015 at 8:09

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

<a href=enter image description here" />

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!

answered Sep 27, 2017 at 15:45 ArifMustafa ArifMustafa 4,885 5 5 gold badges 43 43 silver badges 49 49 bronze badges Can you tell us the full name of Font class? Commented Feb 1, 2021 at 19:56

Import the following:

import java.io.IOException; import java.io.FileNotFoundException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; import java.util.ArrayList; 

The following method returns a file in an ArrayList of Strings:

public ArrayList loadFile(String filename) < ArrayListlines = new ArrayList(); try < ClassLoader classloader = Thread.currentThread().getContextClassLoader(); InputStream inputStream = classloader.getResourceAsStream(filename); InputStreamReader streamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8); BufferedReader reader = new BufferedReader(streamReader); for (String line; (line = reader.readLine()) != null;) < lines.add(line); >>catch(FileNotFoundException fnfe)< // process errors >catch(IOException ioe) < // process errors >return lines; > 
answered Nov 2, 2018 at 19:26 2,352 1 1 gold badge 13 13 silver badges 8 8 bronze badges

You can use the com.google.common.io.Resources.getResource to read the url of file and then get the file content using java.nio.file.Files to read the content of file.

URL urlPath = Resources.getResource("src/main/resource"); List multilineContent= Files.readAllLines(Paths.get(urlPath.toURI())); 
answered Apr 5, 2020 at 18:04 Bhawna Joshi Bhawna Joshi 330 4 4 silver badges 13 13 bronze badges

if you are loading file in static method then ClassLoader classLoader = getClass().getClassLoader(); this might give you an error.

You can try this e.g. file you want to load from resources is resources >> Images >> Test.gif

import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; Resource resource = new ClassPathResource("Images/Test.gif"); File file = resource.getFile(); 
4,570 21 21 gold badges 94 94 silver badges 218 218 bronze badges answered Sep 23, 2020 at 5:43 sagar vyas sagar vyas 131 1 1 silver badge 5 5 bronze badges

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"))); >> 
answered Feb 20, 2017 at 8:35 Piyush Mittal Piyush Mittal 1,880 1 1 gold badge 23 23 silver badges 40 40 bronze badges
this.getClass().getClassLoader().getResource("filename").getPath() 
22.3k 30 30 gold badges 96 96 silver badges 142 142 bronze badges answered Oct 23, 2019 at 7:05 shiva kumar shiva kumar 11.4k 4 4 gold badges 25 25 silver badges 28 28 bronze badges

To read the files from src/resources folder then try this :

DataSource fds = new FileDataSource(getFileHandle("images/sample.jpeg")); public static File getFileHandle(String fileName)

in case of non static reference:

return new File(getClass().getClassLoader().getResource(fileName).getFile()); 
answered Feb 3, 2021 at 7:09 Alferd Nobel Alferd Nobel 3,779 2 2 gold badges 36 36 silver badges 36 36 bronze badges

For Kotlin I am doing the following:

  1. I created an assets folder in my project (for Android studio go to File -> New-> Folder -> Assets Folder)
  2. Copied my assets (.txt files) to this folder
  3. Then I used the code below

Import these items:

 import android.content.Context import android.util.Log import java.io.FileNotFoundException 

I created a function like this:

 fun loadBook(context: Context) < val assetManager = context.assets try < val inputStream = assetManager?.open("19-Psalms.usfm") val lineList = mutableListOf() inputStream?.bufferedReader()?.forEachLine < lineList.add(it) >lineList.forEach $it")> > catch (e:FileNotFoundException) < Log.e("FileNotFoundException","File not found") >> 
answered Dec 5, 2023 at 5:36 136 1 1 silver badge 8 8 bronze badges

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 .

answered Apr 1, 2013 at 18:35 user8681 user8681

When using eclipse and running code from IDE itself. How can we load resources located at "/src/test/resources" in Java code specifically in unit tests. Consider a standard maven project structure.

Commented Jul 2, 2014 at 9:00

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; > > 
answered Feb 2, 2015 at 18:08 BullyWiiPlaza BullyWiiPlaza 18.8k 14 14 gold badges 126 126 silver badges 205 205 bronze badges

My file in the test folder could not be found even though I followed the answers. It got resolved by rebuilding the project. It seems IntelliJ did not recognize the new file automatically. Pretty nasty to find out.

answered Oct 15, 2020 at 9:57 11.8k 8 8 gold badges 59 59 silver badges 67 67 bronze badges

I got it work on both running jar and in IDE by writing as

InputStream schemaStream = ProductUtil.class.getClassLoader().getResourceAsStream(jsonSchemaPath); byte[] buffer = new byte[schemaStream.available()]; schemaStream.read(buffer); File tempFile = File.createTempFile("com/package/schema/testSchema", "json"); tempFile.deleteOnExit(); FileOutputStream out = new FileOutputStream(tempFile); out.write(buffer); 
43 3 3 bronze badges answered Jan 22, 2019 at 13:40 1,073 5 5 gold badges 20 20 silver badges 46 46 bronze badges How does your file structure look like? Commented Sep 16, 2019 at 18:55

I am currently doing it this way.

<a href=enter image description here" />

This is my structure.

final String path = "src/test/resources/archivos/B-163.txt"; final Path filePath = Path.of( path ); final String documento = Files.readString( filePath ); log.debug("DOCUMENTO: <>" , document); 

I am working with Java 11.

answered Aug 17, 2023 at 18:21 1,473 1 1 gold badge 26 26 silver badges 39 39 bronze badges
import java.nio.charset.StandardCharsets import java.nio.file.Files import java.nio.file.Paths val lines = Files.readAllLines( Paths.get((object <>).javaClass.getResource("videos.txt").toURI()), StandardCharsets.UTF_8 ) lines // will contain list of lines in a file 
answered Oct 12, 2023 at 19:55 George Shalvashvili George Shalvashvili 1,506 14 14 silver badges 24 24 bronze badges

If you want to get a File object:

File file = new File(this.getClass().getClassLoader().getResource("test.csv").toURI()) 
answered Jul 31 at 7:53 Dennis Löhmann Dennis Löhmann 49 4 4 bronze badges

This worked pretty fine for me :

InputStream in = getClass().getResourceAsStream("/main/resources/xxx.xxx"); InputStreamReader streamReader = new InputStreamReader(in, StandardCharsets.UTF_8); BufferedReader reader = new BufferedReader(streamReader); String content = ""; for (String line; (line = reader.readLine()) != null;)
answered Jul 28, 2022 at 12:33 270 4 4 silver badges 6 6 bronze badges

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