一、 工作中讀寫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();
}
}
}