0

I have a file named InputFile.txt in a resources folder. My project structure is like this:

  • VirtualMemory
    • src
      • resources
        • InputFile.txt
      • VirtualMemory
        • VirtualMemory.java

And I am trying to access the InputFile.txt in VirtualMemory.java class by like this:

String filename = ("./src/resources/InputFile.txt");
File file = new File(filename); 

But the file is not being found. How to resolve this problem?

xxxvodnikxxx
  • 1,270
  • 2
  • 18
  • 37
  • Since the file resides within the program context, you need to use `Class#getResource` or `Class#getResourceAsStream` to get a reference to it, for example `getClass().getResourceAsStream("/resources/InputFile.txt")` will return an `InputStream` to the contents of the file – MadProgrammer Dec 02 '15 at 01:23
  • Can you please provide code for this? –  Dec 02 '15 at 01:24
  • I did, look at the comments – MadProgrammer Dec 02 '15 at 01:35
  • I need to locate file, but the code will return InputStream. –  Dec 02 '15 at 02:09
  • You can't, essentially, it's not `File` in sense of a file on the file system, it's a named resource, which is stored as series of bytes inside the jar file – MadProgrammer Dec 02 '15 at 02:10
  • When I used InputStream filename = getClass().getResourceAsStream("/resources/InputFile.txt"); File file = new File(filename.toString()); FileReader fr = new FileReader(file); br = new BufferedReader(fr); This error will show java.io.BufferedInputStream@677327b6 (No such file or directory)File: "java.io.BufferedInputStream@677327b6" not Found. –  Dec 02 '15 at 02:11
  • then how can I implement like this: InputStream filename = getClass().getResourceAsStream("/resources/InputFile.txt"); File file = new File(filename.toString()); FileReader fr = new FileReader(file); br = new BufferedReader(fr); –  Dec 02 '15 at 02:15
  • Wrap the `InputStream` into a `InputStreamReader` into a `BufferedReader`, for example; `BufferedReader br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/resources/InputFile.txt")))` – MadProgrammer Dec 02 '15 at 02:18
  • Hi! Everytime, while I need to work with files and I dont know how to correctly write path to a file, I'm using following thing- one you have instanced "File", you can call (and print) actual path- look in http://docs.oracle.com/javase/7/docs/api/java/io/File.html There is getAbsolutePath() :o) – xxxvodnikxxx Dec 02 '15 at 07:50

0 Answers0