当在 中的文件名中遇到 null 时java.io.File
,该字符及其后面的所有字符都将被忽略,从而导致File.exists()
.
java.io.File.exists()
这种行为是我错过的某些方面吗?
例子:
package os;
import java.io.File;
import java.io.IOException;
public class FileNullCheck
{
public static void main(String[] args)
{
File tmp = new File("a.txt");
try
{
tmp.createNewFile();
}
catch (IOException e)
{
e.printStackTrace();
return;
}
String a = "a.txt";
System.out.printf("a.txt exists: %b (len=%d)%n",new File(a).exists(),a.length());
String anull = new String(new byte[] { 'a', '.', 't', 'x', 't', 0x00 });
System.out.printf("a.txt (null) exists: %b (len=%d)%n",new File(anull).exists(),anull.length());
String anullx = new String(new byte[] { 'a', '.', 't', 'x', 't', 0x00, 'x' });
System.out.printf("a.txt (nullx) exists: %b (len=%d)%n",new File(anullx).exists(),anullx.length());
}
}
运行这个的结果。
a.txt 存在:true (len=5) a.txt (null) 存在:true (len=6) a.txt (nullx) 存在:true (len=7)
Linux系统有以下JVM。
Java(TM) SE 运行时环境 (build 1.7.0_10-b18) Java HotSpot(TM) 64 位服务器 VM(内部版本 23.6-b04,混合模式)
该行为似乎类似于 C,并且用于验证文件系统上的文件的字符串在 null 处被截断。
但我希望 Java 的行为File.exists()
对这些无效的文件名返回 false。
更新:2013 年 9 月 19 日
Java 1.7.0 更新 40 已将此作为错误 JDK-8014846 的一部分进行了修复:java.io 中的文件和其他类无法正确处理嵌入的空值