Skip to main content

File and Directory Copying, Moving and Deleting


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
?
File copy using the Files class
1
2
3
4
5
6
7
8
File file = new File("/**/");
// get the java.nio.file.path from this
Path filePath = file.toPath();
//create a temporary file to copy contents to.
//In actual application this is the target file for copy
Path tempFilePath = Files.createTempFile(tempDir, "temp", "a",new FileAttribute[0]);
// copy contents
Files.copy(filePath, out);
Data can be transferred using the transferTo(..) and transferFrom(..) methods of the java.nio.channels.FileChannel class. These methods use the underlying optimization of the file system and therefore in certain cases data transfer can be fast, especially for large files. However, note that the implementation is file system specific and it would be false to claim that this method is always faster then the above methods. In the example below we copy tempFile1 to tempFile2
?
File copy using the FileChannel class
1
2
3
4
5
6
7
8
9
10
// get an inputstream from file1
FileInputStream streamTemp1 = new FileInputStream(tempFile.toFile());
// get the file channel
FileChannel channel1 = streamTemp1.getChannel();
// get the file to which the contents are to be copied
FileOutputStream outputStream = new FileOutputStream(tempFile2.toFile());
// get the channel for the second file
FileChannel channel2 = outputStream.getChannel();
// transfer data from channel 1 to channel 2
channel1.transferTo(0, tempFile.toFile().length(), channel2);
Another way to copy file is to use org.apache.commons.io.IOUtils and org.apache.commons.io.FileUtils
?
File copy using apache commons io
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.File
FileUtils.copyFile(sourceFile,destFile);
To copy a directory use the directory copy method of org.apache.commons.io.FileUtils. The method below copies all contents from directory A to directory B. The directory B is created if not present. The copy method preserves file dates. The directory is of type java.io.File.
?
Copy a directory
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.
?
Move a File
1
Files.move("FileA", "FileB",StandardCopyOption.REPLACE_EXISTING);
The move method can also be used to move the contents of a directory. If the target is a non empty directory than replace would not work and the method will fail. The 'Atomic' options ensures that all files are moved or none. The move method does not work if it involves moving files across file stores.
?
Move a File
1
Files.move("DirA", "DirB",StandardCopyOption.ATOMIC_MOVE);
Move methods exist in apache commons io. There are other variants of this method as well, such asmoveDirectory(..),moveDirectoryToDirectory(..),moveFileToDirectory(..),moveToDirectory(..)
?
Move a File
1
FileUtils.moveFile("FileA", "FileB"));

Deleting file or Directory

Delete a file or directory using java.io.File. The directory needs to be empty.
?
Move a File or Directory
1
2
3
4
//delete a file
file.delete();
//delete a directory
dir.delete();
Delete a file or directory using java.nio.file.Files. The directory needs to be empty. if the Path is a symbolic link, then the link is deleted and not the target that it represents.
?
Delete a File or Directory
1
Files.delete("path");
Apache Commons IO has methods to delete a directory recursively. The method deleteQuietly(..) deletes a file or a directory without throwing an exception. The directory is deleted recursively.
?
Delete a directory recursively
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.
?
Delete a directory recursively
1
fileA.renameTo(fileB);

Comments

Popular posts from this blog

Nginx startup script

#!/bin/sh # # nginx - this script starts and stops the nginx daemon # # chkconfig:   - 85 15 # description:  NGINX is an HTTP(S) server, HTTP(S) reverse \ #               proxy and IMAP/POP3 proxy server # processname: nginx # config:      /etc/nginx/nginx.conf # config:      /etc/sysconfig/nginx # pidfile:     /var/run/nginx.pid # Source function library. . /etc/rc.d/init.d/functions # Source networking configuration. . /etc/sysconfig/network # Check that networking is up. [ "$NETWORKING" = "no" ] && exit 0 nginx="/usr/local/nginx/sbin/nginx" prog=$(basename $nginx) NGINX_CONF_FILE="/usr/local/nginx/conf/nginx.conf" [ -f /etc/sysconfig/nginx ] && . /etc/sysconfig/nginx lockfile=/var/lock/subsys/nginx make_dirs() {    # make required directories    user=`$nginx -V 2>&1 | grep "configure arguments:.*--user=" | sed...

Tomcat NIO Connector and How to Configure It

In  HTTP 1.1 , all connections between the browser and the server are considered persistent unless declared otherwise. Persistence, in this context, means to use a single TCP connection to send and receive multiple HTTP requests/responses, as opposed to opening a new connection for every single request/response pair. In tomcat, the default HTTP connector is blocking and follows a one thread per connection model. This means that in order to serve 100 concurrent users, it requires 100 active threads. We end up wasting resources (the thread) because connections may not be used heavily, but just enough to avoid a timeout. Opposed to this is the relatively new NIO or non blocking connector. This connector has a couple of poller threads used to keep the connection alive for all connected users while worker threads are called whenever data (a new HTTP request) is available. This model leads to a much better sharing of resources (threads) and a larger number of concurrent users can ...

Java + HTTPS: Unable to Find Valid Certification Path to Requested Target

Run  InstallCert.java , with your hostname and https port, and press “ 1 ” when ask for input. It will add your “localhost” as a trusted keystore, and generate a file named “ jssecacerts “. C : \ > java InstallCert localhost : 8443 Loading KeyStore C : \Program Files\Java\jre6\lib\security\cacerts . . . Opening connection to localhost : 8443 . . . Starting SSL handshake . . . javax . net . ssl . SSLHandshakeException : sun . security . validator . ValidatorException : PKIX path building failed : sun . security . provider . certpath . SunCertPathBuilderException : unable to find valid certification path to requested target at com . sun . net . ssl . internal . ssl . Alerts . getSSLException ( Unknown Source ) at com . sun . net . ssl . internal . ssl . SSLSocketImpl . fatal ( Unknown Source ) at com . sun . net . ssl . internal . ssl . Handshaker . fatalSE ( Unknown Source ) at com . sun . net . ssl . internal . ssl . Handshaker...