常用工具类(一):FileUtile 文件相关操作
public class FileUtil {
private static final Logger logger = LoggerFactory.getLogger(FileUtils.class);
//读取文件
public static String readFile(String fileName){
InputStreamReader streamReader = null;
InputStream inputStream = FileUtil.class.getResourceAsStream("/" + fileName);
StringBuilder sb = new StringBuilder();
try {
if (inputStream == null) {
logger.error("InputStream为null,fileName为"+fileName);
throw new IOException();
}
streamReader = new InputStreamReader(inputStream,"utf-8");
int len = 0;
char[] chars = new char[1024 * 10];
while((len = streamReader.read(chars))!= -1) {
sb.append(chars,0,len);
}
} catch (IOException e) {
logger.info("读取文件错误",e);
throw new RuntimeException();
} finally {
try {
if (inputStream != null){
inputStream.close();
}
if (streamReader != null){
streamReader.close();
}
} catch (IOException e) {
logger.error("资源关闭时出错",e);
}
}
return sb.toString();
}
//创建目录
public static void mkdir(String path){
File file = new File(path);
if (!file.exists()) {
//mkdir只能建立一级的文件夹,mkdirs可以建立多级文件夹
if (file.mkdirs()){
logger.info("目录 "+path+" 创建成功");
} else {
logger.error("目录 "+path+" 创建失败");
}
}
}
//删除目录
public static void delDir(String path) {
File file = new File(path);
if (file.exists()) {
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File f : files) {
f.delete();
}
} else {
file.delete();
}
logger.info(path+" 删除成功");
} else {
logger.error(path+" 路径不存在");
}
}
//拷贝文件
public static void copyFile(String fromPath, String toPath){
File fromFile = new File(fromPath);
File[] files = fromFile.listFiles();
File toFile = new File(toPath);
if (!toFile.exists()){
toFile.mkdirs();
}
for (File f : files) {
if (f.isFile()){
copy(f.getPath(), toPath+"/"+f.getName());
} else {
copyFile(f.getPath(),toPath+"/"+f.getName());
}
}
}
public static void copy(String fromPath, String toPath){
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(fromPath),"GBK"));
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(toPath),"GBK"));
String s = null;
while ((s = br.readLine()) != null) {
bw.write(s);
bw.newLine();
bw.flush();
}
} catch (FileNotFoundException e) {
logger.error("文件没有找到",e);
} catch (IOException e) {
logger.error("读取文件异常",e);
} finally {
try {
if (br != null) {
br.close();
}
if (bw != null) {
bw.close();
}
} catch (IOException e) {
logger.info("资源关闭时出错",e);
}
}
}
public static void main(String args[]){
//update目录位置,如下如所示
String fromPath = FileUtil.class.getClassLoader().getResource("update").getFile();
FileUtil.copyFile(fromPath,"C:/test/");
}
}