【问题标题】:Invalid file path, but only if I build the file name with a field文件路径无效,但仅当我使用字段构建文件名时
【发布时间】:2019-10-16 20:13:14
【问题描述】:

下面给我一个FileNotFoundException: Invalid file path

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

this.ext 之前已设置为 "txt"

玩了之后,我发现这完全没问题。

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

为什么我不能使用字段?

【问题讨论】:

  • 你能粘贴整个类的代码吗?
  • 您应该使用Path 实例而不是String 来表示目录路径。

标签: java file field filenotfoundexception


【解决方案1】:

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

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

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

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

【讨论】:

  • 在调试器中找到了。干杯!
【解决方案2】:

在调试器中查看后,看起来我的字段值为“\0\0\0\0\0txt”(即 NUL ascii 字符)。

Java 将“\0”视为空字符串,因此我的 println 语句没有显示问题。

在 4 年的大学生活中,我一定是第一次需要使用调试器!

【讨论】:

  • Java 不认为空字符 \0 '空'。 (C 将其视为字符串终止符,C++ 对 C 风格的字符串执行相同的操作,但 std::string 和 std::wstring 除外。)Java 像任何其他(可编码)字符一样输出它。但是,如果您要输出到任何类型的显示器、终端或控制台,那些不会为 null 显示任何内容。
猜你喜欢
  • 2020-05-17
  • 1970-01-01
  • 2021-07-18
  • 1970-01-01
  • 2019-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-26
相关资源
最近更新 更多