FileNotFoundException is thrown while the file is present. The file name can contain special characters
I wonder if anyone knows why I can get java.io.FileNotFoundException
it when I try to find a file that I know exists in the directory.
I think the following has something to do with this, please let me know if I am correct, or if something else:
- I downgraded my JVM from 1.7 to 1.6.
- The file name contains two question marks, so the file is called
filename_?)?.data
While I was using JVM 1.7, the program was able to find the file and open it. However, after downgrading to 1.6, it looks like it cannot find this file. So I think JVM 1.6 cannot read files with question marks in them.
Also, I check double / triple and the file exists in the directory my program is in (other files can be found as well).
Here is my code below:
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;
}
source to share
maybe you need to encode your filename when it uses special characters
try it
String fileNameNew= java.net.URLEncoder.encode(fileName);
if (fileNameNew == null || fileNameNew.equals("")) return null;
Object obj = null;
ObjectInputStream input = null;
...
and you can check here: How to determine if a string contains a string with invalid encoded characters
source to share