Showing posts with label How to rename and copy file in java. Show all posts
Showing posts with label How to rename and copy file in java. Show all posts

Tuesday, August 11, 2015

Rename:

First we rename a file.

// file location
File oldFile = new File("C:\\Users\\radiate\\Desktop\\OldFolder\\villain.jpg"); // source file location

String oldFileName = oldFile.getName();

// rename the villain.jpg file to darklord.jpg
String rename = oldFileName.replace(oldFileName, "darklord.jpg");

System.out.println("old file name: " + oldFileName +"\n"+"rename file name : " +rename);

Output:

old file name: villain.jpg

rename file name : darklord.jpg

Copy:

Now we move the rename file into another location.

File newFileLocation = new File("C:\\Users\\radiate\\Desktop\\NewFolder"); // destination location

try {

FileInputStream inputOldFile = new FileInputStream(oldFile);
FileOutputStream outputNewFile = new FileOutputStream(newFileLocation.getAbsolutePath()+"\\"+rename);

// this is for copy the file into new location with new name
byte[] buffer = new byte[1024];
int filelength;
while((filelength= inputOldFile.read(buffer))>0){
outputNewFile.write(buffer, 0, filelength);
}
inputOldFile.close();
outputNewFile.close(); // end copy
System.out.println("Successful Rename and move");
} catch (IOException e) {
e.printStackTrace();
}

Output:
old file name: villain.jpg
rename file name : darklord.jpg
Successful Rename and move



Download the source file