写文件:
bw = new BufferedWriter(new FileWriter(localPath, false));
false:重新写入文件
true:在原文件之后增加内容。
bw.newLine(); 换行
bw.flush();BufferedWriter是缓冲输入流,意思是调用BufferedWriter的write方法时候。数据是先写入到缓冲区里,并没有直接写入到目的文件里。必须调用BufferedWriter的flush()方法。这个方法会刷新一下该缓冲流,也就是会把数据写入到目的文件里。或者你可以调用BufferedWriter的close()方法,该方法会在关闭该输入流之前先刷新一下该缓冲流。也会把数据写入到目的文件里。
/**
* 生成输入数据文件
*
* @param list 数据
* @param fileName 文件名
*/
public void writeList(List<String[]> list, String fileName) throws IOException {
BufferedWriter bw = null;
String strLineData = "";
String localPath = Constant.getServiceFilesPath() + "/test/" + fileName + ".txt";
bw = new BufferedWriter(new FileWriter(localPath, false));
if (list != null && list.size() > 0) {
for (int i = 0; i < list.size(); i++) {
String[] str = list.get(i);
for (int j = 0; j < str.length; j++) {
strLineData = strLineData + str[j] + " ";
}
bw.write(strLineData);
bw.newLine();
bw.flush();
strLineData = "";
}
}
}
读文件:
/**
* 解析文件,数据入库
*
* @param 日期
* @return true:成功,false:失败
*/
public boolean saveUnitCpower(String date) {
FileInputStream fr = null;
BufferedReader br = null;
String[] str = null;
List<String[]> list = new ArrayList();
try {
String fileName = "TEST.txt";
String localPath = Constant.getServiceFilesPath() + "/test/";
fr = new FileInputStream(localPath + fileName);
InputStreamReader is = new InputStreamReader(fr, "UTF8");
br = new BufferedReader(is);
String line = br.readLine();
while (line != null) {
line = br.readLine();
str = line.split(" ");
list.add(new String[]{str[0], str[1], str[2], str[3]});
}
} catch (IOException e) {
return false;
} finally {
try {
if (br != null) {
br.close();
}
if (br != null) {
fr.close();
}
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
return mapper.save(date, list);
}
}