Java 写数据到文件

 

private boolean writeToFile(BusGpsBean gpsBean) {

String dataStr = DateUtil.date2String(new Date(), DateUtil.YMD);
String filePath = PathKit.getWebRootPath() + File.separatorChar + "writeFile" + File.separatorChar + dataStr + ".txt"; // 文件保存绝对路径
logger.debug("dataStr, {}", dataStr);
logger.debug("filePath, {}", filePath);

File file = null;
FileWriter fw = null;
file = new File(filePath);
try {
if (!file.exists()) {
//file.getParentFile().mkdirs();
file.createNewFile();
}
fw = new FileWriter(file, true); // true表示追加
fw.write(gpsBean.toString());//向文件中写内容
fw.write("\r\n");//换行
fw.flush();
logger.debug("写数据到文件成功, {}", gpsBean.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}finally{
if(fw != null){
try {
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

return true;
}

posted @ 2018-08-17 16:52  panchanggui  阅读(3335)  评论(0编辑  收藏  举报