我正在尝试将文件写入我的应用程序日志。我创建了一个方法,在行的末尾添加一行。
public static void write2Log(String s){
StringBuilder contents = new StringBuilder();
File root = Environment.getExternalStorageDirectory();
File logFile = new File(root, "testWrite2file.log");
if (root.canWrite()){
try {
BufferedReader input = new BufferedReader(new FileReader(logFile));
String line = null;
while (( line = input.readLine()) != null){
contents.append(line);
// contents.append(System.getProperty("line.separator"));
}
input.close();
FileWriter logWriter = new FileWriter(logFile);
BufferedWriter out = new BufferedWriter(logWriter);
out.write(contents.toString()+"\r\n"+s);////<---HERE IS MY QUESTION
out.close();
}
catch (IOException e) {
Log.e("test", "Could not read/write file " + e.getMessage());
}
}
}
一切都比新角色更好。
我尝试过使用:
\r\n
System.getProperty("line.separator")
newline()
但是我一直只能用一行:(
有什么想法吗?
答案 0 :(得分:2)
试试这个:
FileWriter logWriter = new FileWriter(logFile);
BufferedWriter out = new BufferedWriter(logWriter);
out.write(contents.toString());////<---HERE IS THE CHANGE
out.newLine();
out.write(s);
out.close();
答案 1 :(得分:0)
试试这个
public static boolean writeLog(String user , Exception exS) {
boolean d = false;
try {
File root = new File("TVS_log");
if (!root.exists()) {
root.mkdirs();
}
String name = user + "_" + TimeReporter.getTodayAll() + "_" + "log.txt" ;
System.out.println(name);
File text = new File(root , name);
if (!text.exists()) {
text.createNewFile();
}
String aggregate = "";
for (StackTraceElement element : exS.getStackTrace())
{
BufferedWriter writer = new BufferedWriter(new FileWriter(text)) ;
String message = exS.toString() + " - " + element.toString() + "\r\n" ;
System.out.println(exS.toString());
System.out.println(element.toString());
aggregate += message;
writer.write (aggregate);
writer.newLine();
writer.flush();
writer.close();
writer = null;
}
if(text.exists())
return text.length() > 0;
}catch(Exception ex){
ex.printStackTrace();
}
return d;
}
TimeReporter类和函数
public class TimeReporter {
public static String getTodaysDate() {
String d = "";
final Calendar c = Calendar.getInstance();
d = String.format("%02d", c.get(Calendar.YEAR))
+ String.format("%02d", c.get(Calendar.MONTH) + 1)
+ String.format("%02d", c.get(Calendar.DAY_OF_MONTH));
return d;
}
public static String getTodaysTime() {
String d = "";
final Calendar c = Calendar.getInstance();
d = String.format("%02d", c.get(Calendar.HOUR_OF_DAY))
+ String.format("%02d", c.get(Calendar.MINUTE))
+ String.format("%02d", c.get(Calendar.SECOND));
return d;
}
public static String getTodayAll() {
return getTodaysDate() + "_" + getTodaysTime() ;
}
public static String getNow() {
final Calendar c = Calendar.getInstance();
String ld = c.get(Calendar.YEAR) + "/" + (c.get(Calendar.MONTH) + 1)
+ "/" + c.get(Calendar.DAY_OF_MONTH) + " "
+ String.format("%02d", c.get(Calendar.HOUR_OF_DAY)) + ":"
+ String.format("%02d", c.get(Calendar.MINUTE));
return ld;
}
}