使用以下代码:为什么Path/File放弃尾随文件分隔符?
import java.io.File;
import java.lang.ProcessBuilder.Redirect;
import java.util.ArrayList;
import java.util.List;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
class Target {
String name;
public Target() {
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
public class Test {
public static void main(String args[]) {
Target target = new Target();
target.setName("A");
String tmpDir = System.getProperty("user.dir") + File.separator + "tmp_" + target.getName() + File.separator;
System.out.println("Tmp dir: " + tmpDir);
Path atfTmpPath= Paths.get(tmpDir);
File filePath = atfTmpPath.toFile();
System.out.println("Tmp path: " + atfTmpPath.toAbsolutePath());
System.out.println("Tmp file path: " + filePath.getAbsolutePath());
}
}
〜
这将产生以下输出:
Tmp dir: /home/john/tmp/tmp_A/
Tmp path: /home/john/tmp/tmp_A
Tmp file path: /home/john/tmp/tmp_A
为什么后行文件分离器中除去?如果我以后要使用的路径和文件复制到其中:
Files.copy(src, atfTmpPath);
复制失败(FileAlreadyExistsException)(我想!),因为它认为,该目标是一个文件,而不是一个目录,因为它缺少尾随文件分隔符。我找不到任何方法将Path制作为目录路径。
请注意,使用'copy()'第二个参数是目标*文件*的路径,您不能使用目录作为目标。 –
因此Files.copy相当于'cp test1.log test2.log',但如果'test2'是一个目录,则不能执行'cp test1.log test2 /'。当然不是... – eeijlar
它肯定不能... –