No more nonsense, straight into the subject: The code is as follows:
1. Read log or txt text information
/**
* Read log or txt information
*
* @param FilePath
* @return
*/
Public list<string> Readlog (String filePath) {
list<string> list = new arraylist<string> ();
try {
fileinputstream is = new FileInputStream (filePath);
inputstreamreader ISR = new InputStreamReader (IS);
bufferedreader br = new BufferedReader (ISR);
string Line;
try {
while (line = Br.readline ())!= null) {
if (Line.equals (""))
continue;
else
list.add (line);
&NBSP;&NBSP;&NBSP;&NBSP}
} catch (IOException e) {
E.printstacktrace ();
system.out.println ("Error reading a row of data");
}
} catch (FileNotFoundException e) {
e.printstacktrace ();
&NBSP;&NBSP;&NBSP;SYSTEM.OUT.PRINTLN ("file read path error FileNotFoundException");
}
return list;
}
2. Write log or TXT file content
/**
* Create a new log or TXT file and write to the content
*
* @param filePath
* @param fileName
* @par AM MSG
*/
public void Createlog (String filePath, String fileName, String msg) {
PrintWriter logprint = null;
try {
logprint = new PrintWriter (
new FileWriter (FilePath + FileName, True), true);
} catch (IOException e) {
(new File (FilePath)). mkdir ();
try {
logprint = new PrintWriter (new FileWriter (FilePath + fileName,
true), true);
} catch (IOException ex) {
logprint = new PrintWriter (system.err);
writererrorinfo (Logprint, ex, "Unable to open log file:" + FilePath + fileName);
}
}
writerloginfo (Logprint, msg);
}
/**
* Write text information to the log file
*
* @param msg
* Log Content
*/
Private synchronized static void Writerloginfo (PrintWriter logprint,
String msg) {
Logprint.println (New SimpleDateFormat ("Yyyy-mm-dd hh:mm:ss")
. Format (New Date ())
+ "" + msg);
}
/**
* Write text information and exceptions to the log file
*
* @param E
* @param msg
*/
Private synchronized static void Writererrorinfo (PrintWriter logprint,
Throwable e, String msg) {
Logprint.println (New SimpleDateFormat ("Yyyy-mm-dd hh:mm:ss")
. Format (New Date ())
+ "" + msg);
E.printstacktrace (Logprint);
}
Note that:
FilePath must be like this: "Disk Number://Folder name//"
FileName must be like this: Test.txt or Test.log.