Copy Code code as follows:
Package Com.teligen.eos.teleCode;
Import Java.io.File;
Import Java.io.FileWriter;
Import java.io.IOException;
Import Java.util.Date;
/**
* Write log information to the specified file
*/
public class Writelogutil {
private static String RootPath = "d:\\logs\\";
/**
* Write the information to the file
* @param msg
*/
public static void Writemsgtofile (String msg) {
Delete previous files
Deloldfile ();
FileWriter FileWriter = null;
try {
FileWriter = new FileWriter (GetFileName (), true);
Date today = new Date ();
String time = string.valueof (Today.gethours ()) + ":" + string.valueof (today.getminutes ()) + "" + string.valueof (today.get Seconds ());
Filewriter.write ("#" + Time + "# [" + msg + "]" + "\ r \ n");
Filewriter.flush ();
catch (IOException e) {
System.out.println ("### write log to file exception ### >>>" + e.getmessage ());
E.printstacktrace ();
finally {
try {
Filewriter.close ();
catch (IOException e) {
System.out.println ("### Shutdown write Log flow exception ### >>>" + e.getmessage ());
E.printstacktrace ();
}
}
}
/**
* Delete previous log files
*/
private static void Deloldfile () {
Date today = new Date ();
int month = Today.getmonth () +1;
month = month-2;
if (month = = 1) month = 11;
if (month = = 0) month = 12;
String Delpath = RootPath + string.valueof (month) + "\";
File Folder = new file (Delpath);
if (folder.exists ()) {
file[] files = folder.listfiles ();
for (int i=0; i<files.length; i++) {
Files[i].delete ();
}
}
}
/**
* Get the file to save
* @return FileName
*/
private static String GetFileName () {
Date today = new Date ();
String fileName = string.valueof ((today.getyear () +1900)) + string.valueof ((Today.getmonth () +1)) + string.valueof ( Today.getdate ()) + ". Log";
Create a table of contents
File Folder = new file (RootPath + string.valueof (today.getmonth () +1)) + "\");
if (!folder.exists ()) {
Folder.mkdirs ();
}
Create a file
File File = new file (fileName);
if (!file.exists ()) {
try {
File.createnewfile ();
catch (IOException e) {
System.out.println ("### new log file exception ### >>>" + e.getmessage ());
E.printstacktrace ();
}
}
filename = RootPath + string.valueof ((Today.getmonth () +1)) + "\" + filename;
return fileName;
}
/**
* Test the Main method used
*/
public static void Main (string[] args) {
GetFileName ();
String teststring = " Write the log slightly: 71FABB7890D2CC0D267FBD84F409618C0303BC597B9244C324947BDE4B1C0B4CB08C33FC461F7BADD088535DAE42D8D7D06F4134E442D9D1CE3A 0f9b3edd64337a2d18ce34fcdc137b7cbd84f409618c03038feaec79f79c2f58bd84f409618c03038feaec79f79c2f58bd84f409618c03038feaec79f 79C2F581790ACB3C178641D14D8C09905BC52CF1C8249B12F2EDE5AC3C8FAF2FD8A686E ";
Writemsgtofile (teststring);
Deloldfile ();
}
}