最近有用带io流读取图片! 不过好久没用了居然发现不会写。 最后费了很大了功夫才弄好! 才发现居然很简单!
所以我还是记一下!并且分享给大家一起学习一起进步
io流分为两大类,字节流和字符流。
字节流:OutputStream、InputStream
字符流:Writer、Reader
所有的文件在硬盘或在传输时都是以字节的方式进行的,包括图片等都是按字节的方式存储的,而字符是只有在内存中才会形成,所以开发中字节流使用比较广泛
可以参考java api文档
public class FileOutputStream extends OutputStream
文件输出流是用于将数据写入 File 或 FileDescriptor
的输出流。
--这个是取图片
BufferedInputStream bis=mediaFile.getFileStream();try {BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:\\dest.png")); int i; do{ i = bis.read(); if(i != -1){ bos.write(i); } }while(i != -1); bos.close();} catch (FileNotFoundException e) {// TODO 自动生成的 catch 块e.printStackTrace();} catch (IOException e) {// TODO 自动生成的 catch 块e.printStackTrace();}
package com.xx;import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.io.Writer;public class 文本文件读写 {/*** @param args* @throws IOException */public static void main(String[] args) throws IOException {// TODO Auto-generated method stub// 读FileInputStream is=new FileInputStream("c:/xxx.txt");Reader rd=new InputStreamReader(is,"utf-8");BufferedReader br=new BufferedReader(rd);//写FileOutputStream os=new FileOutputStream("c:/xxx.txt",true); //true 追加Writer wr=new OutputStreamWriter(os,"utf-8");BufferedWriter bw=new BufferedWriter(wr);String line=br.readLine();while(line!=null){System.out.println(line);bw.write(line+"\r\n");line=br.readLine();}bw.close();wr.close();os.close();br.close();rd.close();is.close();}}
package com.xxx;import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream;public class 二进制文件读写 {/*** @param args* @throws Exception */public static void main(String[] args) throws Exception {// TODO Auto-generated method stubbyte[] b=new byte[1024]; //自已写的 缓冲InputStream is=new FileInputStream("c:/xxxx.mp3");OutputStream os=new FileOutputStream("c:/tt.mp3");int n=is.read(b); // n 实际 读到数组 里面的个数 while(n!=-1){System.out.println(n);os.write(b, 0, n);n=is.read(b);}os.close();is.close();}}