天天看點

java把資料寫入檔案_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;

}