我有一个位于 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:Usersabc%20xyzDownloads
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");
顺便说一下,你也可以使用路径而不是文件,这是一个设计更好的API:
Path parentPath = Paths.get("C:\Users\abc xyz\Downloads");
Path filePath = Paths.get(parentPath, "designspec.docx");