Move a file
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class Main {
public static boolean copyFile(File source, File dest) {
try {
FileInputStream sourceFile = new FileInputStream(source);
try {
java.io.FileOutputStream destinationFile = null;
try {
destinationFile = new FileOutputStream(dest);
// Lecture par segment de 0.5Mo
byte buffer[] = new byte[512 * 1024];
int nbLecture;
while ((nbLecture = sourceFile.read(buffer)) != -1) {
destinationFile.write(buffer, 0, nbLecture);
}
} finally {
destinationFile.close();
}
} finally {
sourceFile.close();
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
public static boolean moveFile(File source, File destination) {
if (!destination.exists()) {
boolean result = source.renameTo(destination);
if (!result) {
result = true;
result &= copyFile(source, destination);
if (result){
result &= source.delete();
}
}
return (result);
} else {
return (false);
}
}
}
Home
Java Book
Runnable examples
Java Book
Runnable examples
IO File:
- Compare File Dates
- Compress files using with ZIP
- Concatenate files
- Copy a File with NIO FileChannel and ByteBuffer
- Copy a file with FileReader and FileWriter
- Copy a file with InputStream and OutputStream
- Copy a file and overwrite
- Delete a file
- Delete File Recursively
- Get readable file size
- Move a file
- Rename a file
- Report a file's status
- Search a file by regular expressions
- Touch a file: set File Last Modified Time