我想知道是否有人知道为什么我在尝试查找我知道目录中存在的文件时可能会收到 java.io.FileNotFoundException
。
我认为与此有关,请让我知道我是否正确或是否有其他问题:
- 我将我的 JVM 从 1.7 降级到 1.6
- 文件名包含两个问号,所以文件名为
filename_?)?.data
当我使用 JVM 1.7 时,该程序能够找到并打开该文件。但是,降级到 1.6 后,似乎找不到这个特定文件。所以我想 JVM 1.6 可能无法读取其中带有问号的文件。
此外,我双重/三次检查,文件确实存在于我的程序正在查找的目录中(它也能够在其中找到其他文件)。
下面是我的代码:
public Object readFromFile(String fileName) {
// Check for null
if (fileName == null || fileName.equals("")) return null;
Object obj = null;
ObjectInputStream input = null;
// Open file into (input)
try {
input = new ObjectInputStream(new FileInputStream(fileName + ".data"));
} catch (IOException e) {
e.printStackTrace();
}
// Read content of file into (obj)
try {
obj = input.readObject();
input.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return obj;
}
最佳答案
可能你需要在使用特殊字符时对你的文件名进行编码
试试这个
String fileNameNew= java.net.URLEncoder.encode(fileName);
if (fileNameNew == null || fileNameNew.equals("")) return null;
Object obj = null;
ObjectInputStream input = null;
...
你可以在这里查看:How to determine if a String contains invalid encoded characters
关于java - 文件存在时抛出 FileNotFoundException。文件名可能包含特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14592091/