gpt4 book ai didi

java - 在 Windows 上的 Java 中检查文件是否为空的最有效方法

转载 作者:IT老高 更新时间:2023-10-28 21:21:10 26 4
gpt4 key购买 nike

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

方法一(失败)

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!");

方法二(失败)

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");
}

关于java - 在 Windows 上的 Java 中检查文件是否为空的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7190618/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com