文件操作的问题

ahuu 2004-11-22 12:13:03
public class ErrLog {
public static void log(String logInfo){
String fileName = ("log.txt");
try{
FileWriter fw = new FileWriter(fileName);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter outFile = new PrintWriter(bw);
outFile.print(logInfo);
outFile.print(" ");
outFile.println(new java.util.Date());
outFile.close();
}
catch (IOException e) {
System.err.println(e);
}
}
}
这段代码的问题是:每当向log文件写入信息的时候,总是要创建一个新的log.txt文件,并把原来的文件覆盖了,能不能先判断该文件是否存在,如果不存在,则创建新的,否则直接向已存在的文件(log.txt)追加新的信息,并且不覆盖原来的信息;
还有一问:在java中如何取得系统的当前时间,格式为yyyy-mm-dd hh:mm:ss,多谢了!!
...全文
123 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
wuyuestar 2004-11-22
  • 打赏
  • 举报
回复
public void csvFileOpen(String fileName) throws IOException {
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(fileName)));

String s = "sssss";
pw.println(s);

pw.flush();
pw.close();
}
wuyuestar 2004-11-22
  • 打赏
  • 举报
回复
public static String getSysDate() {
String dateTime = "";
Date sysDate = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
StringBuffer tb = new StringBuffer();
dateTime = sdf.format(sysDate, tb, new FieldPosition(0)).toString();
return dateTime;
}
funcreal 2004-11-22
  • 打赏
  • 举报
回复
另外,要记得flush和close
funcreal 2004-11-22
  • 打赏
  • 举报
回复
try{
PrintWriter out = new PrintWriter(new FileWriter(new File("a.txt"), true));//这样就可以了。注意那个true就决定了是创建新的还是append到旧文件里面。

}catch(IOException e){
e.printStackTrace();
}
funcreal 2004-11-22
  • 打赏
  • 举报
回复

GregorianCalendar calendar = new GregorianCalendar();
String sdt = calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1) + "-" + calendar.get(Calendar.DATE);
这个是得到类似于yyyy-mm-dd的时间格式,相信你能看出如何写出你要的格式了。

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧