java 文件夹存在但是找不到,具有绝对路径的Java FileNotFoundException-无法读取或执行,但是文件存在...

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 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)

解决方案

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.

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值