流的关闭方式!

流务必要在finally里关闭。都是教训啊!

示例:

    public static boolean file_isPass(String filePath, String fileType) {
        File file = new File(filePath);
        byte[] b = new byte[50];
        InputStream is = null;
        try {
            is = new FileInputStream(file);
            is.read(b);
            //如果文件头和获取的map里 这些文件头一样,就为真实文件
            String fileHead = FILE_TYPE_MAP.get(fileType);
            int headLength = fileHead.length();
            String fileTypeAllValue = getFileHexString(b);
            if (fileTypeAllValue != null) {
                // 获取的文件头转换为大写 进行比较
                String fileTypeValue = fileTypeAllValue.substring(0, headLength).toUpperCase();
                System.out.println("当前文件头:" + fileTypeValue);
                if (fileHead.equals(fileTypeValue)) {
                    return true;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return false;
    }

当时没有在finally里关闭,导致成功直接return true。文件一直被占用。

务必要在finally里关闭流!

务必要在finally里关闭流!!

务必要在finally里关闭流!!!

posted @ 2022-11-17 17:51  xiaolifc  阅读(99)  评论(0)    收藏  举报