package XXX.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* 文件操作
* @author Administrator
*
*/
public class FileUtil {
//static String log_path = "E:\\\\workspace\\\\eclipse\\\\Checked.txt";
static String log_path = System.getProperty("user.dir")+"/Checked.txt";
public static void appendLog(String msg) {
try {
File file = new File(log_path);
if (!file.exists()) {
file.createNewFile();
}
//创建文件输入流
FileOutputStream out =new FileOutputStream(file,true); //如果追加方式用true
//写入内容
StringBuffer sb=new StringBuffer();
sb.append("\n");
sb.append(msg);
out.write(sb.toString().getBytes("utf-8"));//注意需要转换对应的字符集
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void updateFile(String path, String msg) {
try {
File file = new File(path);
if (!file.exists()) {
String error_msg = "updateFile失败:";
error_msg += "path:"+path+"\n";
FileUtil.appendLog(error_msg);
}
//创建文件输入流
FileOutputStream out =new FileOutputStream(file); //更改文件内容
//写入内容
StringBuffer sb=new StringBuffer();
sb.append(msg);
out.write(sb.toString().getBytes("utf-8"));//注意需要转换对应的字符集
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 获取匹配的文件名集合
* @param path
* @param inputDay
* @return
*/
public static List<String> findFileList(String path,String inputDay){
String fName = path;
File pathFile =new File(fName.trim());
File[] fileNum = pathFile.listFiles();
ArrayList<String> findList = new ArrayList<>();
for (File file : fileNum) {
String fileName = file.getName();
String tempFileName = "";
if(fileName.length()>26) {
tempFileName = fileName.substring(19, 27);
}
if(inputDay.equals(tempFileName)) {
findList.add(fileName);
}
}
return findList;
}
/**
* 读取文件内容
* @param fileName
* @return
*/
public static String readToString(String fileName) {
try {
BufferedReader in = new BufferedReader(new FileReader(fileName));
String str = "", data = "";
while ((str = in.readLine()) != null) {
data += str;
}
in.close();
return data;
} catch (IOException e) {
e.getStackTrace();
return null;
}
}
/**
* 查找文件路径下所有的文件个数
* @param path
* @return
*/
public static Integer findAllFileListSize(String path){
String fName = path;
File pathFile =new File(fName.trim());
File[] fileNum = pathFile.listFiles();
ArrayList<String> findList = new ArrayList<>();
for (File file : fileNum) {
String fileName = file.getName();
findList.add(fileName);
}
return findList.size();
}
/**
* 创建文件
* @param filePath
*/
public static void createFile(String filePath) {
File file =new File(filePath.trim());
try {
//如果文件不存在,创建文件
if(!file.exists()) {
file.createNewFile();
System.out.println("创建文件:"+filePath);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}