package sunline.common.logic.Utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.log4j.Logger;
import com.sunline.flow.base.annotation.Bizlet;
/**
*
* @author niucc
* Created 2017/04/20
*
*/
public class FileUtils {
private static Logger log = Logger.getLogger(FileUtils.class.getName());
@Bizlet("以字节方式获取文件内容")
public static String getFileContent(String filePath)
throws FileNotFoundException {
File file = null;
InputStream in = null;
byte[] tempbytes = null;
String s = "";
try {
tempbytes = new byte[1024 * 10];
file = new File(filePath);
int byteread = 0;
in = new FileInputStream(file);
// 读入多个字节到字节数组中,byteread为一次读入的字节数
while ((byteread = in.read(tempbytes)) != -1) {
// System.out.write(tempbytes, 0, byteread);
}
s = new String(tempbytes, "UTF-8");
} catch (Exception e1) {
e1.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e1) {
}
}
}
return s;
}
@Bizlet("提取文件字段放入list")
public static List<List<String>> getField(String filePath, int num) {
String str = "";
// 存放截取到的字段list
List<List<String>> fields = new ArrayList<List<String>>();
try {
// 得到文件内容
str = getFileContent(filePath);
// 去除空格,回车,换行符,制表符
str = replaceBlank(str);
//以“^|^”分割字符串,要用\\转义
String[] split = str.split("\\^\\|\\^");
// 总共多少个字段
int length = split.length - 1;
for (int j = 0; j < num; j++) {
List<String> list = new ArrayList<String>();
int start = 0;
int end = 0;
if (j == 0) {
start = 0;
end = 4;
} else {
start = j * 4;
end = (j + 1) * 4;
}
for (int i = start; i < end; i++) {
list.add(split[i]);
}
log.info("====文件内容 " + list);
fields.add(list);
}
} catch (Exception e) {
new Exception("提取文件内容出错");
}
return fields;
}
// 去除空格,回车,换行符,制表符
public static String replaceBlank(String str) {
String dest = "";
if (str != null) {
Pattern p = Pattern.compile("\\s*|\t|\r|\n");
Matcher m = p.matcher(str);
dest = m.replaceAll("");
}
return dest;
}
/*public static void main(String[] args) {
String path = "C:/Users/Administrator/Desktop/sunline/二代支付/a.txt";
List<List<String>> field = getField(path, 2);
System.out.println(field);
}*/
}