zoukankan      html  css  js  c++  java
  • FileInputStream、FileOutputStream的应用

    1. /*
    2. 复制一个图片:
    3. 思路:
    4. 1、用字节流读取对象和图片进行关联
    5. 2、用字节写入流创建一个文件图片,用于存储获取到的图片数据。
    6. 3、通过循环读取,完成数据的存储。
    7. 4、关闭资源
    8. */
    9. 1、二者操作的基本单位是字节byte。
      2、常用于读写图片、声音、影像文件。
      基本操作步骤:
      1、创建流对象
      2、调用流对象的功能read、write等
      3、关闭流对象

    10. 方法一:
      import java.io.*;
      class  CopyMp3
      {
      	public static void main(String[] args) 
      	{
      		CopyPic();
      	}
      
      	public static void CopyPic()
      	{
      		FileInputStream fileInput = null;
      		FileOutputStream fileOutput = null;
      		try
      		{
      			fileInput = new FileInputStream("C:\1.jpg");
      			fileOutput = new FileOutputStream("C:\2.Jpg");
      			byte [] bt = new byte[1024];
      			int len = 0;
      			while((len = fileInput.read()) != -1)
      			{
      				fileOutput.write(len);
      			}
      		}
      		catch (IOException ex)
      		{
      			ex.printStackTrace();
      		}
      		finally
      		{
      			try
      			{
      				if(fileInput != null)
      				{
      					fileInput.close();
      				}
      				if(fileOutput != null)
      				{
      					fileOutput.close();
      				}
      			}
      			catch (IOException ex)
      			{
      				ex.printStackTrace();
      			}
      		}
      	}
      }
      
      此时图片2和图片1的属性完全一样。

      方法二:速度比较快,但是图片多了1KB,可能就是由于数组的使用。
    11. import java.io.*;
      class  CopyMp3
      {
      	public static void main(String[] args) 
      	{
      		CopyPic();
      	}
      
      	public static void CopyPic()
      	{
      		FileInputStream fileInput = null;
      		FileOutputStream fileOutput = null;
      		try
      		{
      			fileInput = new FileInputStream("C:\1.jpg");
      			fileOutput = new FileOutputStream("C:\2.Jpg");
      			byte [] bt = new byte[1024];
      			int len = 0;
      			while((len = fileInput.read(bt)) != -1)
      			{
      				fileOutput.write(bt);
      			}
      		}
      		catch (IOException ex)
      		{
      			ex.printStackTrace();
      		}
      		finally
      		{
      			try
      			{
      				if(fileInput != null)
      				{
      					fileInput.close();
      				}
      				if(fileOutput != null)
      				{
      					fileOutput.close();
      				}
      			}
      			catch (IOException ex)
      			{
      				ex.printStackTrace();
      			}
      		}
      	}
      }
      


  • 相关阅读:
    微博转发的内容如何实现点击人名跳转到个人主页
    解决json_encode中文UNICODE转码问题
    ***git自动化部署总结
    **Git本地仓库图解
    我 Git 命令列表 (1)【转】
    Git
    git pull使用【转】
    git merge简介【转】
    获得内核函数地址的四种方法
    【笔记】一些linux实用函数技巧【原创】
  • 原文地址:https://www.cnblogs.com/dengshiwei/p/4258467.html
Copyright © 2011-2022 走看看