Java中的FileNotFoundException绝对路径问题 - 无法读取或执行,但文件存在

3
我确定这个问题已经有答案了,但是十种不同的策略都没有解决这个问题。
如果我使用以下绝对路径作为文件路径:C:\Users\Anny\Dropbox\SocialMediaOcto\instructions\Trees\instructions.txt,IDEA无法读取或执行该路径。如果我将相同的路径粘贴到Windows资源管理器中,它就能够立即执行。我不想关注工作目录,因为该文件作为程序的配置文件而存在,但是用反斜杠替换斜杠并不能解决问题,绝对路径仍然可以找到该文件,但是IDEA不能启动。
我已经快要崩溃了。
 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()));

编辑 将反斜杠替换为正斜杠后,读者仍然无法正确读取或执行文件。

日志: 该字符串打印: 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)

2
你必须使用双斜杠来转义反斜杠。我认为这段代码肯定会导致编译错误。 - Jens
1
在Java中,你需要使用双反斜杠。字符串 instructions_file = "C:\Users\Anny\Dropbox\SocialMediaOcto\instructions\Trees\instructions.txt"; - dsp_user
https://docs.oracle.com/javase/tutorial/essential/io/pathOps.html - Prashant Shilimkar
使用正斜杠更安全。 - xenteros
多亏了Xenteros,解决方案不是将txt文件命名为filename.txt.txt。 - Jayizzle
1个回答

6

正确的网址:

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

因为在Java中\是一个转义字符。如果要将\作为一个字符使用,你需要对其进行转义。

正确的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";

Java将其读作。
"C:{something}sers{something}nny{something}ropbox{something}ocialMediaOcto{something}nstructions\Trees\instructions.txt"

在我看来,使用第一种方法更好,因为它是跨平台的。

我想我也是用 \ 构建它的,但我会处理这个问题。谢谢。 - Jayizzle
1
@Jayizzle 使用正斜杠是更好的方法!它在各个平台上都是安全的。使用反斜杠可能在某些操作系统上无法正常工作。如果您觉得这个答案有帮助,请点击分数下方的灰色勾选标记为解决方案。 - xenteros
等一下,不对,它还是没有完全成功。仍然抛出相同的错误。 - Jayizzle
我在我的字符串或程序参数中没有反斜杠,但它仍然出现相同的错误。 - Jayizzle
这正是我所想的。 - xenteros
显示剩余7条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接