java如何把输出写到文件中?

import java.io.*;
import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.*;

public class TestLiftCycleServlet extends HttpServlet {

@Override
public void destroy() {
System.out.println("destroy");

}

@Override
public void init(ServletConfig config) throws ServletException {
System.out.println("init");
}

public TestLiftCycleServlet() {
System.out.println("constructor!");

}

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("doGet");

}

}
就是把system.out.println()的内容输出到文件里去,我想用java的方法实现,不是想记录日志,能不能写具体一点,File file =null;
PrintWriter pw = null;
try{
file = new File("c:\\6.txt");
pw = new PrintWriter(file);
pw.println("destroy");
} catch (Exception e ){
e.printStackTrace();
}
pw.close();
这个为什么不行?
zwxlovellm的方法不行

Java使用FileWriter实现文件的写入,用法为:FileWriter(file,true); 其中第二个参数设置成false就是覆盖写入,true就是增量存储。举例代码:

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class File01Demo {
public static void main(String[] args) throws IOException {
File file = new File("D:\\a.txt");
FileWriter fw = new FileWriter(file,true); //设置成true就是追加
fw.write("asd");
fw.write("\r\n");
fw.write("ffd");
fw.close();
}
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2008-09-30
system.out.println()是在控制台输入的
你可以用log4j
然后在配置文件里指定日志输出的目录。
第2个回答  2008-09-30
用FileOutputStream
第3个回答  2008-09-30
你可以加上FileOutputStream fis=new FileOutputSteam(file);
然后pw=new PrintWriter(fis);试试。
第4个回答  2008-09-30
代码没有任何问题啊?你测试看看
import java.io.File;
import java.io.PrintWriter;

class T {

  public static void main(String args[]) throws Exception {
    PrintWriter pw = null;
    try {
      File file = new File("c:\\6.txt");
      pw = new PrintWriter(file);
      pw.println("destroy");
    } catch (Exception e) {
      e.printStackTrace();
    }
    pw.close();
  }
}本回答被网友采纳
相似回答