您的位置:首页 > 职场人生

《黑马程序员》java IO流 基本操作(2)

2013-11-22 19:05 357 查看
--------------------- <a href="http://edu.csdn.net"target="blank">ASP.Net+Android+IOS开发</a>、<a
href="http://edu.csdn.net"target="blank">.Net培训</a>、期待与您交流! ----------------------

 ----------- android培训java培训、java学习型技术博客、期待与您交流! ------------

 
字节流对象可以操作各类数据文件,如拍图片和mp3

 文件输入输出

 
   首先够着一个FielputStream,所以关联的文件必须存在而且可读

 
      FileInputStraenm fid=new FileInputStream("asassa.mp3")

 
  构造一个FileOutputStream ,如果文件存在,就覆盖它

 
      FileOutputStream fos=new FileOutputStream("ada.mp3")
    如果想要追加方式写文件,就需要额外加一个参数
 
    FileOutputStream fos=new FileOutputStream("ada.mp3",
true)

 
  临时存放文件数据用字节数组

 
      byte[] buf=new byte[1024]

实例1
        复制文件

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Copytu {

/**
* 1.用字节读取流 和图片关联
* 2.用字节写入流对象创建一个图片温江,用于存储取到的图片数据
* 3.通过讯黄读写,完成数据的存储
* 关闭资源
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
FileOutputStream fos=null;
FileInputStream fis=null;
try
{
fos=new FileOutputStream("asa.bmp");
fis=new FileInputStream("ada.bmp");
byte[] buf=new byte[1024];
int len=0;
while((len=fis.read(buf))!=-1)
{
fos.write(buf,0,len);
}
}
catch(IOException e)
{
throw new RuntimeException("复制失败");

}
finally
{
try
{
if(fis!=null)
fis.close();
}
catch(IOException e)
{
throw new RuntimeException("读取关闭失败");

}
try
{
if(fos!=null)
fos.close();
}
catch(IOException e)
{
throw new RuntimeException("写入关闭失败");

}
}

}

}
实例2  

    将一个MP3文件(Beyond.mp3)以追加的方式续写到别一个文件(my.mp3),实例中使用了字节输入输出缓冲流,程序编译成功,我运行了三次,最后my.mp3的容量正好是beyond.mp3的三倍,播放MP3也反复播放了三遍

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Mp3Copy {

/**我将beyond.mp3文件以追加的形式存入到12.mp3中
* @param args
* @throws FileNotFoundException
*/
public  static void copy1() throws FileNotFoundException
{   BufferedOutputStream bos=null;
BufferedInputStream bis=null;
try{
bos=new BufferedOutputStream(new FileOutputStream("my.mp3",true));

bis=new BufferedInputStream(new FileInputStream("Beyond.mp3"));
int bt=0;
while((bt=bis.read())!=-1)
{
bos.write(bt);
}
}
catch(IOException e)
{
throw new RuntimeException("复制失败");
}
finally
{
try
{
if(bis!=null)
bis.close();
}
catch(IOException e)
{
throw new RuntimeException("文件读取失败 ");
}
try
{
if(bos!=null)
bos.close();
}
catch(IOException e)
{
throw new RuntimeException(" 复制 失败 ");
}
}
System.out.print("复制成功");

}
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
//通过自己留的缓冲区完成复制
copy1();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: