0

I am trying to fetch a txt file from a specific folder not the same as that of the class in which I am trying to fetch using this simple code:

import java.io.File;
public class MyClass{
    private static  File file = new File("/folder1/folder2/myFile.txt");
    public static void main(String[ ] args) {
        //And trying to check if it exists
        if(file.exists()) {
            System.out.println(file.getName() +  "exists!");
        }
        else { 
            System.out.println("The file does not exist");
        }
    }
}

with the following directory structure:

cFolder1
-->cFolder2
   -->cFolder3
      |>MyClass.java
folder1
-->folder2
   |>myFile.txt

However, the above code is always giving the output:

The file does not exist

which is unexpected(to me). How can I solve this problem?


I have tried solutions as given in these QA links, but NONE worked for me:

Link 1

Link 2

Link 3

Aditya
  • 126
  • 9
  • 1
    Have you tried it without the '/' in front of folder1? That is telling it to look for folder1 in the root of your machine. Also you may want to print the output of file.getAbsolutePath() to see where your program thinks it's looking of that file – user27158 Jun 04 '19 at 16:12
  • 1
    Application resources will become embedded resources by the time of deployment, so it is wise to start accessing them as if they were, right now. An [tag:embedded-resource] must be accessed by URL rather than file. See the [info. page for embedded resource](http://stackoverflow.com/tags/embedded-resource/info) for how to form the URL. – Andrew Thompson Jun 04 '19 at 16:53
  • 1
    @user27158 thanks this piece of code helped: `file.getAbsolutePath()` – Aditya Jun 04 '19 at 17:30
  • @AndrewThompson thanks! forming the input stream is causing an error as I want the embedded to be accessible form myClass only, thus using the keyword STATIC, which gives the error that non-static variable this cannot be accessed from a static context, as I am fairly new to java, you can also suggest me another or better way to do it. – Aditya Jun 04 '19 at 17:44
  • *"I want the embedded to be accessible form myClass only, thus using the keyword `STATIC`"* That's how `private` works, not `static`. – Andrew Thompson Jun 05 '19 at 02:30

0 Answers0