package com.zd.file;
import org.apache.log4j.Logger;
import java.io.*;
import java.nio.channels.FileChannel;
/**
* 文件基本操作工具类
* 1.创建目录
* 2.创建目录,父目录可以不存在
* 3.新建文件
* 4.新建文件
* 5.删除文件
* 6.删除文件夹及文件
* 7.删除文件夹中文件
* 8.复制文件
* 9.复制文件夹
* 10.移动文件
* 11.在文件开头追加内容
* 12.在文件末尾追加内容
* 13.读取文件内容
* Created by ZD on 2017/11/28.
*/
public class FileUtil implements Serializable {
private static final Logger log = Logger.getLogger(FileUtil.class);
/**
* 如果文件存在就把内容追加到后面
*/
private static final int FILE_APPEND_AFTER = 1;
/**
* 如果文件存在就把内容追加到前面
*/
private static final int FILE_APPEND_BEFORE = 2;
/**
* 如果文件存在就把内容覆盖
*/
private static final int FILE_CPVER_IF_HAVE = 3;
/**
* 如果文件存在就把内容舍弃
*/
private static final int FILE_ABANDON_IF_HAVE_FILE = 4;
/**
* 如果文件不存在就把内容舍弃
*/
private static final int FILE_ABANDON_IF_NO_FILE = 5;
/**
* 文件是否存在
* @param file
* @return
*/
private static boolean exists(File file){
return file.exists();
}
/**
* 创建指定目录
* @param dir 目录
*/
public static boolean mkdir(String dir){
try{
if (dir.contains("."))
return false;
String tempDir = dir;
File dirFile = new File(tempDir);
if (!dirFile.exists()){
dirFile.mkdir();
}
}catch (Exception e){
log.error("创建指定目录出错");
e.printStackTrace();
}
return true;
}
/**
* 创建目录,父目录可以不存在
* @param dir
* @return
*/
public static boolean mkdirs(String dir){
try {
if (dir.contains("."))
return false;
String tempDir = dir;
File dirFile = new File(dir);
if (!dirFile.exists())
dirFile.mkdirs();
} catch (Exception e) {
log.error("创建目录失败");
e.printStackTrace();
}
return true;
}
/**
* 创建新文件,并将字符串写入到文件中
* @param fileName
* @param content
* @return
*/
public static boolean createNewFile(String fileName,String content){
try {
File file = new File(fileName);
if (!file.exists())
file.createNewFile();
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(content);
fileWriter.flush();
fileWriter.close();
} catch (IOException e) {
log.error("创建文件失败");
e.printStackTrace();
}
return true;
}
/**
* 创建指定文件,将字节内容写入文件中
* @param fileName
* @param bytes
* @return
*/
public static boolean createNewFile(String fileName, byte[] bytes){
try {
File file = new File(fileName);
if (!file.exists())
file.createNewFile();
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(bytes);
fileOutputStream.flush();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
/**
* 创建文件
* @param fileName
* @return
*/
public static boolean createNewFile(String fileName){
try {
File file = new File(fileName);
if (!file.exists())
file.createNewFile();
} catch (IOException e) {
log.error("创建文件失败");
e.printStackTrace();
}
return true;
}
/**
* 删除文件
* @param fileName
* @return
*/
public static boolean delFile(String fileName){
File file = new File(fileName);
if (!file.isDirectory())
return file.delete();
return false;
}
/**
* 删除文件夹以及文件夹中的文件
* @param dir
* @return
*/
public static boolean delDirAndFiles(String dir){
try {
delFiles(dir);
File file = new File(dir);
file.delete();
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
/**
* 删除文件夹中所有文件
* @param dir 文件夹
* @return
*/
public static boolean delFiles(String dir){
File file = new File(dir);
if (!file.exists())
return false;
if (!file.isDirectory())
return false;
String[] tempList = file.list();
File temp = null;
for (String s:tempList) {
temp = dir.endsWith(File.separator) ? new File(dir + s) : new File(dir + File.separatorChar + s);
if (temp.isFile())
temp.delete();
if (temp.isDirectory()){
delFiles(dir+"/"+s);
delDirAndFiles(dir+"/"+s);
}
}
return true;
}
/**
* 复制单个文件
* @param srcFile 包含路径的源文件
* @param destFile 目标文件夹,不存在将自动创建
* @return
*/
public static boolean copyFile(String srcFile,String destFile){
try {
FileInputStream in = new FileInputStream(srcFile);
mkdirs(destFile);
FileOutputStream out = new FileOutputStream(destFile+"/"+new File(srcFile).getName());
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) != -1)
out.write(buffer,0,length);
out.flush();
out.close();
in.close();
} catch (FileNotFoundException e) {
log.error("复制单个文件出错");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
/**
* 复制文件夹
* @param oldFolder
* @param newFolder
* @return
*/
public static boolean copyFolder(String oldFolder,String newFolder){
try {
File oldFile = new File(oldFolder);
File newFile = new File(newFolder);
if (!oldFile.exists())
return false;
if (!newFile.exists())
newFile.mkdirs();
String[] files = oldFile.list();
File temp = null;
for (String s:files){
temp = oldFolder.endsWith(File.separator) ? new File(oldFolder+s):new File(oldFolder+File.separator+s);
if (temp.isFile()){
FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(newFolder+"/"+(temp.getName()).toString());
int length;
byte[] bytes = new byte[1024];
while ((length = input.read(bytes)) != -1)
output.write(bytes,0,length);
output.flush();
output.close();
input.close();
}
if (temp.isDirectory()){
copyFolder(oldFolder+"/"+s,newFolder+"/"+s);
}
}
} catch (Exception e) {
log.error("复制文件夹出错");
e.printStackTrace();
}
return true;
}
/**
* 移动文件
* @param srcFile
* @param destFile
* @return
*/
public static boolean moveFile(String srcFile,String destFile){
if (copyFile(srcFile,destFile)) {
return delFile(srcFile);
}
return false;
}
/**
* 选择写入文件的方式
* @param path
* @param content
* @param method
*/
public static void write(String path,String content,int method){
switch (method){
case FILE_APPEND_AFTER:
appendFile(path,content);
break;
case FILE_APPEND_BEFORE:
beforFile(path,content);
break;
case FILE_CPVER_IF_HAVE:
createNewFile(path,content);
break;
case FILE_ABANDON_IF_HAVE_FILE:
createNewFile(path,content);
break;
case FILE_ABANDON_IF_NO_FILE:
if (new File(path).exists())
appendFile(path,content);
break;
default:break;
}
}
/**
* 如果文件存在就追加内容到文件中
* @param path
* @param content
*/
public static void beforFile(String path,String content){
try {
File file = new File(path);
if (!file.exists())
file.createNewFile();
String temp = System.getProperty("user.dir")+System.getProperty("file.separator")+System.currentTimeMillis()+".txt";
FileWriter fileWriter = new FileWriter(temp,true);
fileWriter.write(content+System.getProperty("line.separator"));
FileReader fileReader = new FileReader(path);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String tempString = "";
while ((tempString = bufferedReader.readLine()) != null)
fileWriter.write(tempString);
bufferedReader.close();
fileReader.close();
fileWriter.close();
fileChannelCopy(new File(temp),file);
delFile(temp);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 文件通道方式复制文件
* @param srcFile
* @param destFile
*/
public static void fileChannelCopy(File srcFile,File destFile){
try {
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
FileChannel inChannel = null;
FileChannel outChannel = null;
fileInputStream = new FileInputStream(srcFile);
fileOutputStream = new FileOutputStream(destFile);
inChannel = fileInputStream.getChannel();
outChannel = fileOutputStream.getChannel();
inChannel.transferTo(0,inChannel.size(),outChannel);
outChannel.close();
inChannel.close();
fileOutputStream.close();
fileInputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 向文件中追加内容
* @param path
* @param content
*/
public static void appendFile(String path,String content){
try {
File file = new File(path);
if (path.contains(".")){
String dir = file.getParent();
File dirFile = new File(dir);
if (!dirFile.exists())
dirFile.mkdirs();
}
if (!file.exists())
file.createNewFile();
FileWriter fileWriter = new FileWriter(file,true);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(System.getProperty("line.separator")+content);
bufferedWriter.flush();
bufferedWriter.close();
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 向文件中追加内容
* @param path
* @param bytes
*/
public static void appendFile2(String path,byte[] bytes){
try {
File file = new File(path);
if (path.contains(".")){
String dir = file.getParent();
File dirFile = new File(dir);
if (!dirFile.exists())
dirFile.mkdirs();
}
if (!file.exists()){
file.createNewFile();
}
FileOutputStream fileOutputStream = new FileOutputStream(file,true);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
bufferedOutputStream.write(bytes);
bufferedOutputStream.flush();
bufferedOutputStream.close();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 读取文件
* @param fileName
* @return
*/
public static String readFromFile(String fileName){
StringBuilder stringBuilder = new StringBuilder();
try {
File file = new File(fileName);
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String temp = null;
while ((temp = bufferedReader.readLine())!=null)
stringBuilder.append(temp+System.getProperty("line.separator"));
fileReader.close();
bufferedReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
public static void main(String[] args){
String dir = "test1/test2/test3/";
byte[] bytes = {127,2,3,4,5,6,7,8,9,10};
System.out.println("1.创建指定目录:"+FileUtil.mkdir("test"));
System.out.println("2.创建目录,父路径可以不存在:"+FileUtil.mkdirs(dir));
System.out.println("3.新建文件,并把字符内容存到文件中:"+FileUtil.createNewFile(dir+"test.txt","我是一只小小鸟"));
System.out.println("4.新建文件,必将字节内容存到文件中:"+FileUtil.createNewFile(dir+"test.txt",bytes));
System.out.println("5.新建文件:"+FileUtil.createNewFile(dir+"test1.txt"));
System.out.println("6.删除文件:"+FileUtil.delFile(dir+"test1.txt"));
String srcFile = "test1/test2/test3/test.txt";
String destFile = "test11/test22";
System.out.println("9.复制单个文件:"+FileUtil.copyFile(srcFile,destFile));
String oldFolder = "test1/test2/";
String newFolder = "test111/test222/";
System.out.println("10.复制文件夹:"+FileUtil.copyFolder(oldFolder,newFolder));
System.out.println("11.移动文件:"+FileUtil.moveFile(srcFile,destFile));
String srcDir = "test1/test2/test3";
String destDir = "test1/test2";
String path = "test1111/test.txt";
String content = "平常心,静心稳心,冷静";
System.out.println("12.写入文件:");
FileUtil.write(path,content,FileUtil.FILE_APPEND_BEFORE);
String path1 = "test11111/test.txt";
String content1 = "努力学习1,天天向上1";
FileUtil.write(path1,content1,FileUtil.FILE_APPEND_AFTER);
System.out.println("13.读取文件:"+FileUtil.readFromFile(path1));
}
}