1

I've been trying to read and write to a file under my resources directory in my project. However, regardless of what I seem to do it doesn't allow me to do so.

This is my project hierarchy for reference:

enter image description here

Out of all these:

Paths.get("memes.txt")
Paths.get("resources/memes.txt")
Paths.get("/resources/memes.txt")
...

None have worked. What am I doing wrong?

Orange Receptacle
  • 1,173
  • 3
  • 19
  • 40
  • 3
    Possible duplicate of [How to really read text file from classpath in Java](http://stackoverflow.com/questions/1464291/how-to-really-read-text-file-from-classpath-in-java) – Jan B. Aug 16 '16 at 08:30

3 Answers3

1

Is it a Maven project ? Try this :

//Get file from resources folder
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource(fileName).getFile());

Ref : https://www.mkyong.com/java/java-read-a-file-from-resources-folder/

Numerinico
  • 55
  • 5
1

Your application can be packed as .jar file - a zip format. There, or in the built classes directory should be memes.txt. A so-called resource, and in case of a jar not really a file system file. But is located on the class path.

URL url = getClass().getResource("/memes.txt");
InputStream in = getClass().getResourceAsStream("/memes.txt");

The path is relative to the package directory of the class, or absolute as above.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
0

Try it using "../resources/memes.txt" with ".." you go up one directory from your current file (i assume that you are using the code in SwearTest.java)

DJ MERKEL
  • 87
  • 8
  • It still throws me `Exception in thread "main" java.nio.file.NoSuchFileException: ..\resources\memes.txt`, though. And yes, I am using the code in SwearTest.java – Orange Receptacle Aug 16 '16 at 08:49