commons io文件操作示例分享
package com.pzq.io;
import java.io.bufferedreader;
import java.io.bufferedwriter;
import java.io.file;
import java.io.filewriter;
import java.io.ioexception;
import java.io.stringreader;
import java.nio.charset.charset;
import java.util.arraylist;
import java.util.list;
import org.apache.commons.io.fileutils;
/**
* 文件操作工具类
* @version 1.0 2013/07/16
*
*/
public class fileutil {
/**
* 复制文件或者目录,复制前后文件完全一样。
* @param resfilepath 源文件路径
* @param distfolder 目标文件夹
* @ioexception 当操作发生异常时抛出
*/
public static void copyfile(string resfilepath, string distfolder)
throws ioexception {
file resfile = new file(resfilepath);
file distfile = new file(distfolder);
if (resfile.isdirectory()) { // 目录时
fileutils.copydirectorytodirectory(resfile, distfile);
} else if (resfile.isfile()) { // 文件时
// fileutils.copyfiletodirectory(resfile, distfile, true);
fileutils.copyfiletodirectory(resfile, distfile);
}
}
/**
* 删除一个文件或者目录
* @param targetpath 文件或者目录路径
* @ioexception 当操作发生异常时抛出
*/
public static void deletefile(string targetpath) throws ioexception {
file targetfile = new file(targetpath);
if (targetfile.isdirectory()) {
fileutils.deletedirectory(targetfile);
} else if (targetfile.isfile()) {
targetfile.delete();
}
}
/**
* 将字符串写入指定文件(当指定的父路径中文件夹不存在时,会最大限度去创建,以保证保存成功!)
*
* @param res 原字符串
* @param filepath 文件路径
* @return 成功标记
* @throws ioexception
*/
public static boolean string2file(string res, string filepath) throws ioexception {
boolean flag = true;
bufferedreader bufferedreader = null;
bufferedwriter bufferedwriter = null;
try {
file distfile = new file(filepath);
if (!distfile.getparentfile().exists()) {// 不存在时创建
distfile.getparentfile().mkdirs();
}
bufferedreader = new bufferedreader(new stringreader(res));
bufferedwriter = new bufferedwriter(new filewriter(distfile));
char buf[] = new char[1024]; // 字符缓冲区
int len;
while ((len = bufferedreader.read(buf)) != -1) {
bufferedwriter.write(buf, 0, len);
}
bufferedwriter.flush();
bufferedreader.close();
bufferedwriter.close();
} catch (ioexception e) {
flag = false;
throw e;
}
return flag;
}
/**
* 取得指定文件内容
*
* @param res 原字符串
* @param filepath 文件路径
* @return 成功标记
* @throws ioexception
*/
public static list<string> getcontentfromfile(string filepath) throws ioexception {
list<string> lists = null;
try {
if(!(new file(filepath).exists())){
return new arraylist<string>();
}
lists = fileutils.readlines(new file(filepath), charset.defaultcharset());
} catch (ioexception e) {
throw e;
}
return lists;
}
/**
* 给指定文件追加内容
* @param filepath
* @param contents
*/
public static void addcontent(string filepath, list<string> contents) throws ioexception {
try {
fileutils.writelines(new file(filepath), contents);
} catch (ioexception e) {
throw e;
}
}
}