package io;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
//需求:拷贝一张图片
public class Demo3 {
public static void main(String[] args) {
copyImage();
}
public static void copyImage() {
// 找到目标文件
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try {
File infile = new File("E:\\画\\1.jpg");// 源文件
File desfile = new File("D:\\a.jpg");// 目标文件
// 建立数据通道----每新创建一个FileOutputStream 默认情况 指针指向开始的位置,每写一次,指针相应的移动
fileInputStream = new FileInputStream(infile);
fileOutputStream = new FileOutputStream(desfile);// 参数加true,追加数据
byte[] buf = new byte[1024];// 缓冲数组存储读到的数据
int length = 0;// fileinputStream 返回值是长度byte
while ((length = fileInputStream.read(buf)) != -1) {
fileOutputStream.write(buf, 0, length);// 再将字符传转成字符数组写入
}
System.out.println("拷贝成功");
} catch (IOException e) {
// 读取失败
System.out.println("拷贝出错失败");
throw new RuntimeException(e);
}
// 原则 先开后关,后开先关
finally {
try {
if (fileOutputStream != null) {
fileOutputStream.close();
System.out.println("关闭输出流成功");
}
} catch (IOException e) {
System.out.println("关闭输出流失败");
throw new RuntimeException(e);
} finally {
try {
if (fileInputStream != null) {
fileInputStream.close();
System.out.println("关闭输入流成功");
}
} catch (IOException e) {
System.out.println("关闭输入流失败");
throw new RuntimeException(e);
}
}
}
}
}
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
//需求:拷贝一张图片
public class Demo3 {
public static void main(String[] args) {
copyImage();
}
public static void copyImage() {
// 找到目标文件
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try {
File infile = new File("E:\\画\\1.jpg");// 源文件
File desfile = new File("D:\\a.jpg");// 目标文件
// 建立数据通道----每新创建一个FileOutputStream 默认情况 指针指向开始的位置,每写一次,指针相应的移动
fileInputStream = new FileInputStream(infile);
fileOutputStream = new FileOutputStream(desfile);// 参数加true,追加数据
byte[] buf = new byte[1024];// 缓冲数组存储读到的数据
int length = 0;// fileinputStream 返回值是长度byte
while ((length = fileInputStream.read(buf)) != -1) {
fileOutputStream.write(buf, 0, length);// 再将字符传转成字符数组写入
}
System.out.println("拷贝成功");
} catch (IOException e) {
// 读取失败
System.out.println("拷贝出错失败");
throw new RuntimeException(e);
}
// 原则 先开后关,后开先关
finally {
try {
if (fileOutputStream != null) {
fileOutputStream.close();
System.out.println("关闭输出流成功");
}
} catch (IOException e) {
System.out.println("关闭输出流失败");
throw new RuntimeException(e);
} finally {
try {
if (fileInputStream != null) {
fileInputStream.close();
System.out.println("关闭输入流成功");
}
} catch (IOException e) {
System.out.println("关闭输入流失败");
throw new RuntimeException(e);
}
}
}
}
}