Salinan kode adalah sebagai berikut:
paket com.teligen.eos.telecode;
impor java.io.file;
impor java.io.filewriter;
impor java.io.ioException;
impor java.util.date;
/**
* Tulis informasi log ke dalam file yang ditentukan
*/
Kelas Publik Writelogutil {
Private Static String rootpath = "d: // log //";
/**
* Tulis informasi ke file
* @param msg
*/
public static void wrItemsgtofile (string msg) {
// Hapus file sebelumnya
deloldfile ();
FileWriter FileWriter = null;
mencoba {
FileWriter = FileWriter baru (getFileName (), true);
Tanggal hari ini = tanggal baru ();
String time = string.valueOf (hari ini.getHours ()) + ":" + string.valueof (hari ini.getMinutes ()) + "" + string.ValueOf (hari ini.getSeconds ());
fileWriter.write ("#" + waktu + "# [" + msg + "]" + "/r/n");
FileWriter.Flush ();
} catch (ioException e) {
System.out.println ("#### Ucikan log ke file pengecualian #### >>>" + e.getMessage ());
e.printstacktrace ();
} Akhirnya {
mencoba {
filewriter.close ();
} catch (ioException e) {
System.out.println ("### Tutup pengecualian aliran untuk menulis log ### >>" + e.getMessage ());
e.printstacktrace ();
}
}
}
/**
* Hapus file log sebelumnya
*/
private static void deloldFile () {
Tanggal hari ini = tanggal baru ();
int bulan = hari ini.getMonth ()+1;
Bulan = Bulan - 2;
if (bulan == -1) bulan = 11;
if (bulan == 0) bulan = 12;
String delpath = rootpath + string.valueof (bulan) + "//";
File folder = file baru (delpath);
if (folder.exists ()) {
File [] file = folder.listFiles ();
untuk (int i = 0; i <file.length; i ++) {
file [i] .delete ();
}
}
}
/**
* Mendapatkan file yang disimpan
* @return fileName
*/
Private Static String getFileName () {
Tanggal hari ini = tanggal baru ();
String filename = string.valueof ((hari ini.getYear () + 1900)) + string.valueof ((hari ini.getMonth () + 1)) + string.valueof (hari ini.getDate ()) + ".log";
// Buat direktori
Folder file = file baru (rootpath + string.valueof ((hari ini.getMonth () + 1)) + "//");
if (! folder.exists ()) {
folder.mkdirs ();
}
// Buat file
File file = file baru (nama file);
if (! file.exists ()) {
mencoba {
file.createNewFile ();
} catch (ioException e) {
System.out.println ("#### file log baru pengecualian #### >>>" + e.getMessage ());
e.printstacktrace ();
}
}
filename = rootpath + string.valueof ((hari ini.getMonth () + 1)) + "//" + fileName;
Kembalikan nama file;
}
/**
* Metode utama yang digunakan untuk menguji
*/
public static void main (string [] args) {
// getFileName ();
String testString = Log Tulis: 71FABB7890D2CC0D267FBD84F409618C0303BC597B9244C324947BDE4B1C0B4CB08C33FC44D06BADD0888853535DAE42D82D844D84D068885353535DAE4D82D84D844D84D8888535353535d82d82d82d82d82d82d82d82d8fc4d84d82d8fc4d82d82d8fc4 64337A2D18CE34FCDC137B7CBD84 F409618C03038FEAEC79F79C2F58BD84F409618C03038FEAEC79F79C2F58BD84F409618C03038FEAEC79F79C2F581790ACB3C178641D14D8C09905BC52CF1C8249B12F2EDE5AC3C8FAF2FD8A686E";
writemsgtofile (testString);
// deloldfile ();
}
}