我在一台Windows机器上使用带有-Dfile.encoding=UTF-8的JAVA_OPTS的Tomcat 5.5.28。
我遇到了从文件系统读取文件的问题,这是我的代码:
File directory = new File(directoryPath);
if (directory.exists()) {
File[] fileInDir = directory.listFiles();
for (int i=0; i<fileInDir.length; i++) {
FileInputStream fileInput = new FileInputStream(fileInDir[i]);
...
}
}
如果文件不包含任何“奇怪”的字符,它可以正常工作。 如果目录中包含带有重音符号/波浪符号的文件名时,创建FileInputStream时会出现FileNotFoundException。
我解决了这个问题,使用解码后的字符串而不是File对象,做法如下:
String name = new String(fileInDir[i].getName().getBytes(), System.getProperty("file.encoding"));
String parent = new String(fileInDir[i].getParent().getBytes(), System.getProperty("file.encoding"));
Charset systemCharset = Charset.forName(System.getProperty("file.encoding"));
CharsetDecoder systemDecoder = systemCharset.newDecoder();
CharBuffer cbufN = systemDecoder.decode(ByteBuffer.wrap(name.getBytes()));
CharBuffer cbufP = systemDecoder.decode(ByteBuffer.wrap(parent.getBytes()));
String path = cbufP.toString() + File.separator + cbufN.toString();
FileInputStream fileInput = new FileInputStream(path);
它在我的Windows机器上运行良好,我可以读取像(X:\directory\zípìç\ñañaf.txt)这样的文件而没有问题:
我将此代码移动到其他环境:具有相同Tomcat版本(5.5.28),相同Java虚拟机版本(1.6.0_20),相同file.encoding选项(UTF-8)的Linux机器上,并再次收到FileNotFoundException。
我做错了什么吗?
感谢任何帮助。 Juan Arcadio.
FileInputStream fileInput = FileUtils.openInputStream(fileInDir[i]);
但在Linux环境中,如果文件名包含某些特殊字符,则会出现“FileNotFoundException”错误。有什么建议吗? - Juan Arcadiojava.io.FileNotFoundException: /www/compartida/carpet� (No such file or directory)
当它抛出Apache IO异常时,请打印:java.io.FileNotFoundException: File '/www/compartida/carpet�' does not exist
- Juan Arcadio