I'm using java IO to copy a picture,but I get different size. original image "eye.jpg" is 225995kb,the copy "eyecopy2.jpg"is 226304. And I program to get eye.jpg's size,it's 226304kb. I open the copy, it's correct.I wonder if it's nomal?
byte[] data=null;
try {
InputStream is = new FileInputStream("eye.jpg");
ByteArrayOutputStream os=new ByteArrayOutputStream();
copy(is, os);
data=os.toByteArray();
System.out.println(data.length);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
InputStream is = new ByteArrayInputStream(data);
OutputStream os=new FileOutputStream("eyecopy2.jpg");
copy(is, os);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
the copy function
public static void copy(InputStream is,OutputStream os) {
try {
byte[] data=new byte[1024];
int len=-1;
while((len=is.read(data))!=-1) {
os.write(data,0,data.length);
}
os.flush();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(null!=os) {
try {
os.close();
} catch (IOException e) {
// TODO: handle exception
}
}
if(null!=is) {
try {
is.close();
} catch (IOException e2) {
// TODO: handle exception
}
}
}
}
Look at the while loop
while((len=is.read(data))!=-1) {
os.write(data,0,data.length);
}
It's writing data.length
, which is always 1024, the length of the buffer.
But at the end of the stream the amount read in isn't necessarily exactly 1024 bytes.
Instead, try writing the amount read in:
while((len=is.read(data))!=-1) {
os.write(data, 0, len); // <-- here
}