package com.lx.product.seal.utils;
|
|
import java.io.BufferedInputStream;
|
import java.io.BufferedOutputStream;
|
import java.io.BufferedReader;
|
import java.io.BufferedWriter;
|
import java.io.File;
|
import java.io.FileInputStream;
|
import java.io.FileOutputStream;
|
import java.io.InputStreamReader;
|
import java.io.OutputStreamWriter;
|
import java.util.Map;
|
|
import com.lx.product.seal.log.Logger;
|
|
public class FileUtil {
|
private static final String row = "\n";
|
public static Logger log = Logger.getInstance();
|
|
/**
|
* 复制文件
|
* @param sourceFile
|
* @param targetFile
|
*/
|
public static void copyFile(File sourceFile, File targetFile) {
|
|
BufferedInputStream inBuff = null;
|
BufferedOutputStream outBuff = null;
|
try {
|
if (!targetFile.getParentFile().exists()) {
|
targetFile.getParentFile().mkdirs();
|
}
|
// 新建文件输入流并对它进行缓冲
|
inBuff = new BufferedInputStream(new FileInputStream(sourceFile));
|
// 新建文件输出流并对它进行缓冲
|
outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));
|
// 缓冲数组
|
byte[] b = new byte[1024 * 5];
|
int len;
|
while ((len = inBuff.read(b)) != -1) {
|
outBuff.write(b, 0, len);
|
}
|
// 刷新此缓冲的输出流
|
outBuff.flush();
|
} catch (Exception e) {
|
log.writeInfo(e.getMessage(), Logger.ERROR_TYPE);
|
} finally {
|
// 关闭流
|
if (inBuff != null) {
|
try {
|
inBuff.close();
|
} catch (Exception ee) {
|
log.writeInfo(ee.getMessage(), Logger.ERROR_TYPE);
|
}
|
}
|
if (outBuff != null) {
|
try {
|
outBuff.close();
|
} catch (Exception ee) {
|
log.writeInfo(ee.getMessage(), Logger.ERROR_TYPE);
|
}
|
}
|
}
|
}
|
|
/**
|
* 修改文件
|
* @param sourceFile
|
* @param targetFile
|
*/
|
public static void modifyFile(File sourceFile, File targetFile, Map<String, String> items, String readEncode, String writeEncode) {
|
BufferedWriter bw = null;
|
try (InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(sourceFile), readEncode);
|
BufferedReader br = new BufferedReader(inputStreamReader);) {
|
StringBuilder content = new StringBuilder(512);
|
String line = null;
|
while ((line = br.readLine()) != null) {
|
if (line.startsWith("pause")) {
|
continue;
|
}
|
for (Map.Entry<String, String> entry : items.entrySet()) {
|
if (line.trim().startsWith(entry.getKey())) {
|
line = entry.getValue();
|
}
|
}
|
content.append(line).append("\r\n");
|
}
|
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(targetFile), writeEncode));
|
bw.write(content.toString());
|
// 刷新此缓冲的输出流
|
bw.flush();
|
} catch (Exception e) {
|
e.printStackTrace();
|
} finally {
|
if (bw != null) {
|
try {
|
bw.close();
|
} catch (Exception ee) {
|
ee.printStackTrace();
|
}
|
}
|
}
|
}
|
|
public static void modifyFile(File sourceFile, File targetFile, Map<String, String> items, String encode) {
|
modifyFile(sourceFile, targetFile, items, encode, encode);
|
}
|
|
public static void modifyFile(File sourceFile, File targetFile, Map<String, String> items) {
|
modifyFile(sourceFile, targetFile, items, "utf-8");
|
}
|
}
|