1,/* * 自动化测试,每一次运行会生成一个log,使用当前的日期时间作为log文件名字会带来方便,用该log文件来记录所有的输入输出。 */
package c1;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.io.*;
public class Test{
public static void main(String[] args){
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd-HHmmss");
String sLogFileName=sdf.format(new Date())+".log";
TestOut testout=new TestOut(sLogFileName);
testout.logOut("hello");
testout.logOut("hello1");
}
}
class TestOut{
public String sLogFileName="";
public TestOut(String sLogFileName){
this.sLogFileName=sLogFileName;
File logfile=new File(sLogFileName);
try{
logfile.createNewFile();
logOut(sLogFileName+" was created.");
//throw new IOException();
}
catch(IOException e){
e.printStackTrace();//System.out.println (e);
System.out.println("failed to create file:"+sLogFileName);// print out the runtime variables
//return false;
System.exit(0); //terminate the program or Runtime.getRuntime().exit(0);
}
}
public void logOut(String sOut){
System.out.println(sOut);
try{
BufferedWriter bw = new BufferedWriter( new FileWriter(sLogFileName,true));
bw.write(new Date()+" -- "+sOut);
bw.newLine();
bw.close();
//throw new IOException();
}
catch(IOException e){
e.printStackTrace();//System.out.println (e);
System.out.println("failed to write "+sOut+" into file:"+sLogFileName);// print out the runtime variables
System.exit(0); //terminate the program or Runtime.getRuntime().exit(0);
}
}
}
/*
输出结果:
2010-01-18-102901.log was created.
hello
hello1
log文件2010-01-18-102901.log内容:
Mon Jan 18 10:29:01 CST 2010 -- 2010-01-18-102901.log was created.
Mon Jan 18 10:29:01 CST 2010 -- hello
Mon Jan 18 10:29:01 CST 2010 -- hello1
*/
2,用static方法重写此类,事情变得更简单。
/*
* 自动化测试,每一次运行会生成一个log,使用当前的日期时间作为log文件名字会带来方便
*/
package c1;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.io.*;
public class Test{
public static void main(String[] args){
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd-HHmmss");
String sLogFileName=sdf.format(new Date())+".log";
TestOut.sLogFileName=sLogFileName;
TestOut.logOut("hello");
TestOut.logOut("hello1");
}
}
class TestOut{
public static String sLogFileName="";
public static void logOut(String sOut){
System.out.println(sOut);
try{
BufferedWriter bw = new BufferedWriter( new FileWriter(sLogFileName,true));
bw.write(new Date()+" -- "+sOut);
bw.newLine();
bw.close();
//throw new IOException();
}
catch(IOException e){
e.printStackTrace();//System.out.println (e);
System.out.println("failed to write "+sOut+" into file:"+sLogFileName);// print out the runtime variables
System.exit(0); //terminate the program or Runtime.getRuntime().exit(0);
}
}
}
/*
输出结果:
2010-01-18-102901.log was created.
hello
hello1
log文件2010-01-18-102901.log内容:
Mon Jan 18 10:29:01 CST 2010 -- 2010-01-18-102901.log was created.
Mon Jan 18 10:29:01 CST 2010 -- hello
Mon Jan 18 10:29:01 CST 2010 -- hello1
*/
阅读(1616) | 评论(0) | 转发(0) |