最有效的方法来检查Windows中的Java文件是否为空

前端之家收集整理的这篇文章主要介绍了最有效的方法来检查Windows中的Java文件是否为空前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图检查一个日志文件是否为空(意味着没有错误),在Java中,在Windows上。到目前为止,我已经尝试使用2种方法

方法1(失败)

FileInputStream fis = new FileInputStream(new File(sLogFilename));  
int iByteCount = fis.read();  
if (iByteCount == -1)  
    System.out.println("NO ERRORS!");
else
    System.out.println("SOME ERRORS!");

方法2(失败)

File logFile = new File(sLogFilename);
if(logFile.length() == 0)
    System.out.println("NO ERRORS!");
else
    System.out.println("SOME ERRORS!");

现在这两种方法在日志文件为空(没有内容)时失败,但文件大小不为零(2字节)。

检查文件是否为空的最有效和准确的方法是什么?我要求效率,因为我必须继续检查文件大小数千次。

注意:文件大小只能悬停在几个到10 KB之间!

方法3(失败)

遵循@ Cygnusx1的建议,我也尝试使用FileReader,没有成功。如果有人有兴趣,这是代码段。

Reader reader = new FileReader(sLogFilename);
int readSize = reader.read();
if (readSize == -1)
    System.out.println("NO ERRORS!");
else
    System.out.println("SOME ERRORS!");
检查文件的第一行是否为空:
BufferedReader br = new BufferedReader(new FileReader("path_to_some_file"));     
if (br.readLine() == null) {
    System.out.println("No errors,and file empty");
}
原文链接:https://www.f2er.com/windows/372955.html

猜你在找的Windows相关文章