我的文件位于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)
如何解决此异常请指导
答案 0 :(得分:3)
你想做什么?
您不需要通过%20
手动替换空白。
File.toURI()
为此目标服务。
此外,你问我在哪里:
File source = new File(sourceFilePath.toString(),"designspec.docx");
您传递了URI的字符串表示形式,但这不适用于需要两个File
pathname
的{{1}}构造函数。
要解析文件夹中的文档,URI无用:
String
顺便说一下,你也可以使用Path而不是File,它是一个设计得更好的API:
String sourceFilePathStr="C:\\Users\\abc xyz\\Downloads";
File source = new File(sourceFilePathStr,"designspec.docx");