为什么用字节流读取写入文件会造成文件大小不一致?

dcq 2004-07-19 04:41:03
我的程序代码如下:
import java.io.*;

public class IOTest{
public static void main(String[] args){

try{

DataInputStream in2 = new DataInputStream(new BufferedInputStream(new FileInputStream("1.jpg")));
DataOutputStream out2= new DataOutputStream(new BufferedOutputStream(new FileOutputStream("2.jpg")));
while( in2.available()!=0)
out2.writeByte(in2.readByte());

}
catch(IOException e){}

}
}

我的想法是:从文件1.jpg产生一个DataInputStream,然后从此stream中读取数据写入2.jpg,结果2.jpg文件和1.jpg文件大小不致了,请问这是什么?
...全文
1586 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
javafaq2004 2004-07-20
  • 打赏
  • 举报
回复
怎么知道该byte数组应该分配多大呢?
cowboyseu 2004-07-20
  • 打赏
  • 举报
回复
byte[] b = new byte[2048];
int startPosition = 0;
int readLen = 0;
int fileLen = sourceFile.length();
while(startPostion < fileLen)
while( (readLen=in2.read(b,0,b.length))!=-1)
{
out2.write(b,0,readLen);
startPostion += readLen;
}
........

byte数组大,缓存就大,byte数组小缓存就小,你把它设成大小1,也没有问题,就是计算机忙了些,呵呵
rick_silver 2004-07-20
  • 打赏
  • 举报
回复
to:javafaq2004(农村干部瞎忙活)
long len = sourceFile.length();
通过得到源文件的长度就可以知道分配多大的数组了
rick_silver 2004-07-19
  • 打赏
  • 举报
回复
sorry没有看清题目,reader和writer是用来读取文本文件的,数据文件的读取

long len = sourceFile.length();
byte[] b;
if(len > Integer.MAX_VALUE){
throw new Exception("File is too large!");
}else{
b = new byte[(int)len];
}
int bytes = 0;
int offset = 0;
try {
FileInputStream fis = new FileInputStream(sourceFile);
FileOutputStream fos = new FileOutputStream(targetFile);
while(offset < b.length && (bytes = fis.read(b,offset,b.length-offset)) >= 0){
offset += bytes;
}
fos.write(encoder.encode(b));
fos.close();
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

应该声明一个长度和源文件等长的byte数组,但是file对象得到的length是long类型,声明数组的维度只能是整型,也就是说源文件的体积被限制在Integer的最大值,大概是4g多。这样,得到file的长度之后,就可以根据这个长度创建数组了。
dcq 2004-07-19
  • 打赏
  • 举报
回复
为改成如下的方式就正常了:
byte[] b = new byte[2048];
int readLen = 0;

while( (readLen=in2.read(b,0,b.length))!=-1)
out2.write(b,0,readLen);
这是为什么呢?为怎么知道该byte数组应该分配多大呢?
dcq 2004-07-19
  • 打赏
  • 举报
回复
对于像jpg这类格式的文件也可用Reader/Writer类来进行读写吗?
rick_silver 2004-07-19
  • 打赏
  • 举报
回复
如果你分配读取的byte数组足够大,这个问题就应该不存在了.
但是建议采用Reader/Writer类组完成文件读写操作
shuneng 2004-07-19
  • 打赏
  • 举报
回复
我试过这样的情况 JAVA的这个available函数好像有点问题
你最好用一个变量先取出它的值 再来做WHILE 不用次次都调用
dcq 2004-07-19
  • 打赏
  • 举报
回复
问题还是一样呀!
stonecsdn 2004-07-19
  • 打赏
  • 举报
回复
while( in2.available()!=-1)//这换成-1试试
out2.writeByte(in2.readByte());

62,622

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧