Java tutorial
Java tutorial
Copying Files
When directories are copied, the copy is shallow. A shallow copy means that the
files and subdirectories within the directory are not copied.
Files.copy(Path.of("book.txt"), Path.of("movie.txt"),
StandardCopyOption.REPLACE_EXISTING);
The first method reads the contents of an I/O stream and writes the output to a
file. The second method reads the contents of a file and writes the output to an I/O
stream.
Files.copy(Path.of("/fish/clown.xsl"), System.out);
Files.move(Path.of("C:\\zoo"), Path.of("C:\\zoo-new"));
Files.move(Path.of("C:\\user\\addresses.txt"),
Path.of("C:\\zoo-new\\addresses2.txt"));
The first example renames the zoo directory to a zoo-new directory, keeping all of
the original contents from the source directory. The second example moves
the addresses.txt file from the directory user to the directory zoo-new and renames
it addresses2.txt .
Like copy() , move() requires REPLACE_EXISTING to overwrite the target if it exists;
otherwise, it will throw an exception
Another enum value that you need to know for the exam when working with
the move() method is the StandardCopyOption value ATOMIC_MOVE .
Files.move(Path.of("mouse.txt"), Path.of("gerbil.txt"),
StandardCopyOption.ATOMIC_MOVE);
An atomic move is one in which a file is moved within the file system as a single
indivisible operation. Put another way, any process monitoring the file system
never sees an incomplete or partially written file. If the file system does not
support this feature, an AtomicMoveNotSupportedException will be thrown.
Files.delete(Path.of("/vulture/feathers.txt"));
Files.deleteIfExists(Path.of("/pigeon"));
Sometimes you want to compare the contents of the file rather than whether it is
physically the same file
The mismatch() method takes two Path objects as input. The method returns -1 if
the files are the same; otherwise, it returns the index of the first position in the file
that differs.