import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class FileUtility {
public static final int BUFF_SIZE = 65535;
public static final String ROOT_PATH = "D:\\_mydaily\\TestFile\\";
public FileUtility() {
super();
// TODO Auto-generated constructor stub
}
/**
* @param args
*/
public static void main(String[] args) throws Exception {
//
/*
* FileUtility.createZipFileAsByte(new String[] { ROOT_PATH + "a.txt"
* }); FileUtility.ZipSubdirectory(new File(ROOT_PATH));
* FileUtility.createZipFile(ROOT_PATH + "a.txt");
*
* FileUtility.copyFile(new File("a.txt"),new File("b.txt"));
* FileUtility.copyDirectiory("Stat","Stat2");
*/
//FileUtility.insertStringInFile(new File("texttext.txt"),2,"0\n1\n");
FileUtility.copyFile2(new File("a.txt"),new File("b.txt"));
}
// 复制文件
public static void copyFile(File sourceFile, File targetFile)
throws IOException {
// 新建文件输入流并对它进行缓冲
FileInputStream input = new FileInputStream(sourceFile);
BufferedInputStream inBuff = new BufferedInputStream(input);
// 新建文件输出流并对它进行缓冲
FileOutputStream output = new FileOutputStream(targetFile);
BufferedOutputStream outBuff = new BufferedOutputStream(output);
// 缓冲数组
byte[] b = new byte[1024 * 5];
int len;
while ((len = inBuff.read(b)) != -1) {
outBuff.write(b, 0, len);
}
// 刷新此缓冲的输出流
outBuff.flush();
// 关闭流
inBuff.close();
outBuff.close();
output.close();
input.close();
}
// 复制文件
// 只用到了 FileInputStream ,不需要BufferedInputStream--BufferedInputStream 为添加了功能,即缓冲输入和支持 mark 和 reset 方法的能力
public static void copyFile2(File sourceFile, File targetFile)
throws IOException {
// 新建文件输入流并对它进行缓冲
FileInputStream input = new FileInputStream(sourceFile);
// 新建文件输出流并对它进行缓冲
FileOutputStream output = new FileOutputStream(targetFile);
// 缓冲数组
byte[] b = new byte[1024 * 5];
int len;
while ((len = input.read(b)) != -1) {
output.write(b, 0, len);
}
// 刷新此缓冲的输出流
output.flush();
// 关闭流
output.close();
input.close();
}
// 复制文件夹
public static void copyDirectiory(String sourceDir, String targetDir)
throws IOException {
// 新建目标目录
(new File(targetDir)).mkdirs();
// 获取源文件夹当前下的文件或目录
File[] file = (new File(sourceDir)).listFiles();
for (int i = 0; i < file.length; i++) {
if (file[i].isFile()) {
// 源文件
File sourceFile = file[i];
// 目标文件
File targetFile = new File(new File(targetDir)
.getAbsolutePath()
+ File.separator + file[i].getName());
copyFile(sourceFile, targetFile);
}
if (file[i].isDirectory()) {
// 准备复制的源文件夹
String dir1 = sourceDir + "/" + file[i].getName();
// 准备复制的目标文件夹
String dir2 = targetDir + "/" + file[i].getName();
copyDirectiory(dir1, dir2);
}
}
}
/**
* 创建目录
*
* @param folderPath:目录路径
* @return
* @throws IOException
*/
public static boolean createFolder(String folderPath) throws IOException {
boolean result = false;
File f = new File(folderPath);
result = f.mkdirs();
return result;
}
/**
* 删除目录下所有文件
*
* @param directory
* (File 对象)
*/
public static void emptyDirectory(File directory) {
File[] entries = directory.listFiles();
for (File file : entries) {
if (file.isDirectory()) {
emptyDirectory(file);
file.delete();
} else if (file.isFile()) {
file.delete();
}
}
/*
* for (int i = 0; i < entries.length; i++) { entries[i].delete(); }
*/
}
/**
* 创建文件
*
* @param filepath:文件所在目录路径,比如:c:/test/test.txt
* @return
*/
public static boolean makeFile(String filepath) throws IOException {
boolean result = false;
File file = new File(filepath);
result = file.createNewFile();
file = null;
return result;
}
/**
* 删除文件
*
* @param filepath:文件所在物理路径
* @return
*/
public static boolean isDel(String filepath) {
boolean result = false;
File file = new File(filepath);
result = file.delete();
file = null;
return result;
}
/**
* 文件重命名
*
* @param filepath:文件所在物理路径
* @param destname:新文件名
* @return
*/
public static boolean renamefile(String filepath, String destname) {
boolean result = false;
File f = new File(filepath);
String fileParent = f.getParent();
String filename = f.getName();
File rf = new File(fileParent + "//" + destname);
if (f.renameTo(rf)) {
result = true;
}
f = null;
rf = null;
return result;
}
/**
* 将文件内容写入数据库中
*
* @param filepath:文件所在物理路径
* @param content:写入内容
* @throws Exception
*/
public static void WriteFile(String filepath, String content,
boolean isAppend) throws Exception {
FileWriter filewriter = new FileWriter(filepath, isAppend);// 追加或者清空原来
PrintWriter printwriter = new PrintWriter(filewriter);
printwriter.println(content);
printwriter.flush();
printwriter.close();
filewriter.close();
}
/**
* 日志备份
*
* @param filePath:日志备份路径
* @param baksize:日志备份大小参考值(字节大小)
* @throws IOException
*/
public static void logBak(String filePath, long baksize) throws IOException {
File f = new File(filePath);
long len = f.length();
SimpleDateFormat simpledateformat = new SimpleDateFormat(
"yyyyMMddHHmmss");
String s = simpledateformat.format(new Date());
String fileName = f.getName();
int dot = fileName.indexOf(".");
String bakName = s + fileName.substring(dot);
System.out.println(bakName);
if (len >= baksize) {
renamefile(filePath, bakName);
makeFile(filePath);
}
f = null;
}
/*
* 产生的是二进制文件
*/
public static File createZipFileAsByte(String[] fileNames)
throws IOException {
OutputStream fout = null;
ZipOutputStream out = null;
FileInputStream in = null;
try {
byte[] buf = new byte[BUFF_SIZE];
fout = new FileOutputStream("zipFile");
if (fout != null) {
out = new ZipOutputStream(fout);
}
for (String file : fileNames) {
in = new FileInputStream(file);
if (in != null) {
out.putNextEntry(new ZipEntry(file));
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.closeEntry();
in.close();
in = null;
}
}
if (out != null && fout != null) {
out.close();
fout.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
throw e;
} catch (IOException e) {
e.printStackTrace();
throw e;
}
return new File("zipFile");
}
// ZipSubdirectory函数将一个指定目录(包括它子目录)压缩成一个同名压缩文件(这里称为"ORIGIN")
public static File ZipSubdirectory(File myDir) throws IOException {
boolean flag = false;
// 创建缓冲输入流BufferedInputStream
BufferedInputStream origin = null;
// 创建ZipOutputStream对象,将向它传递希望写入文件的输出流
File zipFile = new File(myDir.getName() + ".zip");
FileOutputStream fos = new FileOutputStream(zipFile);
/*
* FileOutputStream wraps ZipOutputStream
*/
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(fos,
BUFF_SIZE));
// dirContents[]获取当前目录(myDir)所有文件对象(包括子目录名)
File dirContents[] = myDir.listFiles();
// 创建临时文件tempFile,使用后删除
File tempFile = null;
try {
// 处理当前目录所有文件对象,包括子目录
for (int i = 0; i < dirContents.length; i++) {
// 使用递归方法将当前目录的子目录转成一个ZIP文件,并作为一个ENTRY加进"ORIGIN"
if (dirContents[i].isDirectory()) {
tempFile = ZipSubdirectory(dirContents[i]);
flag = true;
}
// 如果当前文件不是子目录
else {
tempFile = dirContents[i];
// flag标记tempFile是否由子目录压缩成的ZIP文件
flag = false;
}
System.out.println("Compress file: " + tempFile.getName());
FileInputStream fis = new FileInputStream(tempFile);
origin = new BufferedInputStream(fis, BUFF_SIZE);
// 为被读取的文件创建压缩条目
ZipEntry entry = new ZipEntry(tempFile.getName());
byte data[] = new byte[BUFF_SIZE];
int count;
// 在向ZIP输出流写入数据之前,必须首先使用out.putNextEntry(entry); 方法安置压缩条目对象
out.putNextEntry(entry);
// 向ZIP 文件写入数据
while ((count = origin.read(data, 0, BUFF_SIZE)) != -1) {
out.write(data, 0, count);
}
// 关闭输入流
origin.close();
// tempFile是临时生成的ZIP文件,删除它
if (flag == true) {
flag = tempFile.delete();
System.out.println("Delete file:" + tempFile.getName()
+ " " + flag);
}
}
} catch (IOException e) {
e.printStackTrace();
throw e;
}
// 递归返回
out.close();
return zipFile;
}
public static File createZipFile(String fileName)
throws FileNotFoundException, IOException {
File zipFile = null;
if (null == fileName) {
System.out.println("Flile Name is empty");
return null;
}
try {
/*
* 输出流
*/
// 创建ZipOutputStream对象,将向它传递希望写入文件的输出流
zipFile = new File("default.zip");
FileOutputStream fos = new FileOutputStream(zipFile);
/*
* FileOutputStream wraps ZipOutputStream
*/
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
fos, BUFF_SIZE));
/*
* 输入流
*/
// 创建缓冲输入流BufferedInputStream
File fileIn = new File(fileName);
if (fileIn.isDirectory()) {
System.out.println("It is directory ,not File");
return null;
}
FileInputStream fis = new FileInputStream(fileIn);
BufferedInputStream bis = new BufferedInputStream(fis, BUFF_SIZE);
ZipEntry entry = new ZipEntry(fileIn.getName());
byte data[] = new byte[BUFF_SIZE];
int count;
// 在向ZIP输出流写入数据之前,必须首先使用out.putNextEntry(entry); 方法安置压缩条目对象
out.putNextEntry(entry);
// 向ZIP 文件写入数据
while ((count = bis.read(data, 0, BUFF_SIZE)) != -1) {
out.write(data, 0, count);
}
if (out != null) {
out.close();
}
if (bis != null) {
bis.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
throw e;
} catch (IOException e) {
e.printStackTrace();
throw e;
}
return zipFile;
}
public static void appendRandom(String file, String context)
throws Exception {
RandomAccessFile raf = new RandomAccessFile(new File(file), "rwd");
raf.seek(0);// 将写文件指针移至文件末尾
raf.writeBytes(context);
raf.close();
}
/**
* 在文件里面的指定行插入一行数据
*
* @param inFile
* 文件
* @param lineno
* 行号
* @param lineToBeInserted
* 要插入的数据
* @throws Exception
* IO操作引发的异常
*/
public static void insertStringInFile(File inFile, int lineno,
String lineToBeInserted) throws Exception {
// 临时文件
File outFile = File.createTempFile("name", ".tmp");
// 输入
FileInputStream fis = new FileInputStream(inFile);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
// 输出
FileOutputStream fos = new FileOutputStream(outFile);
PrintWriter out = new PrintWriter(fos);
// 保存一行数据
String thisLine;
// 行号从1开始
int i = 1;
while ((thisLine = in.readLine()) != null) {
// 如果行号等于目标行,则输出要插入的数据
if (i == lineno) {
out.println(lineToBeInserted);
}
// 输出读取到的数据
out.println(thisLine);
// 行号增加
i++;
}
out.flush();
out.close();
in.close();
// 删除原始文件
inFile.delete();
// 把临时文件改名为原文件名
outFile.renameTo(inFile);
}
}