背景介绍:项目中有一个创建合同数据的接口,里面包含了上游系统的文件的url,系统中用URL进行请求文件地址。

代码如下:

URL url = new URL(urlAddress);
URLConnection uc = url.openConnection();
if (BooleanUtils.isTrue(isNeedHeaders)) {
    setURLHeaderInfo(uc);
}
map.put("inputStream", uc.getInputStream());
map.put("fileName", urlAddress.substring(urlAddress.lastIndexOf("/") + 1));
map.put("fileType", urlAddress.substring(urlAddress.lastIndexOf(".") + 1));

获取文件字节的大小如下:

Long fileLength = inputStream.available()

fileLength的大小不是真实的文件大小,看api有介绍

大致意思是返回的字节数可能由于网络原因阻塞一次只能返回部分字节或者另外一个线程也读了导致返回部分字节。

我的解决办法:

把inputStream里的字节都读出来用read()方法,然后再取文件的字节大小。

        代码如下:

File destFile = new File(filePath, localFileName);
if (!destFile.getParentFile().exists()) {
    destFile.getParentFile().mkdirs();
}

FileOutputStream os = null;
try {
    os = new FileOutputStream(destFile);
    int n = 0;
    byte[] b = new byte[1024];
    while ((n = fileInputStream.read(b)) != -1) {
        os.write(b, 0, n);
    }
    os.flush();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        if (fileInputStream != null) {
            fileInputStream.close();
        }
        if (os != null) {
            os.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

然后用file.length()获取文件大小。

更多推荐

inputStream.available()方法获取文件字节大小不对的问题