public static void copyfile(File fromFile, File toFile){
if(!fromFile.exists()){
return;
}
if(!fromFile.isFile()){
return;
}
if(!fromFile.canRead()){
return;
}
if(!toFile.getParentFile().exists()){
toFile.getParentFile().mkdirs();
}
if(toFile.exists()){
toFile.delete();
}
try {
FileInputStream fosfrom = new FileInputStream(fromFile);
FileOutputStream fosto = new FileOutputStream(toFile);
byte[] bt = new byte[1024];
int c;
while((c=fosfrom.read(bt)) > 0){
fosto.write(bt,0,c);
}
fosfrom.close();
fosto.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
- 其他的一些常用的方法,都放在FileUtils 类里面了
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileUtils {
public static boolean createDirs(String dirPath) {
File file = new File(dirPath);
if (!file.exists() || !file.isDirectory()) {
return file.mkdirs();
}
return true;
}
public static void copyfile(File fromFile, File toFile){
if(!fromFile.exists()){
return;
}
if(!fromFile.isFile()){
return;
}
if(!fromFile.canRead()){
return;
}
if(!toFile.getParentFile().exists()){
toFile.getParentFile().mkdirs();
}
if(toFile.exists()){
toFile.delete();
}
try {
FileInputStream fosfrom = new FileInputStream(fromFile);
FileOutputStream fosto = new FileOutputStream(toFile);
byte[] bt = new byte[1024];
int c;
while((c=fosfrom.read(bt)) > 0){
fosto.write(bt,0,c);
}
fosfrom.close();
fosto.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void delFolder(String folderPath) {
try {
delAllFile(folderPath);
String filePath = folderPath;
filePath = filePath.toString();
File myFilePath = new File(filePath);
myFilePath.delete();
} catch (Exception e) {
System.out.println("删除文件夹操作出错");
e.printStackTrace();
}
}
public static void delAllFile(String path) {
File file = new File(path);
if (!file.exists()) {
return;
}
if (!file.isDirectory()) {
return;
}
String[] tempList = file.list();
File temp = null;
for (int i = 0; i < tempList.length; i++) {
if (path.endsWith(File.separator)) {
temp = new File(path + tempList[i]);
} else {
temp = new File(path + File.separator + tempList[i]);
}
if (temp.isFile()) {
temp.delete();
}
if (temp.isDirectory()) {
delAllFile(path + "/" + tempList[i]);
delFolder(path + "/" + tempList[i]);
}
}
}
}