常用工具類(一):FileUtile 檔案相關操作
阿新 • • 發佈:2018-12-07
常用工具類(一):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/");
}
}