一个IO流的问题,请大家帮我解释一下
private static final int buff = 1024;
public static void main(String []args) throws Exception{
FileInputStream fis = new FileInputStream("f:\\test.mp3");
FileOutputStream fos = new FileOutputStream("f:\\copyOftest.mp3");
byte [] bytes = new byte[buff];
while(fis.read(bytes)!= -1){
fos.write(bytes);
}
fis.close();
fos.close();
}
就这段代码,当我们往文件写字节数组时,应该是将整个数组内容全部写出去,前面几次没问题,但是当文件大小不是1024的整数倍时,那也会把后面的写进去啊,但是程序运行并没有问题,请各位帮忙解释一下,谢谢
[最优解释]
out.flush();
默认是1024个字节,如果你不够的话他是不会主动去flush的,如果碰巧不能整除,那么你会发现最后面少了些数据。
不信你可以弄个txt文件试试。
[其他解释]
把byte [] bytes = new byte[buff];
while(fis.read(bytes)!= -1){
fos.write(bytes);
}
改为
byte [] bytes = new byte[buff];
int len = 0;
while((len=fis.read(bytes))!= -1){
fos.write(new String(bytes,0,len));
}
[其他解释]
需要判断下文件大小
读出源文件大小除以1024 得到商和余数
循环读取、写入的时候循环商次
最后读写一次,buff大小设定为余数大小
[其他解释]
static void t7(){
int readLen = 0;
InputStream in = null;
OutputStream out = null;
byte[] buff = new byte[512];
try{
//in = ...;
//out = ...;
while(-1 != (readLen=in.read(buff))){
out.write(buff, 0, readLen);
}
}catch(Exception ex){
ex.printStackTrace();
}
}
屌了...这样写会对吗...MP3文件,你用string往里面写???
fos.write(buf,0,len);
[其他解释]
谢谢大家的热心回答,大家提供的方法能够解决,但是我这样写运行也没有问题,拷贝后MP3能正常播放,而且大小也和源文件一模一样,我想知道为什么会这样
[其他解释]