黑马程序员----IO流

来源:互联网 发布:查看数据库的存储过程 编辑:程序博客网 时间:2024/06/05 07:05

------<a href="http://www.itheima.com" target="blank">Java培训、Android培训、iOS培训、.Net培训</a>、期待与您交流! -------

IO流是用来处理数据的输入和输出的流,分为字节流和字符流,字节流可处理所有文件,字符流只能处理二进制的文件,字符流的处理效率高与字符流。以下是一些IO流常用的操作:

/** * 功能:演示IO流字节流的一些常用功能, * 以下代码包括 * 1、字节流读取文件的方法 * 2、字节流写入文件的方法 * 3、字节流复制文件的方法 * 4、字符流读取文件的方法 * 5、字符流写入文件的方法 * 6、字符流复制文件的方法 * 7、带缓冲功能的字符流复制文件的方法 *  */package myblog;import java.io.*;public class IoLiu {    public static void main(String []args){}    //字节流读取文件的方法public static void dqmothed(File f){byte []bytes=new byte[1024];int n=0;FileInputStream fis=null;try {fis=new FileInputStream(f);while((n=fis.read(bytes))!=-1){System.out.println(new String(bytes,0,n));}} catch (Exception e) {e.printStackTrace();}finally{try {fis.close();} catch (IOException e) {e.printStackTrace();}}}//字节流写入文件的方法public static void xrmothed(File f,String s){BufferedReader br=new BufferedReader(new InputStreamReader(System.in));int n=0;FileOutputStream  fos=null;try {fos=new FileOutputStream(f);fos.write(s.getBytes());} catch (Exception e) {e.printStackTrace();}finally{try {fos.close();} catch (IOException e) {e.printStackTrace();}}}//字节流复制的功能的方法public static void fzmothed(File f1,File f2){FileInputStream fis=null;FileOutputStream fos=null;try {fis=new FileInputStream(f1);fos=new FileOutputStream(f2);byte []bytes=new byte[1024];int n=0;while((n=fis.read(bytes))!=-1){fos.write(bytes, 0, n);}} catch (Exception e) {e.printStackTrace();}finally{try {fos.close();fis.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}//字符流读取的方法public static void zfldu(File f){FileReader fr=null;try {fr=new FileReader(f);char []c=new char[1024];int n=0;//记录读取的字符数while((n=fr.read(c))!=-1){String s=new String(c,0,n);System.out.println(s);}} catch (Exception e) {e.printStackTrace();}finally{try {fr.close();} catch (Exception e) {e.printStackTrace();}}}//字符流写入的方法public static void zflXie(File f,String s){FileWriter fw=null; try {fw=new FileWriter(f);fw.write(s);} catch (IOException e) {e.printStackTrace();}finally{try {fw.close();} catch (IOException e) {e.printStackTrace();}}}//字符流复制的方法public static void zflfz(File f1,File f2){FileReader fr=null;FileWriter fw=null;try {fr=new FileReader(f1);fw=new FileWriter(f2);char []c=new char[1024];int n=0;while((n=fr.read(c))!=-1){fw.write(c);}} catch (Exception e) {e.printStackTrace();}finally{try {fw.close();fr.close();} catch (IOException e) {e.printStackTrace();}}}//带缓冲功能的字符流复制方法public static void bufferZflfz(File f1,File f2){BufferedReader br=null;BufferedWriter bw=null;try {br=new BufferedReader(new FileReader(f1));bw=new BufferedWriter(new FileWriter(f2));char []c=new char[1024];int n=0;while((n=br.read(c))!=-1){bw.write(c, 0, n);}} catch (Exception e) {e.printStackTrace();} finally{try {bw.close();br.close();} catch (IOException e) {e.printStackTrace();}}}}


0 0