首页 > 解决方案 > Invalid file path, but only if I build the file name with a field

问题描述

The following gives me a FileNotFoundException: Invalid file path

String fileName = "folder/file" + "." + this.ext;
try {
  File file = new File(fileName);
} catch(Exception e){
}

Where this.ext has previously been set to "txt"

After playing around, I find that this works perfectly fine.

String ext = "txt";
String fileName = "folder/file" + "." + ext;
try {
  File file = new File(fileName);
} catch(Exception e){
}

Why can't I use a field?

标签: javafilefieldfilenotfoundexception

解决方案


没有理由不能使用字段 ie this.ext。如果你在下面一行放了一个调试点,你会发现this.ext没有设置为"txt"

String fileName = "folder/file" + "." + this.ext;

如果您对调试器不满意,只需将以下行放在上述行之前,您就可以找到问题所在:

System.out.println("this.ext="+this.ext);

推荐阅读