Java FileNotFoundException with Absolute path - Cant Read or Execute, but file exists [duplicate]

萝らか妹 提交于 2019-12-11 01:07:17

问题


I'm sure this has been answered, but ten different strategies hasn't worked on this issue.

If I use C:\Users\Anny\Dropbox\SocialMediaOcto\instructions\Trees\instructions.txt as my absolute path for the file, IDEA cannot read or execute from this path. If I take that same path and paste it into windows explorer, it will execute right away. I dont want to focus on a working directory as this file works as the program's configurations file, but replaceing the slashes with backslashes doesnt work, the absolute path still brings me to the file, but IDEA doesnt launch.

I'm at wits end.

 public static String generateFileName(String folder){

    String filename = "";
    List<String> hashtags = new ArrayList<>();
    String instructions_file =         "C:\Users\Anny\Dropbox\SocialMediaOcto\instructions\Trees\instructions.txt";

    //does not return true-true, but can launch file on windows explorer..
    System.out.println("FILE EXIST AND EXECUTE?" + new File(instructions_file).getAbsoluteFile().canRead() +" "+new File(instructions_file).getAbsoluteFile().canExecute());

    System.out.println(new File(instructions_file).getAbsoluteFile());
    //C:\Users\Anny\Dropbox\SocialMediaOcto\instructions\Trees\instructions.txt

    BufferedReader br = null;

    try {

        String sCurrentLine;

        br = new BufferedReader(new FileReader(new File(instructions_file).getAbsoluteFile()));

EDIT After replacing backslashes with forward slashes, the reader still cannot properly read or execute the file.

LOG: The string prints: C:/Users/Anny/Dropbox/SocialMediaOcto/instructions/Bees/instructions.txt

  java.io.FileNotFoundException:    C:\Users\Anny\Dropbox\SocialMediaOcto\instructions\Bees\instructions.txt (The system cannot find the file specified)

回答1:


Correct url:

String instructions_file = "C:/Users/Anny/Dropbox/SocialMediaOcto/instructions/Trees/instructions.txt";

Because \ is an escape character in Java. If you want to use \ as a character you have to escape it itself.

Correct Url v2:

String instructions_file  = "C:\\Users\\Anny\\Dropbox\\SocialMediaOcto\\instructions\\Trees\\instructions.txt";

What you had:

String instructions_file  = "C:\Users\Anny\Dropbox\SocialMediaOcto\instructions\Trees\instructions.txt";

is read by java as

"C:{something}sers{something}nny{something}ropbox{something}ocialMediaOcto{something}nstructions\Trees\instructions.txt"

In my oppinion it's much better to use the first approach as it's platform safe.



来源:https://stackoverflow.com/questions/39286320/java-filenotfoundexception-with-absolute-path-cant-read-or-execute-but-file-e

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!