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

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

问题描述

我正在Java中,在Windows上检查日志文件是否为空(意味着没有错误)。



方法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(失败)

 文件logFile =新建文件(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!);


解决方案

检查文件的第一行是否为空: / p>

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


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.

Method 1 (Failure)

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

Method 2 (Failure)

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

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.

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

Method 3 (Failure)

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天全站免登陆