public static void copyImage() throws IOException
{
//找到目标文件
File inFile = new File("D:\\1.jpg");
File destFile = new File("E:\\1.jpg");
//建立数据的输入输出通道
FileInputStream fileInputStream = new FileInputStream(inFile);
FileOutputStream fileOutputStream = new FileOutputStream(destFile); //追加数据....
//每新创建一个FileOutputStream的时候,默认情况下FileOutputStream 的指针是指向了文件的开始的位置。 每写出一次,指向都会出现相应移动。
//建立缓冲数据,边读边写
byte[] buf = new byte[1024];
int length = 0 ;
while((length = fileInputStream.read(buf))!=-1){ //不限丢人的输出来第一次我写的时候,read(buf)中的参数buf被我写丢了,好久才发现的错误
fileOutputStream.write(buf,0,length); //写出很多次数据,所以就必须要追加。
}
//关闭资源 原则: 先开后关,后开先关。
fileOutputStream.close();
fileInputStream.close();
}
//输入字节流的异常处理。
public static void readTest()
{
FileInputStream fileInputStream = null;
try
{
//找到目标文件
File file = new File("D:\\b.txt");
//建立数据输入通道
fileInputStream = new FileInputStream(file);
//建立缓冲数组,读取数据
byte[] buf = new byte[1024];
int length = 0;
while((length = fileInputStream.read(buf))!=-1)
{
System.out.println(new String(buf, 0, length));
}
}catch(IOException e){
//处理读出异常的代码 首先要阻止后面的代码执行,而且还要通知调用者出错了... throw
// throw e; //我们一般不会这样做,或者上面函数声明处使用throws 这个样子需要强迫调用者 trycatch
throw new RuntimeException(e); //将IOException包装一层,然后再抛出,这样子做的目的是为了让调用者更加的方便,运行时异常不需要trycatch包围。 }finally
{
//关闭资源
try
{
if(fileInputStream!=null){ //关闭之前应当先检查,万一之前通道就没有建立成功
fileInputStream.close();//这一块想想必须应当放到finally块重,为什么,因为如果碰到了异常,总不能不把资源释放吧
System.out.println("关闭资源成功过了");
}
} catch (IOException e)
{
System.out.println("关闭资源失败");
throw new RuntimeException(e);
} }
}
//拷贝图片是有输入流有输出流 综合在一块做异常处理,值得玩味。
public static void copyImage()
{
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
//找到目标文件
try
{
File inFile = new File("D:\\1.jpg");
File outFile = new File("E:\\1.jpg"); //建立输入输出通道
fileInputStream = new FileInputStream(inFile);
fileOutputStream = new FileOutputStream(outFile); //缓冲数组
byte[] buf = new byte[1024];
int length = 0;
while((length = fileInputStream.read(buf))!=-1)
{
fileOutputStream.write(buf, 0, length);
}
}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);
}
}
}
}