Java 检查文件是否为空:IOException: null

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16460790/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 23:00:42  来源:igfitidea点击:

Java check if file is empty: IOException: null

javafile-io

提问by NGix

I'm trying to load a file to my ArrayList, program creates a file if it doesn't exist. I'm getting IOException: Null as at the beginning file is empty. How I can avoid that error and check if file is empty or not? Here's my code:

我正在尝试将文件加载到我的 ArrayList,如果文件不存在,程序会创建一个文件。我收到 IOException: Null 因为开头的文件是空的。如何避免该错误并检查文件是否为空?这是我的代码:

     File f = new File(fileName);

     try {
        if( !f.exists() ){
            f.createNewFile();
        }

        inputStream = new ObjectInputStream(new FileInputStream(f));
        scores = (ArrayList<Score>) inputStream.readObject();
     } catch (IOException e) {
        System.out.println("IO Error: " + e.getMessage());
     } finally {
         ...
     }

回答by hmjd

Use File.length()to obtain the size number of bytes of the file:

使用File.length()获得文件的字节大小数:

The length, in bytes, of the file denoted by this abstract pathname, or 0L if the file does not exist. Some operating systems may return 0L for pathnames denoting system-dependent entities such as devices or pipes.

此抽象路径名表示的文件的长度(以字节为单位),如果文件不存在,则为 0L。某些操作系统可能会为表示系统相关实体(例如设备或管道)的路径名返回 0L。

回答by Vorsprung

It seems to me your program needs a minor bit of restructuring, then it won't try and load the empty file

在我看来你的程序需要一点点重组,然后它不会尝试加载空文件

File f = new File(fileName);

     try {
        if( f.length() == 0 ){
            f.createNewFile();
        } else {
            inputStream = new ObjectInputStream(new FileInputStream(f));
            scores = (ArrayList<Score>) inputStream.readObject();
        }
     } catch (IOException e) {
        System.out.println("IO Error: " + e.getMessage());
     } finally {
         ...