Java上路16-I/O

来源:互联网 发布:淘宝开店运费怎么弄 编辑:程序博客网 时间:2024/06/05 00:54


        IO流用来处理设备之间的数据传输,Java对数据的操作是通过流的方式,Java用于操作的流的对象都在IO包中。流按操作数据分为字节流和字符流,流按流向分为输入流和输出流。

        字符流:FileReader、FileWriter,BufferedReader、BufferedWriter 

        字节流:InputStream、OutputStream,FileInputStream、FileOutputStream

 

一. FileWriter:

       Writer下.OutputStreamWriter的一个子类,用来写入字符文件的便捷类。此类的构造方法假定默认字符编码和默认字节缓冲区大小都是可接受的,用于写入字符流。

import java.io.FileWriter;import java.io.IOException; class IoDemo{       public static void main(String[] args)       {              FileWriter fw=null;              try              {                     //在指定目录创建文件,如果已有同名文件将被覆盖                     fw=new FileWriter("demo.txt");                      //调用write方法写字符串到流                     fw.write("HelloIO");                      //刷新缓冲区,使数据进入目的地                     fw.flush();                      fw.write(" Sogood");                     fw.flush();              }              catch (IOException e)              {                     System.out.println(e.toString());              }              finally              {                     try                     {                            if (fw!=null)                            {                                   //刷新缓冲区后关闭流                                   fw.close();                            }                     }                     catch (IOException e)                     {                            System.out.println(e.toString());                     }              }       }}


       如果构造函数中加入第二个参数true,将不覆盖已有的文件,而是续写操作。

 

二. FileReader:

       Reader中io.InputStreamReader的子类,用来读取字符文件的便捷类。此类的构造方法假定默认字符编码和默认字节缓冲区大小都是适当的。

import java.io.FileReader;import java.io.IOException; class IoDemo{       public static void main(String[] args)       {              FileReader fr=null;              try              {                     //创建一个文件读取流对象,指定的文件必须存在                     fr=new FileReader("demo.txt");/*                     //连续读取单个字符                     int ch=0;                     while((ch=fr.read())!=-1)                     {                            System.out.print((char)ch);                     }*/                     //每次读取多个字符                     char[] buf=new char[1024];                     int num=0;                     while((num=fr.read(buf))!=-1)                     {                            System.out.println("num"+": "+new String(buf, 0, num));                     }              }              catch (IOException e)              {                     System.out.println(e.toString());              }              finally              {                     try                     {                            if (fr!=null)                            {                                   fr.close();                                   System.out.println("fr.close();");                            }                     }                     catch (IOException e)                     {                            System.out.println(e.toString());                     }              }       }}


三. 文件复制演示:

import java.io.*; class IoDemo{       public static void main(String[] args)throws IOException       {              copy2();       }/*       public static void copy1() throws IOException       {              //创建目标文件              FileWriter fw=new FileWriter("NewDemo.txt");               //读取源文件              FileReader fr=new FileReader("Demo.txt");               int ch=0;              while ((ch=fr.read())!=-1)              {                     fw.write(ch);                     fw.flush();              }              fw.close();              fr.close();       }*/       public static void copy2() throws IOException       {              FileWriter fw=new FileWriter("NewDemo.txt");              FileReader fr=new FileReader("Demo.txt");               char[] buf=new char[1024];               int len=0;              while ((len=fr.read(buf))!=-1)              {                     fw.write(buf, 0, len);              }              fw.close();              fr.close();       }}


四. BufferedWriter & BufferedReader:

// BufferedWriter将文本写入字符输出流,缓冲各个字符,从而提供单个字符、数组和字符串的高效写入。创建缓冲区前,必须先有流对象。import java.io.*; class BufferedDemo{       public static void main(String[] args)throws IOException       {              //字符写入到文件类              FileWriter fw=new FileWriter("demo.txt");              //字符输出到流写入文本类              BufferedWriter bufw=new BufferedWriter(fw);              //在流中写入内容              bufw.write("HelloBufferedWriter");              bufw.write(" Je amievou");              bufw.newLine();   //换行              bufw.write("My love");              bufw.flush();  //刷新该流的缓冲,写入文本              bufw.close(); //关闭此流,但要先刷新它。在关闭该流之后,再调用 write() 或flush() 将导致抛出 IOException               //读取文件的字符类              FileReader fr=new FileReader("demo.txt");              //读取文本字符输入流类              BufferedReader bufr=new BufferedReader(fr);              String line=null;              //readLine读取一行,但不返还换行符              while ((line=bufr.readLine())!=null)              {                     System.out.println(line);              }              //关闭流,释放资源              bufr.close();               //Runtime rt=Runtime.getRuntime();              //Process p=rt.exec("notepaddemo.txt");       }}


五. 复制文件演示:

import java.io.*; class BufferedDemo{       public static void main(String[] args) throws IOException       {              BufferedReader bufr=null;              BufferedWriter bufw=null;               try              {                     bufr=new BufferedReader(new FileReader("demo.txt"));                     bufw=new BufferedWriter(new FileWriter("NewDemo.txt"));                      Stringline = null;                             while((line = bufr.readLine())!=null)                            {                                   bufw.write(line);                                   bufw.newLine();                                   bufw.flush();                            }              }              catch(IOException e)              {                     throw new RuntimeException("读取失败");              }              finally              {                     try                     {                            if(bufr!=null)                                   bufr.close();                     }                     catch(IOException e)                     {                            throw new RuntimeException("读取关闭失败");                     }                      try                     {                            if(bufw!=null)                                   bufw.close();                     }                     catch(IOException e)                     {                            throw new RuntimeException("写入关闭失败");                     }              }       }}


六. 自定义的缓冲类

class MyBufferedReader{       private FileReader fr;       MyBufferedReader(FileReader r)       {              fr=r;       }       //每次读取一行       public String myReadLine() throws IOException       {              //定义一个临时容器,原BufferReader封装的是字符数组,此处使用StringBuilder              StringBuilder sb=new StringBuilder();              int ch=0;              while((ch=fr.read())!=-1)              {                     if(ch=='\r')                     {                            continue;                     }                     if(ch=='\n')                     {                            return sb.toString();                     }                     else                     {                            sb.append((char)ch);                     }              }              if(sb.length()!=0)              {                     return sb.toString();              }              return null;       }        public void myClose() throws IOException       {              fr.close();       }}    


七. 装饰设计模式:

/*装饰设计模式:当想要对已有的对象进行功能增强的时候,可以定义类,将已有的对象传入,基于已有的功能,并提供加强功能。那么自定义的类成为装饰类。装饰类通常会通过构造方法接收被装饰的对象。并基于被装饰的对象的功能进一步增强。*/ import java.io.*; class Person{       public void chifan()       {              System.out.println("吃饭");       }} class SuperPerson{       private Person p;       SuperPerson(Person p)       {              this.p=p;       }        public void superChifan()       {              System.out.println("甜点");              p.chifan();              System.out.println("咖啡");       }} class BufferedDemo{       public static void main(String[] args) throws IOException       {               Person p=new Person();              p.chifan();               SuperPerson sp=new SuperPerson(p);              sp.superChifan();       }}


八. LineNumberReader:

跟踪行号的缓冲字符输入流。此类定义了方法 setLineNumber(int) 和 getLineNumber(),它们可分别用于设置和获取当前行号。

import java.io.*; class BufferedDemo{       public static void main(String[] args) throws IOException       {              FileReader fr=new FileReader("demo.txt");               LineNumberReader lnr=new LineNumberReader(fr);               String line=null;              lnr.setLineNumber(100);              while((line=lnr.readLine())!=null)              {                     System.out.println(lnr.getLineNumber()+":"+line);              }              lnr.close();       }}


       模拟LineNumberReader:

import java.io.*; class MyLineNumberReader{       private Reader r;       private int lineNumber;        MyLineNumberReader(Reader r)       {              this.r=r;       }        public String myReadLine() throws IOException       {              lineNumber++;              StringBuilder sb=new StringBuilder();              intch=0;              while((ch=r.read())!=-1)              {                     if(ch=='\r')                     {                            continue;                     }                     if(ch=='\n')                     {                            return sb.toString();                     }                     else                     {                            sb.append((char)ch);                     }              }              if(sb.length()!=0)              {                     return sb.toString();              }              return null;       }        public void setLineNumber(int lineNumber)       {              this.lineNumber=lineNumber;       }        public int getLineNumber()       {              return lineNumber;       }        public void myClose() throws IOException       {              r.close();       }} class BufferedDemo{       public static void main(String[] args) throws IOException       {              FileReader fr=new FileReader("demo.txt");               MyLineNumberReader mlnr=new MyLineNumberReader(fr);               String line=null;              mlnr.setLineNumber(100);              while((line=mlnr.myReadLine())!=null)              {                     System.out.println(mlnr.getLineNumber()+":"+line);              }              mlnr.myClose();       }}


九. FileInputStream & FileOutputStream:

       字节读取流和字节写入流,可以对图片及视频等文件复制拷贝。

import java.io.*; class BufferedDemo{       public static void main(String[] args) throws IOException       {              writeFile();              readFile_1();              readFile_2();              readFile_3();       }        public static void readFile_3() throws IOException       {              //通过打开一个到实际文件的连接来创建一个输入字节流              FileInputStream fis=new FileInputStream("demo.txt");              byte[] buf=new byte[fis.available()]; //定义一个刚刚好的缓冲区              fis.read(buf);              System.out.println(new String(buf));              fis.close();       }        public static void readFile_2() throws IOException       {              FileInputStream fis=new FileInputStream("demo.txt");              byte[] buf=new byte[1024];      //     定义指定大小的缓冲区              intlen=0;              while((len=fis.read(buf))!=-1)              {                     System.out.println(new String(buf, 0, len));              }              fis.close();       }        public static void readFile_1() throws IOException       {              FileInputStream fis=new FileInputStream("demo.txt");              int ch=0;              //单个字符循环读取              while ((ch=fis.read())!=-1)              {                     System.out.println((char)ch);              }              fis.close();       }        public static void writeFile() throws IOException       {              //创建一个向指定 File 对象表示的文件中写入数据的文件输出流              FileOutputStream fos=new FileOutputStream("demo.txt");              fos.write("这是新的文字内容2012-11-27".getBytes());              fos.close();       }}



拷贝图片示例:

import java.io.*; class BufferedDemo{       public static void main(String[] args)       {              FileOutputStream fos=null;              FileInputStream fis=null;               try              {                     fis=new FileInputStream("E:\\test.jpg"); //源文件                     fos=new FileOutputStream("E:\\newtest.jpg");     //新文件                      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("写入关闭失败");                     }              }       }}


拷贝MP3文件示例:

import java.io.*; class MyBufferedInputStream{       private InputStream in;        private byte[] buf=new byte[1024*4];       private int pos=0, count=0;        MyBufferedInputStream(InputStream in)       {              this.in=in;       }        //每次读取一个字节       public int myRead() throws IOException       {              if(count==0)              {                     //通过in对象读取硬盘上的数据存储在buf                     count = in.read(buf);                      if(count<0)                            return -1;                      pos=0;                     byte b=buf[pos];                      count--;                     pos++;                     return b&255;      //类型提升,避免-1出现              }              else if(count>0)              {                     byte b=buf[pos];                      count--;                     pos++;                     return b&255;              }              return -1;       }        public void myClose() throws IOException       {              in.close();       }} class IoDemo{       public static void main (String [] args)throws IOException       {              MyBufferedInputStream bufis=new MyBufferedInputStream(new FileInputStream("E:/demo.mp3"));              BufferedOutputStream bufos=new BufferedOutputStream(new FileOutputStream("E:/newdemo.mp3"));               int by=0;              while ((by=bufis.myRead())!=-1)              {                     bufos.write(by);              }              bufos.close();              bufis.myClose();       }}

---------------------**---------------------------

附加:

        Editplus编译运行java程序设置:





原创粉丝点击