字节流可以操作非文本数据,方法原理与字符流的类似,只是字符流用的是字符数组,字节流用的是字节数组。
InputStream子类FileInputStream读文件
OutputStream子类FileOutputStream写文件
一、FileOutputStream写文件
FileOutputStream fos = new FileOutputStream("fos.txt");
fos.write("abdskaf".getBytes()); //getBytes()将字符串变成字节数组
//不需要刷新,字节流的字节可以单个操作,有一个字节就处理一个字节,对字节最小单位的操作,不需要做转换。
//而字符流,例如中文,需要读取两个字节,然后查编码表,最后处理,所以需要刷新流资源。
fos.close(); //这个需要写,虽然不具有刷新的功能,但是要关闭流资源
二、FileInputStream读文件
//读取文件方式一:一个一个地读
public static void readFile_1() throws IOException{
FileInputStream fis = new FileInputStream("fos.txt");
int ch =0;
while( ( ch = fis.read() ) !=-1 ){
System.out.println( (char)ch );
}
fis.close();
}
//读取文件方式二:
public static void readFile_2() throws IOException{
FileInputStream fis = new FileInputStream("fos.txt");
byte[] buf = new byte[1024];
int len=0;
while( ( len = fis.read(buf) ) !=-1 ){
System.out.println( new String(buf,0,len) );
}
fis.close();
}
//读取文件方式三:字节流特有的方法aviable().
public static void readFile_3() throws IOException{
FileInputStream fis = new FileInputStream("fos.txt");
int num = fis.aviable();
byte[] buf = new byte[num]; //定义一个刚刚好的缓冲区,不用再循环了
fis.read(buf);
System.out.println( new String(buf) );
fis.close();
}
第三种读取方式的弊端,如果处理的是一个很大的媒体对象,需要很大的内存,不建议使用创建一个刚刚好的缓冲区。
三,图片的拷贝
1.用字节读取流对象和图片关联
2.用字节写入流对象创建一个图片文件,用于存储获取到的图片数据
3.通过循环读写,完成数据的存储。
4.关闭资源
public static boid main(String[] args){
FileOutputStream fos = null;
FileInputStream fis = null;
try{
fos = new FileOutputStream();
fis = new FileInputStream();
byte[] buf = new byte[1024];
int len = 0;
while( (len = fis.read() )!=-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("写入关闭失败");
}
}
}
四、通过字节流的缓冲区完成复制BufferedInputStream 、BufferedOutputStream
BufferedInputStream bufis = new BufferedInputStream(newFileInputStream("c:\\0.mp3"));
BufferedOutputStream bufos = new BufferedOutputStream(newFileOutputStream("c:\\1.mp3"));
int by = 0;
while( by = bufis.read() !=-1 ){
bufos.write(by);
}
bufos.close();
bufis.close();
IO流的字节流InputStream、OutputStream
于 2014-09-10 09:59:01 首次发布