一、 工作中读写txt文件是一种很常用的方式,比如日志记录,当然需要有对应的解析脚本解析,然后得出我们需要的数据。本文只是简单地对文件读入和输出
1、文件读入,先判断文件是否存在,不存在则退出。然后对流进行封装,用一个BufferedReader读,每次一行,然后进行相应的处理。
/**
* 读txt
* @param path 文件路径
* @return
*/
public static Set<String> readTxt(String path) {
BufferedReader br = null;
Set<String> set = null;
try {
File file = new File(path);
//判断文件是否存在
if (file.exists()) {
} else {
System.out.println(path + "文件不存在!");
return null;
}
//中文的时候要注意文件的编码
InputStreamReader reader = new InputStreamReader(new FileInputStream(file), "utf-8");
br = new BufferedReader(reader, 1024 * 1024);
String line = "";
set = new HashSet<String>();
while ((line = br.readLine()) != null) {
// 对每行进行处理,此处只是简单的打印
// System.out.println(line);
set.add(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return set;
}
2、写文件,把处理好的数据存入容器,然后指定路径输出
/**
* 写txt文件
* @param col需要写入文件的数据
* @param path写入文件路径
*/
public static void writeTxt(Collection<String> col, String path) {
try {
File f = new File(path);
if (!f.exists()) {
//文件不存在则建立一个
f.createNewFile();
}
} catch (Exception e) {
e.printStackTrace();
}
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter(path));
if (col.size() != 0) {
Iterator<String> iter = col.iterator();
while (iter.hasNext()) {
String pid = (String) iter.next();
bw.write(pid + "\r\n");
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
bw.flush();
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}