javalogo

Move file in Java


How to move file in Java? (Cut-paste)

Reference : here

import java.io.*;

public class MoveFile {

public static void main(String[] args) {

InputStream inStream = null;

OutputStream outStream = null;

//We will move file from folder1 to folder backup

try{

File afile =new File(“D:/folder/folder1/nama_file”);

File bfile =new File(“D:/folder/backup/nama_file”);

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 (cut-paste)

afile.delete();

//If we don’t delete file in original folder, ┬áit just copy-paste

System.out.println(“File has moved successful!”);

}catch(IOException e){

e.printStackTrace();

}

}

}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s