java 一行行读取写入txt文档

来源:互联网 发布:知乎 不知道 编辑:程序博客网 时间:2024/05/18 02:13
package com.ynu.www.tool;
import java.io.*;
import java.util.*;

//流的关闭顺序:先打开的后关,后打开的先关,否则有可能出现java.io.IOException: Stream closed异常
//读取txt文档中的内容,写入数据库。
public class Txt2Database {
private final static String PATH = System.getProperty("user.dir");
public final static String DIR = PATH + "/src/com/ynu/www/data/";


public List<List> readeTxt(String filename) {
// 用于存放txt文件里所有的数据
List txtList = new ArrayList<List>();
try {
// 用来记录读到第几行记录
int id = 0;
FileReader fr = new FileReader(DIR + filename);
BufferedReader bf = new BufferedReader(fr);
String str = null;
while ((str = bf.readLine()) != null) {
// 用于存放txt文件里每行数据
List tempList = new ArrayList<Integer>();
id++;
String[] strs = str.split(" ");
if (strs[0] != null && !strs[0].equals("") && strs[1] != null
&& !strs[1].equals("")) {
tempList.add(Integer.parseInt(strs[0]));
tempList.add(Integer.parseInt(strs[1]));
} else {
System.out.println("读取第" + id + "行txt文档内容时,发现不合要求的数据!");
}
txtList.add(tempList);
}
} catch (Exception e) {
System.out.println("读取txt文档内容时,发生异常!");
e.printStackTrace();
}
return txtList;
}


// 选择合适数量的文本文档数据,写入txt。
public void writerTxt(List<List> txtList) {
try {
FileOutputStream fos = new FileOutputStream("E:/test.txt");
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");//一行一行读取文件,解决读取中文字符时出现乱码
BufferedWriter bw = new BufferedWriter(osw);
for (int i = 0; i < txtList.size(); i++) {
List tempList = new ArrayList<Integer>();
tempList = txtList.get(i);
int tempValue0 = (Integer) tempList.get(0);
int tempValue1 = (Integer) tempList.get(1);
if (tempValue0 < 5000 && tempValue1 < 5000) {
bw.write(tempValue0 + " " + tempValue1 + "\r\n");
}

}
// 注意关闭的先后顺序,先打开的后关闭,后打开的先关闭
bw.close();
osw.close();
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


// 打印list数据
public void printList(List<List> txtList) {
// 用于存放txt文件里每行数据
List tempList = new ArrayList<String>();
for (int i = 0; i < txtList.size(); i++) {
tempList = txtList.get(i);
System.out.print(tempList.get(0) + " " + tempList.get(1));
System.out.println();
}
System.out.println("打印完毕");
}


}
0 0
原创粉丝点击