package com.idbp.common.utils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.GZIPInputStream;
import org.apache.commons.lang.StringUtils;
import com.dap.config.ParamsContainer;
import com.dap.exception.BusinessException;
public class FileUtil {
private final static String CHAR_SET = "UTF-8";
private final static int NEW_LINE_CHAR_BYTE = System.getProperty("line.separator").getBytes().length;
private final static String TEMPATH = ParamsContainer.getString("icon.fileTranPath");
/**
*
* @param fileName
* 文件路径+文件名
* @param content
* 文件内容
* @throws Exception
*/
public static void write(String fileName, String content) throws Exception {
write(fileName, content, false);
}
/**
* 追写文件
*
* @param fileName
* @param content
* @param append
* @throws Exception
*/
public static void write(String fileName, String content, boolean append) throws Exception {
File file = new File(fileName);
File fileParent = file.getParentFile();
if (!fileParent.exists()) {
boolean exist = fileParent.mkdirs();
if (!exist) {
throw new Exception("生成文件路径" + fileParent.getAbsolutePath() + "失败!");
}
}
BufferedWriter bw =
new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, append), CHAR_SET));
try {
bw.write(content);
} finally {
bw.close();
}
}
/**
* 读取文件将每行放到List里 , 只允许读取小文件时使用此方法
*
* @param fileName
* @return
* @throws Exception
*/
public static List<String> readFileToList(String fileName) throws Exception {
List<String> list = new ArrayList<String>();
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
String buf = null;
try {
while ((buf = br.readLine()) != null) {
list.add(buf);
}
} finally {
br.close();
}
return list;
}
/**
* 获取文件的总行数,文件需要每一行均含有固定长度
*
* @param fileName
* @param lineByteSize
* 单行的固定字节数 ,小于1表示无固定长度
* @return
* @throws Exception
*/
public static long getFileRowCount(String fileName, long lineByteSize) throws Exception {
long rowCount = 0;
if (lineByteSize > 0) {
long len = new File(fileName).length();
rowCount = (len + NEW_LINE_CHAR_BYTE) / (lineByteSize + NEW_LINE_CHAR_BYTE);// 加上换行符字节数
} else {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
try {
while (br.readLine() != null) {
rowCount++;
}
} finally {
br.close();
}
}
return rowCount;
}
/**
* 读取每行无固定长度的文件,将每行放到一个List返回,List最后一个元素为已读取的内容字节数值(skipByte+这次读取的字节数)
*
* @param fileName
* 文件名
* @param skipByte
* 跳过的字节数
* @param maxLine
* 最大行数
* @return
* @throws Exception
*/
public static List<String> readFileToList(String fileName, long skipByte, long maxLine) throws Exception {
List<String> list = new ArrayList<String>();
BufferedReader br =
new BufferedReader(new InputStreamReader(new FileInputStream(fileName), CHAR_SET));
String buf = null;
long lineNum = 0;
long byteSize = skipByte;
try {
br.skip(skipByte);
while ((buf = br.readLine()) != null && ++lineNum <= maxLine) {
list.add(buf);
byteSize += buf.getBytes().length;
byteSize += NEW_LINE_CHAR_BYTE;// 换行符占两个字节
}
} finally {
br.close();
}
list.add(String.valueOf(byteSize));
return list;
}
/**
* 读取固定行长度的文件,每行记录存放到List中返回
*
* @param fileName
* 文件名
* @param startLineIndex
* 起始行,从0开始
* @param lineByteSize
* 每行固定的字节数
* @param maxLine
* 读取的最大行数
* @return
* @throws Exception
*/
public static List<String> readFileToList(String fileName, long startLineIndex, long lineByteSize,
long maxLine) throws Exception {
List<String> list = new ArrayList<String>();
BufferedReader br =
new BufferedReader(new InputStreamReader(new FileInputStream(fileName), CHAR_SET));
String buf = null;
long lineNum = 0;
try {
br.skip(startLineIndex * (lineByteSize + NEW_LINE_CHAR_BYTE));
while ((buf = br.readLine()) != null && ++lineNum <= maxLine) {
list.add(buf);
}
} finally {
br.close();
}
return list;
}
/**
* 新建目录
*
* @param folderPath
* String 如 c:/fqf
* @return boolean
*/
public static void newFolder(String folderPath) {
String filePath = folderPath;
filePath = filePath.toString();
java.io.File myFilePath = new java.io.File(filePath);
if (!myFilePath.exists()) {
myFilePath.mkdirs();
}
}
/***
* 解析txt文件
*
* @param filePath
* String eg:"d:/1.txt"
* @return String[]
*/
public static String[] readFile(String filePath) {
File file = new File(filePath);
String line = null;
List list = new ArrayList();
String[] array = null;
try {
if (file.isFile() && file.exists()) {
BufferedReader br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
list.add(line);
}
array = new String[list.size()];
for (int i = 0; i < list.size(); i++) {
String a = (String) list.get(i);
array[i] = a;
}
br.close();
} else {
throw new BusinessException("BBPF0016");// 找不到解析文件
}
} catch (IOException e) {
e.printStackTrace();
}
return array;
}
/***
* 解析txt文件格式为GBK
*
* @param filePath
* String eg:"d:/1.txt"
* @return String[]
*/
public static String[] readFileForGBK(String filePath) {
File file = new File(filePath);
String line = null;
List list = new ArrayList();
String[] array = null;
try {
if (file.isFile() && file.exists()) {
BufferedReader br =
new BufferedReader(new InputStreamReader(new FileInputStream(file), "GBK"));
while ((line = br.readLine()) != null) {
list.add(line);
}
array = new String[list.size()];
for (int i = 0; i < list.size(); i++) {
String a = (String) list.get(i);
array[i] = a;
}
br.close();
} else {
throw new BusinessException("BBPF0016");// 找不到解析文件
}
} catch (IOException e) {
e.printStackTrace();
}
return array;
}
/**
* 判断文件是否存在
*
* @param path
* @return
*/
public static boolean isExists(String path) {
boolean flag = false;
if (!StringUtils.isEmpty(path)) {
File f = new File(path);
flag = f.exists();
}
return flag;
}
/**
* 新建目录.
*
* @param path
* 文件路径
* @throws Exception
*/
public static void createDirectory(String path) {
if (StringUtils.isEmpty(path)) {
return;
}
try {
// 获得文件对象
File f = new File(path);
if (!f.exists()) {
// 如果路径不存在,则创建
f.mkdirs();
}
} catch (Exception e) {
throw new BusinessException("BBPF0016");// 找不到解析文件
}
}
/**
* 获取文件后缀名
*
* @param str
* @return
*/
public static String getSuffix(String str) {
String suffix = "";
if (str != null && !("").equals(str)) {
if (str.lastIndexOf(".") != -1) {
suffix = str.substring(str.lastIndexOf(".") + 1);
}
}
return suffix;
}
/**
* 文件删除
*
* @param filePath
* @return
*/
public static boolean deleteFile(String filePath) {// 删除单个文件
boolean flag = false;
File file = new File(filePath);
if (file.isFile() && file.exists()) {// 路径为文件且不为空则进行删除
file.delete();// 文件删除
flag = true;
}
return flag;
}
/**
* URL文件下载
*
* @param urlString
* 下载URL路径
* @param filename
* 文件名
*/
public static String download(String urlString, String filename) {
String filePath = null;
URL url = null;
InputStream is = null;
OutputStream os = null;
try {
url = new URL(urlString);
} catch (MalformedURLException e) {
throw new BusinessException("BBPF0025", "下载文件");
}
try {
URLConnection con = url.openConnection();
FileUtil.createDirectory(TEMPATH); // 创建目录文件夹
is = con.getInputStream();
byte[] bs = new byte[1024];
int len;
os = new FileOutputStream(TEMPATH + filename);
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);
}
filePath = TEMPATH + filename;
} catch (IOException e) {
throw new BusinessException("BBPF0025", "下载文件");
} finally {
try {
os.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return filePath;
}
/**
* 文件解压
*
* @param sourcedir
* 解压文件路径
*/
public static void unGzipFile(String sourcedir) {
String ouputfile = "";
try {
FileInputStream fin = new FileInputStream(sourcedir); // 建立文件输入流
GZIPInputStream gzin = new GZIPInputStream(fin); // 建立gzip解压工作流
ouputfile = sourcedir.substring(0, sourcedir.lastIndexOf('.'));
FileOutputStream fout = new FileOutputStream(ouputfile);
int num;
byte[] buf = new byte[1024];
while ((num = gzin.read(buf, 0, buf.length)) != -1) {
fout.write(buf, 0, num);
}
gzin.close();
fout.close();
fin.close();
} catch (Exception ex) {
System.err.println(ex.toString());
}
return;
}
/**
* 文件追加写入
*
* @param fileContent
* @throws Exception
* @throws IOException
*/
public static void writeFile(String fileContent, String file, int i) throws Exception {
FileOutputStream writerStream = null;
BufferedWriter writer = null;
try {
writerStream = new FileOutputStream(file, true);
writer = new BufferedWriter(new OutputStreamWriter(writerStream, CHAR_SET));
if (i == 0) {
writer.write(fileContent + "\n");
} else {
writer.write(fileContent);
}
} finally {
try {
writer.close();
writerStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}