java - 如何使用路径类?
问题描述
public static void main(String[] args) {
java.nio.file.Path p = Paths.get("E:/test/Hellow.txt");
try {
FileOutputStream f = new FileOutputStream(p.getParent() + "hellow2.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
你好,如何使用路径类?
我希望将输入文件E:/test/Hellow.txt
输出到E:/test/Hellow2.txt
但我得到E:\testHellow2.txt
的是输出文件名。我该如何解决?
解决方案
您应该resolve
使用副本应该获得的新文件名作为源文件的父目录。
看看这个例子:
public static void main(String[] args) {
// provide the source file (must exist, won't check for that here)
Path sourceFile = Paths.get("D:/ZZ--temp/Hellow.txt");
// then try to copy source to target
try {
Path copy = Files.copy(sourceFile,
/* get the parent directory of the source file
* and resolve it with the file name of the copy
*/
sourceFile.getParent().resolve("Hellow2.txt"),
StandardCopyOption.REPLACE_EXISTING);
if (Files.exists(copy)) {
System.out.println("Successfully copied"
+ sourceFile.toAbsolutePath().toString()
+ " to "
+ copy.toAbsolutePath().toString());
}
} catch (IOException e) {
e.printStackTrace();
}
}
它真的复制文件并在我的机器上输出以下内容(路径不等于你的!)
Successfully copiedD:\ZZ--temp\Hellow.txt to D:\ZZ--temp\Hellow2.txt
推荐阅读
- spring-boot - Sleuth Tracing 不适用于 Spring JMS
- excel - Excel:嵌套 if 和/或
- c# - 表格单元格中的 C# iText 长段落重叠
- oracle - 将 Neo4J 数据导入 Oracle 关系数据库
- lotus-notes - 外出 - 不自动回复发送给群组的邮件
- java - 将方法从文件转换为 LambdaExpression
- sql - SQL server 中的 String_agg 等效函数
- r - 如何在ggplot中写化学式
- php - Firebase , android 和 PHP 后端
- javascript - 如何将 componentDidMount() 和 componentWillUnmount 转换为 useEffect()?