日期:2014-05-20  浏览次数:20914 次

往文件里写文件,写了好多内容了,文件大小却显示为0
往文件里写文件,写了好多内容了,文件大小却显示为0。这是为什么呢?这些文件是我用java写的日志文件。
代码如下:package com.southinfo.kedaoservice.log;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.lang.reflect.Field;
import java.util.Date;

import com.southinfo.kedaoservice.util.DateUtil;

public class Logger {

private Class<?> cls;

private PrintStream printStream;

public static Logger getLogger(Class<?> cls) {
String filePath = null;
try {
Class<?> forName = Class
.forName("com.southinfo.kedaoservice.core.Config");
Field declaredField = forName.getDeclaredField("ID");
filePath = "logs/[" + declaredField.get(null) + "]"
+ cls.getSimpleName() + ".log";
} catch (ClassNotFoundException e) {
filePath = "logs/[_]" + cls.getSimpleName() + ".log";
} catch (Exception e) {
System.err.println("生成日志文件出错!");
System.exit(1);
}

Logger logger = new Logger();
logger.cls = cls;
try {
logger.printStream = new PrintStream(new FileOutputStream(new File(
filePath)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return logger;
}

public void info(String message) {
info(message, null);
}

public void info(String message, Exception e) {
String output = DateUtil.format(new Date()) + " INFO "
+ cls.getSimpleName() + " " + message;
printStream.append(output + "\r\n");
System.out.println(output);
if (e != null) {
e.printStackTrace(printStream);
}
}

public void error(String message) {
error(message, null);
}

public void error(String message, Exception e) {
String output = DateUtil.format(new Date()) + " ERROR "
+ cls.getSimpleName() + " " + message;
printStream.append(output + "\r\n");
System.out.println(output);
if (e != null) {
e.printStackTrace(printStream);
}
}

public void debug(String message) {
debug(message, null);
}

public void debug(String message, Exception e) {
String output = DateUtil.format(new Date()) + " DEBUG "
+ cls.getSimpleName() + " " + message;
System.out.println(output);
printStream.append(output + "\r\n");
if (e != null) {
e.printStackTrace(printStream);
}
}

public Class<?> getCls() {
return cls;
}

public void setCls(Class<?> cls) {
this.cls = cls;
}

public PrintStream getPrintStream() {
return printStream;
}

public void setPrintStream(PrintStream printStream) {
this.printStream = printStream;
}

}


------解决方案--------------------
这个,应该跟你操作系统有关,操作系统没有去刷新它自己的缓存数据。

另外,可以考虑定期执行flush(),避免数据在缓存中而没有实际写入系统,那么程序意外终止,这些数据就没了;不过一般来说缓存不会很大。
------解决方案--------------------
由于是日志文件,推测你打开文件看的时候,Java这边仍没有关闭文件,处于写入状态。
这样没有别的好办法,在程序里经常flush一下吧

------解决方案--------------------
OutputStream 都有flush()方法。
另外,你在日志文件所在目录,常按"F5"几下。