java中用IO粗略方法实现图片的拷贝
package IO;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class PictureChange {
public static void main(String args[]) {
File f = new File(“D:/java_foundation/src/IO/lover.jpg”);
filetoByteArray(f);
System.out.println(f.length());
byteArraytoFile(filetoByteArray(f),new File(“D:/java_foundation/src/IO/l.jpg”));
}
public static byte[] filetoByteArray(File f) {
ByteArrayOutputStream b = null;
InputStream i = null;
try {
i = new FileInputStream(f);
b = new ByteArrayOutputStream();
int len = -1;
byte[] b1 = new byte[1024];
while((len = i.read(b1))!=-1) {
b.write(b1, 0, len);
}
b.flush();
return b.toByteArray();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
b.close();
i.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
public static void byteArraytoFile(byte[] b,File f) {
InputStream i = new ByteArrayInputStream(b);
OutputStream o = null;
int len = -1;
byte[] b1 = new byte[1024];
try {
o = new FileOutputStream(f);
while((len = i.read(b1))!=-1) {
o.write(b1, 0, len);
}
o.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
o.close();
i.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}