Reputation: 11
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();
}
}
Hi, How to use path class?
I want input file E:/test/Hellow.txt
to be output to E:/test/Hellow2.txt
But I'm getting E:\testHellow2.txt
as the output file name. How do I fix this?
Upvotes: 0
Views: 108
Reputation: 18568
You should resolve
the parent directory of the source file with the new file name the copy should get.
Have a look at this example:
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();
}
}
It really copies the file and outputs the following on my machine (paths not equal to yours!)
Successfully copiedD:\ZZ--temp\Hellow.txt to D:\ZZ--temp\Hellow2.txt
Upvotes: 1