在 Windows 上的 Java 中检查文件是否为空的最有效方法 [英] Most efficient way to check if a file is empty in Java on Windows

查看:31
本文介绍了在 Windows 上的 Java 中检查文件是否为空的最有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检查日志文件是否为空(意味着没有错误),在 Java 中,在 Windows 上.到目前为止,我已尝试使用 2 种方法.

I am trying to check if a log file is empty (meaning no errors) or not, in Java, on Windows. I have tried using 2 methods so far.

方法 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 个字节).

Now both these methods fail at times when the log file is empty (has no content), yet the file size is not zero (2 bytes).

检查文件是否为空的最有效方法是什么?我要求效率,因为我必须循环检查文件大小数千次.

What is the most efficient and accurate method to check if the file is empty? I asked for efficiency, as I have to keep checking the file size thousands of times, in a loop.

注意:文件大小只会在几到 10 KB 左右徘徊!

Note: The file size would hover around a few to 10 KB only!

方法 3(失败)

按照@Cygnusx1 的建议,我也尝试过使用 FileReader,但没有成功.这是片段,如果有人感兴趣的话.

Following @Cygnusx1's suggestion, I had tried using a FileReader too, without success. Here's the snippet, if anyone's interested.

Reader reader = new FileReader(sLogFilename);
int readSize = reader.read();
if (readSize == -1)
    System.out.println("NO ERRORS!");
else
    System.out.println("SOME ERRORS!");

推荐答案

检查文件第一行是否为空:

Check if the first line of file is empty:

BufferedReader br = new BufferedReader(new FileReader("path_to_some_file"));     
if (br.readLine() == null) {
    System.out.println("No errors, and file empty");
}

这篇关于在 Windows 上的 Java 中检查文件是否为空的最有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆