File and Directory Copying, Moving and Deleting
File and directory Copying
Copying using java.io.File
To copy a file, read the data from the file using an inputstream and write to another file using an outputstream. But there are better methods for copying, so we will not spend any time on this.
copying using java.nio.file.Files
Use the copy method to copy contents to the outputstream. The copy works by copying contents from source, putting it in a buffer and then writing the buffer to the outputstream. There are various variants of this method. we could use path for both source and target or a path for target and an inputstream for source. This later method can be used to read files from the web
1
2
3
4
5
6
7
8
| File file = new File("/*);// get the java.nio.file.path from thisPath filePath = file.toPath();//create a temporary file to copy contents to. //In actual application this is the target file for copyPath tempFilePath = Files.createTempFile(tempDir, "temp", "a",new FileAttribute[0]);// copy contentsFiles.copy(filePath, out); |
1
2
3
4
5
6
7
8
9
10
| // get an inputstream from file1FileInputStream streamTemp1 = new FileInputStream(tempFile.toFile());// get the file channelFileChannel channel1 = streamTemp1.getChannel();// get the file to which the contents are to be copiedFileOutputStream outputStream = new FileOutputStream(tempFile2.toFile());// get the channel for the second fileFileChannel channel2 = outputStream.getChannel();// transfer data from channel 1 to channel 2channel1.transferTo(0, tempFile.toFile().length(), channel2); |
1
2
3
| IOUtils.copy(new FileInputStream(file), new FileOutputStream(file2));// copy file and preserve the time stamp. the sourceFile and destFile are of type java.io.FileFileUtils.copyFile(sourceFile,destFile); |
1
| FileUtils.copyDirectory("Directory A","Directory B"); |
File and Directory Moving
Move a file. The command below moves FileA to FileB in the same directory. it can be thought of as a rename. The REPLACE_EXISTING option replaces FileB if already present. If its a symbolic link then the link is copied and not the target.
1
| Files.move("FileA", "FileB",StandardCopyOption.REPLACE_EXISTING); |
1
| Files.move("DirA", "DirB",StandardCopyOption.ATOMIC_MOVE); |
1
| FileUtils.moveFile("FileA", "FileB")); |
Deleting file or Directory
Delete a file or directory using java.io.File. The directory needs to be empty.
1
2
3
4
| //delete a filefile.delete();//delete a directorydir.delete(); |
1
| Files.delete("path"); |
1
2
| FileUtils.deleteDirectory("dirA"));FileUtils.deleteQuietly("dirB"); |
Renaming file or directory
To rename a file or a directory use the renameTo method of java.io.File or use any of the move methods described above.
1
| fileA.renameTo(fileB); |
Comments