Search code examples
javajava-iojava.nio.file

How do I read a file in a directory other than src?


I have myFile.txt located in myJavaProject\webResources\sampleTransmissions. I am trying to read the file in myJavaProject\src\package1\notMyMainClass.java and I am having trouble building the path properly to access the webResources directory. Also, I would like to read the file using Files.readAllBytes(Path path) because I need to get non-printable characters to work with

edit: this would be my project structure

+myJavaProject

++src

+++notMyMainClass.java

++webResources

+++sampleTransmissions

++++myFile.txt


Solution

  • Are you looking for something like this:

    Scanner scanner = new Scanner(new File("webResources/sampleTransmissions/myFile.txt"));
    

    This assumes that "myJavaProject" is your working directory. If you want it to work indepenently from the working directory, use an absolute path.

    The forward slashes should work on Windows as well. If you prefer backslashes, you need to write "webResources\\sampleTransmissions\\myFile.txt"

    Note: The working directory has nothing to do with the location of your .java or .class file.