---
title: "ReadFile2ByteArrayTest"
author: "f543711700"
date: "2017-11-02T11:09:08Z"
tags: []
categories: ["编程语言"]
slug: "readfile2bytearraytest"
draft: false
lastmod: "2017-11-02T11:09:08Z"
id: 2398395
url: "https://f543711700.iteye.com/blog/2398395"
---

```java
package com.ghca.policeintf.test;

import java.io.FileInputStream;
import java.io.IOException;

/**
 * Created by DUDU on 2017/11/2.
 */
public class ReadFile2ByteArrayTest {
    public static void main(String[] args) throws IOException {
        FileInputStream fis = new FileInputStream("D:\\32位系统移植过来的文件\\1`.rar");
        byte[] buffer = new byte[1024];
        int totalReadCount = 0;
        while(true) {
            int remaining = buffer.length - totalReadCount;
//                if (remaining > 0) {
//                    int currentReadCount = fis.read(buffer,totalReadCount,remaining);
//                    if (currentReadCount > 0) {
//                        totalReadCount = totalReadCount +  currentReadCount;
//                    } else {
//                        break;
//                    }
//                } else {//扩容buffer
//                    byte[] newBuffer = new byte[buffer.length * 2];
//                    System.arraycopy(buffer,0,newBuffer,0,totalReadCount);
//                    buffer = newBuffer;
//                }
            if (remaining <= 0) {//先扩容buffer
                byte[] newBuffer = new byte[buffer.length * 2];
                System.arraycopy(buffer,0,newBuffer,0,buffer.length);
                buffer = newBuffer;
//                remaining = buffer.length - totalReadCount;
                continue;
            }
            int currentReadCount =  fis.read(buffer,totalReadCount,remaining);
            if (currentReadCount > 0) {
                totalReadCount = totalReadCount + currentReadCount;
            } else {
                break;
            }
        }
        System.out.println("总共读取字节数:" + totalReadCount);
        System.out.println("buffer大小：" + buffer.length);
    }
}

```