Java.io.File does not contains any ready make move file method, but you can workaround with the following two alternatives :
- File.renameTo().
- Copy to new file and delete the original file.
- File Set Read Only
In the below two examples, you move a file “C:\\folderA\\Afile.txt” from one directory to another directory with the same file name “C:\\folderB\\Afile.txt“.
A Java program to demonstrate the use of java.io.File setReadOnly() method to make a file read only. Since JDK 1.6, a new setWritable() method is provided to make a file to be writable again.
A Java program to demonstrate the use of java.io.File setReadOnly() method to make a file read only. Since JDK 1.6, a new setWritable() method is provided to make a file to be writable again.
1. File.renameTo()
package com.naresh.file; import java.io.File; public class MoveFileExample { public static void main(String[] args) { try{ File afile =new File("C:\\folderA\\Afile.txt"); if(afile.renameTo(new File("C:\\folderB\\" + afile.getName()))){ System.out.println("File is moved successful!"); }else{ System.out.println("File is failed to move!"); } }catch(Exception e){ e.printStackTrace(); } } }
2. Copy and Delete
package com.naresh.file; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class MoveFileExample { public static void main(String[] args) { InputStream inStream = null; OutputStream outStream = null; try{ File afile =new File("C:\\folderA\\Afile.txt"); File bfile =new File("C:\\folderB\\Afile.txt"); inStream = new FileInputStream(afile); outStream = new FileOutputStream(bfile); byte[] buffer = new byte[1024]; int length; //copy the file content in bytes while ((length = inStream.read(buffer)) > 0){ outStream.write(buffer, 0, length); } inStream.close(); outStream.close(); //delete the original file afile.delete(); System.out.println("File is copied successful!"); }catch(IOException e){ e.printStackTrace(); } } }
3. File Read Onlypackage com.naresh.file; import java.io.File; import java.io.IOException; public class FileReadAttribute { public static void main(String[] args) throws IOException { File file = new File("c:/file.txt"); //mark this file as read only, since jdk 1.2 file.setReadOnly(); if(file.canWrite()){ System.out.println("This file is writable"); }else{ System.out.println("This file is read only"); } //revert the operation, mark this file as writable, since jdk 1.6 file.setWritable(true); if(file.canWrite()){ System.out.println("This file is writable"); }else{ System.out.println("This file is read only"); } } }Output
This file is read only This file is writable
No comments:
Post a Comment