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[]里实际占用的字节数(也就是文件的大小)
int len = new File(fileName).length();
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;
不过你如果想读文件大小何必怎么麻烦
input = new FileInputStream(fileName);
int len = input.available(); 这句话就获取文件大小了
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();
}