日期:2014-05-19  浏览次数:20734 次

用read从FileInputStream里读出的byte[],怎么知道它的长度?
Java code

FileInputStream input;
byte[] buffer = new byte[1024 * 1024];

        try {
            input = new FileInputStream(fileName);
            int len = input.read(buffer, 0, buffer.length);
            
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }



读文件的代码如上,如果用buffer.length返回的是1024*1024=1048576,这个是byte[]数组的所有字节数。我想得到文件在byte[]里实际占用的字节数(也就是文件的大小)

------解决方案--------------------
用FileInputStream的未必精确,建议用:
int len = new File(fileName).length();
------解决方案--------------------
int len = input.read(buffer, 0, buffer.length);

如果 文件大小 小于 buffer.length 的话 

len 的值就是文件的实际大小,也就是byte[]数组中实际占用的字节数

如果文件大小 大于 buffer.length 的话

你需要多次读取才行,一直到 len < buffer.length 才读完

Java code

        byte[] buf = new byte[1024*1024];
        FileInputStream fis = new FileInputStream("c:\\test.db");
        
        int totalLen = 0; //文件总大小
        int len = 0;
        while((len = fis.read(buf)) == buf.length){
            totalLen += buf.length;
        }
        totalLen += len;

------解决方案--------------------
那你只有把byte[]重新定义大小再传

Java code

FileInputStream input;

byte[] buffer = null;
        try {
            int fileLen = 0;
            fileLen = input.available();
            buffer = new byte[fileLen]; //buffer的大小就是文件的大小
            input = new FileInputStream(fileName);
            int len = input.read(buffer);

            
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

------解决方案--------------------
那个。。。read不是都返回了len嘛。。。。看看doc吧。。。。
------解决方案--------------------
http://topic.csdn.net/u/20120816/17/963e96cd-4476-41c4-88fb-b7a1d2a958ba.html