我有一个文件位于 C:\Users\abc xyz\Downloads\designspec.docx 我想使用此代码将此文件复制到另一个目录
String sourceFilePathStr="C:\\Users\\abc xyz\\Downloads";
URI sourceFilePath = new URI(("file:///"+ sourceFilePathStr.replaceAll(" ", "%20")));
File source = new File(sourceFilePath.toString(),"designspec.docx");
File dest = new File("path to another directory","designspec.docx");
try {
inputChannel = new FileInputStream(source).getChannel();
outputChannel = new FileOutputStream(dest).getChannel();
outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
log.info("copy complete");
} finally {
inputChannel.close();
outputChannel.close();
}
上面的代码抛出异常
SEVERE: got NoFilepatternException {}
java.net.URISyntaxException: Illegal character in path at index 11: file:///C:\Users\abc%20xyz\Downloads
at java.net.URI$Parser.fail(URI.java:2848)
at java.net.URI$Parser.checkChars(URI.java:3021)
at java.net.URI$Parser.parseHierarchical(URI.java:3105)
at java.net.URI$Parser.parse(URI.java:3053)
at java.net.URI.<init>(URI.java:588)
如何解决此异常,请指导
最佳答案
你想做什么?
您不需要手动将空格替换为 %20
。
File.toURI()
服务于此目标。
此外,我认为您存在问题:
File source = new File(sourceFilePath.toString(),"designspec.docx");
您传递了 URI 的字符串表示形式,但这不适用于需要两个 pathname
String
的 File
构造函数。
要解析文件夹中的文档,URI 是无用的:
String sourceFilePathStr="C:\\Users\\abc xyz\\Downloads";
File source = new File(sourceFilePathStr,"designspec.docx");
<小时/>
顺便说一下,您也可以使用 Path 而不是 File,这是一个设计更好的 API:
Path parentPath = Paths.get("C:\\Users\\abc xyz\\Downloads");
Path filePath = Paths.get(parentPath, "designspec.docx");
关于java nio NoFilepatternException如何处理文件路径中的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49386870/