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

তৈদুছড়া ঝর্ণা : খাগড়াছড়ি

(সংগৃহীত) তৈদুছড়া ঝর্ণা:তৈদুছড়া এলাকায় খুব কাছাকাছিই বড় ঝর্ণা আছে তিনটি।এছাড়া এক ঝর্ণা থেকে আরেক ঝর্ণায় যাওয়ার পথে আছে বেশ কয়েকটি ছোট ঝর্ণা এবং যাওয়ার ঝিরিপথটাও অসাধারণ সুন্দর। ঝর্ণা দেখার সাথে সাথে পাহাড়ের ঢাল বেড়ে ট্রেকিং- এর থ্রিলটাও পাওয়া যাবে এখানে। পুরো এলাকাতেই জুম চাষ করা হয়,তাই পাহাড়ের ঢালে ঢালে দেখা পাবেন অসংখ্য সুন্দর সুন্দর জুম ঘরের। যেভাবে যাবেন: ঢাকা থেকে শান্তি পরিবহনে সরাসরি আসতে পারেন দিঘীনালায়,অথবা শ্যামলী, এস আলম সেন্টমার্টিন পরিবহনে খাগড়াছড়ি এসে খাগড়াছড়ি থেকে সিএনজ ি তে আসতে পারবেন দিঘীনালা।খাগড়াছড়ি -দিঘীনালা সময় লাগবে ৪০ মিনিট। ভাড়া ৬০টাকা। দিঘীনালার জামতলি থেকে হেঁটে যেতে হবে ঝর্ণায়,দিঘীনালা থেকে জামতলি যেতে পারবেন অটোরিকশায়।ঝর্ণায় যেতে ২-৩ ঘন্টা লাগে,সকালে রওনা দিলে বিকেলের মধ্যেই ফিরে আসা যায়। থাকবেন কোথায়:দিঘীনালায় ফ্যামিলি নিয়ে থাকার মত হোটেল রয়েছে বাস স্টেশনের পাশেই। বাস স্টেশন থেকে তিন মিনিট হাঁটলে বোয়ালখালি বাজারেও পাবেন থাকার হোটেল। সাথে যা যা নিতে হবে:শুকনো খাবার নিয়ে নিতে হবে সাথে,পানিও নিয়ে নেবেন।দড়ি নেবেন,কাজে লাগবে।অবশ্যাই ভালো গ্রিপ আ...

How to automatically rotate catalina.out daily

How to automatically rotate catalina.out daily or when it becomes bigger than 5M 1. Create this file /etc/logrotate.d/tomcat   2. Copy the following contents into the above file /usr/tomcat/default/logs/catalina.out {    copytruncate    daily    rotate 7    compress    missingok     size  5M   }   About the above configuration: Make sure that the path  /var/log/tomcat/catalina.out  above is adjusted to point to your tomcat’s catalina.out daily  -  rotates the catalina.out  daily rotate  – keeps at most  7  log files compress –  compresses   the rotated files size  – rotates if the size of catalina.out is bigger than  5M copytruncate  – truncates the original log file in place after creating a copy, instead of moving the old log file and optionally creatin...

How to batch INSERT and UPDATE statements with Hibernate

Courtesy: VLAD MIHALCEA Introduction JDBC  has long been offering support for  DML  statement batching. By default, all statements are sent one after the other, each one in a separate network round-trip. Batching allows us to send multiple statements in one-shot, saving unnecessary socket stream flushing. Hibernate hides the database statements behind a transactional  write-behind abstraction layer . An intermediate layer allows us to hide the JDBC batching semantics from the persistence layer logic. This way, we can change the JDBC batching strategy without altering the data access code. Configuring Hibernate to support JDBC batching is not as easy as it should be, so I’m going to explain everything you need to do in order to make it work. Testing time We’ll start with the following entity model: The  Post  has a one-to-many association with the  Comment  entity: 1 2 3 4 5 @OneToMany (    ...