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;
}