有时候需要对一些数据进行批量分析和操作(比如数据库查询出来的字段信息) ,这时我们可以将其放在txt或者excel文件中,然后对txt进行读取并处理逻辑。txt文件内容按如下显示:
oid sid
1 2
1 3
下面给出操作txt文件的工具代码:
public class ReadTxtUtils {
private File filename ;
private InputStreamReader reader;
private BufferedReader br ;
public ReadTxtUtils(String filepath) {
try {
File file = new File(filepath);
reader = new InputStreamReader(new FileInputStream(file), "gbk");
br = new BufferedReader(reader);
} catch (Exception e) {
}
}
public void readTxtContent() throws Exception{
long starttime=System.currentTimeMillis();
String line = "";
line = br.readLine();
int i = 0;
int errorCount=0;
while (line != null) {
if(i > 0 && !StringUtils.isEmpty(line)){
line = br.readLine(); //第一行数据
String[] lines = null;//
if(line!=null){
lines=line.split(" ");
}else{
continue;
}
try {
String oid = lines[0].trim();
String sid =lines[1].trim();
String url="http://testapi.crius.cn/test_web/updateUserId";
//请求参数
HashMap<String, Object> requestMap = new HashMap<String, Object>();
requestMap.put("oid ",oid );
requestMap.put("sid",sid);
HttpUtil.doPost(url,requestMap,null);//这里是http请求调用其他服务处理数据
} catch (Exception e) {
errorCount++;
System.out.println("oid==="+lines[0].trim());
}
}
i = i + 1;
}
System.out.println("错误数据记录数"+errorCount);
long endtime=System.currentTimeMillis();
System.out.println("总用时(min):"+(endtime-starttime)/1000/60);
System.out.println("总张数(min):"+i);
}
public static boolean createDir(String destDirName) {
File dir = new File(destDirName);
if (dir.exists()) {
// System.out.println("创建目录" + destDirName + "失败,目标目录已经存在");
return false;
}
if (!destDirName.endsWith(File.separator)) {
destDirName = destDirName + File.separator;
}
//创建目录
if (dir.mkdirs()) {
System.out.println("创建目录" + destDirName + " 成功!");
return true;
} else {
System.out.println("创建目录" + destDirName + "失败!");
return false;
}
}
public static void main(String[] args) {
try {
String filepath = "C:/Users/crius/Desktop/1.txt";
ReadTxtUtils excelReader = new ReadTxtUtils(filepath);
excelReader.readTxtContent();
}catch (Exception e) {
System.out.println("未找到指定路径的文件!");
e.printStackTrace();
}
}
}