import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;public class CopyImageDemo { public static void main(String[] args) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("c:/a.jpg");
fos = new FileOutputStream("c:/b.jpg");
try {
System.out.println("文件大小:" + fis.available() + "Byte");
byte buf[] = new byte[fis.available()];
int len = 0;
while ((len = fis.read(buf)) != -1) {
fos.write(len);
fos.flush();
} } catch (IOException e) { e.printStackTrace();
}
} catch (FileNotFoundException e) { e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
if (fos != null) {
fos.close();
}
} catch (IOException e) { e.printStackTrace();
}
}
}
}
代码如上。
为啥是这样的结果呢~谢谢~
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;public class CopyImageDemo { public static void main(String[] args) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("c:/a.jpg");
fos = new FileOutputStream("c:/b.jpg");
try {
System.out.println("文件大小:" + fis.available() + "Byte");
byte buf[] = new byte[fis.available()];
int len = 0;
while ((len = fis.read(buf)) != -1) {
fos.write(len);
fos.flush();
} } catch (IOException e) { e.printStackTrace();
}
} catch (FileNotFoundException e) { e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
if (fos != null) {
fos.close();
}
} catch (IOException e) { e.printStackTrace();
}
}
}
}
代码如上。
为啥是这样的结果呢~谢谢~
改成
fos.write(buf, 0, len);不过不建议1次把文件全读了输出。
万一文件很大,会出错的。类似这样。 // 新建文件输入流并对它进行缓冲
inBuff = new BufferedInputStream(new FileInputStream(sourceFile)); // 新建文件输出流并对它进行缓冲
outBuff = new BufferedOutputStream(new FileOutputStream(targetFile)); // 缓冲数组
byte[] b = new byte[1024 * 5];
int len;
while ((len = inBuff.read(b)) != -1) {
outBuff.write(b, 0, len);
}
// 刷新此缓冲的输出流
outBuff.flush();
用BufferedInputStream包装FileInputStream
用BufferedOutputStream包装FileOutputStream
flush方法写在while循环的外面