### **1、复制文件:**
注:该方法支持中文处理,适用于TXT、XML、JPG、DOC等多种格式的文件
```
public static void copyFile(String source, String destination) throws IOException {
FileInputStream in = new FileInputStream(source);
File file = new File(destination);
if (!file.exists())
file.createNewFile();
FileOutputStream out = new FileOutputStream(file);
int c;
byte buffer[] = new byte[1024];
while ((c = in.read(buffer)) != -1) {
for (int i = 0; i < c; i++)
out.write(buffer[i]);
}
in.close();
out.close();
} //测试:copyFile("D:\\TASK.txt", "E:\\TASK.txt");
```
### **2、文件重命名:**
```
public static void renameFile(String oldName, String newName) {
if (!oldName.equals(newName)) {// 新的文件名和以前文件名不同时,才有必要进行重命名
File oldFile = new File(oldName);
File newFile = new File(newName);
if (newFile.exists())// 若在该目录下已经有一个文件和新文件名相同,则不允许重命名
System.out.println(newName + "已经存在!");
else {
oldFile.renameTo(newFile);
}
}
} //测试:renameFile("D:\\TASK.txt", "D:\\TASK2.txt");
```
### **3、读文件:**
1)使用BufferedReader类读取:
```
public static String readFile(String path) throws IOException {
File file = new File(path);
if (!file.exists() || file.isDirectory())
throw new FileNotFoundException();
BufferedReader br = new BufferedReader(new FileReader(file));
String temp = null;
StringBuffer sb = new StringBuffer();
temp = br.readLine();
while (temp != null) {
sb.append(temp + "\r\n");
temp = br.readLine();
}
return sb.toString();
}
```
2)使用FileInputStream类读取:
```
public static String readFile(String path) throws IOException {
File file = new File(path);
if (!file.exists() || file.isDirectory())
throw new FileNotFoundException();
FileInputStream fis = new FileInputStream(file);
byte[] buf = new byte[1024];
StringBuffer sb = new StringBuffer();
while ((fis.read(buf)) != -1) {
sb.append(new String(buf));
buf = new byte[1024];// 重新生成,避免和上次读取的数据重复
}
return sb.toString();
}
```
### **4、写文件:**
```
public static void writeFile(String path, String content, String encode)throws IOException {
File file = new File(path);
if (!file.exists())
file.createNewFile();
FileOutputStream out = new FileOutputStream(file, true);
StringBuffer sb = new StringBuffer();
sb.append(content);
out.write(sb.toString().getBytes(encode));
out.close();
} //测试:writeFile("D:\\TASK2.txt", "\r\n这是我加入的内容", "GBK");
```
### **5、删除(有子文件的)目录:**
注:如果方法参数指向的目录有子目录,则删除会失败,因此必须通过递归调用逐层删除文件,最后删除目录
```
public static void deleteDir(String path) {
File dir = new File(path);
if (dir.exists()) {
File[] tmp = dir.listFiles();
for (int i = 0; i < tmp.length; i++) {
if (tmp[i].isDirectory()) {
deleteDir(path + "/" + tmp[i].getName());
} else {
tmp[i].delete();
}
}
dir.delete();
}
} //测试:deleteDir("D:\\task");
```