首页 > 解决方案 > 如何使用路径类?

问题描述

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的是输出文件名。我该如何解决?

标签: java

解决方案


您应该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

推荐阅读