import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
//字节流粘贴复制
public class IO2 {
public static void main(String[] args) throws IOException {
//copyFile 有泄露危险bug
copyFile("E:\\code\\IO练习/view.jpg" , "E:\\code\\IO练习/view2.jpg");
//copyFile2 无bug但代码臃肿
copyFile2("E:\\code\\IO练习/view.jpg" , "E:\\code\\IO练习/view2.jpg");
//copyFile3 最终版
copyFile3("E:\\code\\IO练习/view.jpg" , "E:\\code\\IO练习/view2.jpg");
}
private static void copyFile(String srcPath, String destPath) throws IOException {
FileInputStream fileInputStream = new FileInputStream(srcPath);
FileOutputStream fileOutputStream = new FileOutputStream(destPath);
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fileInputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer,0,len);
}
fileInputStream.close();
fileOutputStream.close();
}
private static void copyFile2(String srcPath, String destPath) {
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try {
fileInputStream = new FileInputStream(srcPath);
fileOutputStream = new FileOutputStream(destPath);
byte[] buffer = new byte[1024];
int len = -1;
while ((len = fileInputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fileInputStream != null) {
fileInputStream.close();
}
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void copyFile3(String srcPath, String destPath) {
try (FileInputStream fileInputStream = new FileInputStream(srcPath);
FileOutputStream fileOutputStream = new FileOutputStream(destPath);
) {
byte[] buffer = new byte[1024];
int len = -1;
while ((len = fileInputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer,0,len);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}