小强的练级之路

<!--[if !supportLists]-->一、<!--[endif]-->输入输出字节流

<!--[if !supportLists]-->1、<!--[endif]-->文件字节输入字节流

publicstaticvoid readByStream() throws Exception {

 

       File file = new File("D:/1.jpg");

       FileInputStream inputStream = new FileInputStream(file);

 

       byte buf[] = newbyte[1024];

       int len = 0;

 

       while ((len = inputStream.read(buf)) != -1) {

           System.out.print(new String(buf, 0, len));

       }

}

<!--[if !supportLists]-->2、<!--[endif]-->文件字节输出字符流

publicstaticvoid copyImg() throws IOException {

       // 读取图片

       File iFile = new File("f:/a.jpg");

       InputStream inputStream = new FileInputStream(iFile);

       // 拷贝

       File oFile = new File("d:/b.jpg");

       OutputStream outputStream = new FileOutputStream(oFile);

      

       byte[] buf = newbyte[1024];  //缓冲数组

       int len = 0;

 

       while((len = inputStream.read(buf)) != -1) {

           outputStream.write(buf, 0, len);

       }

}

<!--[if !supportLists]-->3、<!--[endif]-->拷贝图片案例

publicstaticvoid copyImg() throws IOException {

       // 读取图片

       File iFile = new File("f:/a.jpg");

       InputStream inputStream = new FileInputStream(iFile);

       // 拷贝

       File oFile = new File("d:/b.jpg");

       OutputStream outputStream = new FileOutputStream(oFile);

      

       byte[] buf = newbyte[1024];  //缓冲数组

       int len = 0;

 

       while((len = inputStream.read(buf)) != -1) {

           outputStream.write(buf, 0, len);

       }

}

二、文件异常处理方法

publicstaticvoid readFile(){

       FileInputStream fis = null;

       try{

           //创建文件

           File file = new File("e:/a.txt");

           //创建输入通道

           fis = new FileInputStream(file);

           //创建缓冲数组

           byte[] buf = newbyte[1024];

           int len = 0;

           //读取文件

           while((len = fis.read(buf)) != -1) {

              System.out.println(new String(buf,0,len));

           }

       }catch(IOException e) {

           //处理文件异常信息方式

           thrownew RuntimeException(e);

       }finally{

           if(fis != null) {

              try {

                  fis.close();

              } catch (IOException e) {

                  thrownew RuntimeException(e);

              }

           }

       }

}

<!--[if !supportLists]-->三、   <!--[endif]-->缓冲输入输出字节流

1、缓冲输入字节流

缓冲输入流:

     -----------|InputStream

     -------------------|FileInputStream

     -------------------|BufferedInputStream

     注意事项:1BufferedInputStream 关闭的时候会连带构造缓冲流时候传入的输入流一起关闭。

              2、缓冲流不是文件流!

              3、缓冲流实际上是内部创建一个大小为8K的缓冲数组。实际上效率不如自己手动创建一个缓冲数组。

 

2、缓冲输出字节流

缓冲输出流:

     -----------|OutputStream

     -------------------|FileOutputStream

     -------------------|BufferedOutputStream

     注意事项: BufferedOutputStream 实际上是输出到缓冲数组中,如果想让其输出到硬盘中两种方式:

               1、缓冲数组装满了,自动释放到硬盘。

               2、手动调用flush方法和close方法(内部先调用了flush方法)

 

3、案例拷贝图片

publicstaticvoid copyImage() throws IOException {

       //输入缓冲流的创建

       File iFile = new File("d:/1.jpg");

       FileInputStream fis = new FileInputStream(iFile);

       BufferedInputStream bis = new BufferedInputStream(fis);

       //输出缓冲流的创建

       File oFile = new File("f:/2.jpg");

        FileOutputStream fos = new FileOutputStream(oFile);

       BufferedOutputStream bos = new BufferedOutputStream(fos);

      

       //读写图片操作

       int content = 0;

       while((content = bis.read()) != -1) {

           bos.write(content);

       }

       bos.close();

       bis.close();

}

<!--[if !supportLists]-->四、   <!--[endif]-->输入输出字符流

<!--[if !supportLists]-->1、<!--[endif]-->输入字符流

/**

----------|Reader

-----------------|FileReader

    输入字符流:

       和字节流读取的过程非常类似。

 */

publicstaticvoid testReader() throws Exception {

       //目标文件

       File file = new File("f:/a.txt");

       //打开通道

       FileReader fr = new FileReader(file);

       //读取文件

       char[] buf = newchar[1024];

       int len = 0;

       while((len = fr.read(buf)) != -1) {

           System.out.println(new String(buf,0,len));

       }

       //关闭通道

       fr.close();

}

 

<!--[if !supportLists]-->2、<!--[endif]-->输出字符流

/**

----------|Writer

-----------------|FileWriter

    输出字符流:

       1.每次向文件写出内容的时候,都会首先清空文件的内容,如果想要追加需要在使用FileWriter(File,true);

       2.如果FileWriter没有关闭为什么程序内容写不出去。因为Writer类自己内部维护了一个存放数据的数组。

           a.当数组内容满了的时候可以被释放。

           b.close()或者flush()方法。

 */

publicstaticvoid testWriter() throws Exception {

       //目标文件

       File file = new File("f:/a.txt");

       //打开通道

       FileWriter fw = new FileWriter(file);

       //写出

       String data = "奋斗By小强";

       fw.write(data);

       //关闭通道

       fw.close();

}

案例一、拷贝一个.java文件

// 1、拷贝一个.java文件

    publicstaticvoid copyJavaFile() throws Exception {

 

       // 输入通道

       File iFile = new File("d:/Demo1.java");

       FileReader fr = new FileReader(iFile);

 

       // 输出通道

       File oFile = new File("f:/test.java");

       FileWriter fw = new FileWriter(oFile);

 

       // 读写操作

       char[] buf = newchar[1024];

       int len = 0;

       while ((len = fr.read(buf)) != -1) {

           fw.write(buf, 0, len);

       }

       // 关闭资源

       fw.close();

       fr.close();

    }

 

案例二、拷贝一个图片

为什么会出现拷贝的图片无法打开?

<!--[if gte vml 1]><v:shapetype id="_x0000_t75" coordsize="21600,21600" o:spt="75" o:preferrelative="t" path="m@4@5l@4@11@9@11@9@5xe" filled="f" stroked="f"> <v:stroke joinstyle="miter"/> <v:formulas> <v:f eqn="if lineDrawn pixelLineWidth 0"/> <v:f eqn="sum @0 1 0"/> <v:f eqn="sum 0 0 @1"/> <v:f eqn="prod @2 1 2"/> <v:f eqn="prod @3 21600 pixelWidth"/> <v:f eqn="prod @3 21600 pixelHeight"/> <v:f eqn="sum @0 0 1"/> <v:f eqn="prod @6 1 2"/> <v:f eqn="prod @7 21600 pixelWidth"/> <v:f eqn="sum @8 21600 0"/> <v:f eqn="prod @7 21600 pixelHeight"/> <v:f eqn="sum @10 21600 0"/> </v:formulas> <v:path o:extrusionok="f" gradientshapeok="t" o:connecttype="rect"/> <o:lock v:ext="edit" aspectratio="t"/> </v:shapetype><v:shape id="图片_x0020_1" o:spid="_x0000_i1025" type="#_x0000_t75" style='width:415.5pt;height:179.25pt;visibility:visible;mso-wrap-style:square'> <v:imagedata src="file:///C:\Users\ADMINI~1\AppData\Local\Temp\msohtmlclip1\01\clip_image001.png" o:title=""/> </v:shape><![endif]--><!--[if !vml]--><!--[endif]-->

总结、字节流和字符流的使用场景

何时使用字符流?如果操作文本数据,这时候应该使用字符流。

何时使用字节流?如果操作非文本数据,这时候应该使用字节流。(图片、视频、音频、word文档)

 

五、缓冲输入输出字符流

<!--[if !supportLists]-->1、<!--[endif]-->缓冲输入字符流

publicstaticvoid testBufferedReader() throws Exception {

       //目标文件

       File file = new File("d:/Demo1.java");

       //文件通道

       FileReader fr = new FileReader(file);

       //缓冲

       BufferedReader br = new BufferedReader(fr);

       //写入操作

       String line = null;

       while((line = br.readLine()) != null) {  //拓展的readLine方法。

           System.out.println(line);

       }

       //关闭资源

       br.close();

    }

 

<!--[if !supportLists]-->2、<!--[endif]-->缓冲输出字符流

publicstaticvoid testBufferedWriter() throws Exception {

       //目标文件

       File file = new File("f:/date.txt");

       //通道

       FileWriter fw = new FileWriter(file,true);

       //缓冲

       BufferedWriter bw = new BufferedWriter(fw);

       //写出操作

       String date = "哈哈,今天天气真好!~";

       bw.newLine();  //拓展方法

       bw.write(date);

       //关闭

       bw.close();

    }

六、序列流对象

/**

 电台:

       马丁·路德·金:不断努力,梦想无法实现。

      《时间长廊》:也许今天无法实现,明天也不能实现,但是最重要的是它在你心里,你永远有目标为之奋斗。

  --------------------|序列流

           需求一:合并两个文件

           需求二:合并两个以上的文件(VectorArrayList)

           需求三:切割一个MP3文件、再合并

 */

//需求一:合并两个文件

    publicstaticvoid merge1() throws Exception {

      

       File inFile1 = new File("f:/1.txt");

       File inFile2 = new File("f:/2.txt");

      

       FileOutputStream fos = new FileOutputStream(new File("f:/合并.txt"));

       FileInputStream fis1 = new FileInputStream(inFile1);

       FileInputStream fis2 = new FileInputStream(inFile2);

      

       SequenceInputStream sis = new SequenceInputStream(fis1, fis2);

      

       byte[] buf = newbyte[1024];

       int len = 0;

       while((len = sis.read(buf)) != -1) {

           fos.write(buf,0,len);

       }

       sis.close();

       fos.close();

    }

//需求二:合并两个以上的文件(Vector)

    publicstaticvoid merge2() throws Exception {

       File inFile1 = new File("f:/1.txt");

       File inFile2 = new File("f:/2.txt");

       File inFile3 = new File("f:/3.txt");

   

       FileOutputStream fos = new FileOutputStream(new File("f:/合并.txt"));

       FileInputStream fis1 = new FileInputStream(inFile1);

       FileInputStream fis2 = new FileInputStream(inFile2);

       FileInputStream fis3 = new FileInputStream(inFile3);

      

       Vector<FileInputStream> v = new Vector<FileInputStream>();

       v.add(fis1);

       v.add(fis2);

       v.add(fis3);

       Enumeration<FileInputStream> e = v.elements();

      

       SequenceInputStream sis = new SequenceInputStream(e);

      

       byte[] buf = newbyte[1024];

       int len = 0;

      

       while((len = sis.read(buf)) != -1) {

           fos.write(buf,0,len);

       }

       sis.close();

       fos.close();

    }

//需求二:合并两个以上的文件(ArrayList)

    publicstaticvoid merge3() throws Exception {

       File inFile1 = new File("f:/1.txt");

       File inFile2 = new File("f:/2.txt");

       File inFile3 = new File("f:/3.txt");

   

       FileOutputStream fos = new FileOutputStream(new File("f:/合并.txt"));

       FileInputStream fis1 = new FileInputStream(inFile1);

       FileInputStream fis2 = new FileInputStream(inFile2);

       FileInputStream fis3 = new FileInputStream(inFile3);

      

       List<FileInputStream> list = new ArrayList<FileInputStream>();

       list.add(fis1);

       list.add(fis2);

       list.add(fis3);

       final Iterator<FileInputStream> it = list.iterator();

       //匿名内部类

       SequenceInputStream sis = new SequenceInputStream(new Enumeration<FileInputStream>() {

 

           publicboolean hasMoreElements() {

              return it.hasNext();

           }

 

           public FileInputStream nextElement() {

              return it.next();

           }

       });

      

       byte[] buf = newbyte[1024];

       int len = 0;

      

       while((len = sis.read(buf)) != -1) {

           fos.write(buf,0,len);

       }

       sis.close();

       fos.close();

    }

    //需求三:切割一个MP3文件

    publicstaticvoid merge4() throws Exception {

       //1.找到目标文件

        File file = new File("F:/a.mp3");

       //2.创建文件通道

       FileInputStream fis = new FileInputStream(file);

      

       byte[] buf = newbyte[1024*1024*3];

       int len = 0;

       int count = 1;

       FileOutputStream fos = null;

       while((len = fis.read(buf)) != -1) {

           fos = new FileOutputStream(new File("F:/music/"+ count + ".mp3"));

           fos.write(buf,0,len);

           count++;

           fos.close();

       }

       fis.close();

    }

//需求三:合并

    publicstaticvoid merge5() throws Exception {

       File file = new File("F:/music");

       File[] listFiles = file.listFiles();

      

       File outFile = new File("F:/合并.mp3");

       FileOutputStream fos = new FileOutputStream(outFile);

      

       Vector<FileInputStream> v = new Vector<FileInputStream>();

   

       for(int i=0; i<listFiles.length; i++) {

           if(listFiles[i].getName().endsWith(".mp3")) {

              v.add(new FileInputStream(listFiles[i]));

           }

       }

       Enumeration<FileInputStream> e = v.elements();

      

       SequenceInputStream sis = new SequenceInputStream(e);

      

       byte[] buf = newbyte[1024];

       int len = 0;

      

       while((len = sis.read(buf)) != -1) {

           fos.write(buf,0,len);

       }

       sis.close();

       fos.close();

    }

 

七、对象的输入输出流。

/**

    1、序列化(ObjectOutputStream):把一个对象信息写到硬盘上 

    2、反序列化(ObjectInputStream):把硬盘上的一个对象信息读取到程序中

 

    注意点:

        1、想要序列化的对象要实现Serializeable接口,Serializeable接口是一个标识接口,没有方法。

        2、反序列化是否调用对象的构造器?

            答案是否定的。

            因为我们把对象写到文件上的时候,文件除了记录class的版本号(SerialVersionUID)。

            JVM本地匹配版本号,有相同的则创建对象。

        3、当我们序列化一个对象之后改动了该对象的成员变量,还能否完成反序列化。

            不能。

            因为我们把对象写到文件上的时候,文件除了记录class的版本号(SerialVersionUID

            版本号 = 类名 + 包名 + 工程名 + 成员一起算出的id

            在反序列化的时候,jvm会使用本地class文件算出一个id号与文件记录的id号进行对比,如果不一致。反序列化失败。

        4、如果有可能改动class文件的时候,那么我们可以指定SerialVersionUID

        5transient可以保证该成员变量透明,当序列化的时候不参与序列化过程。

 

 */

class User implements Serializable{

   

    privateintid;

    private String name;

   

    public User(int id, String name) {

       super();

       this.id = id;

       this.name = name;

    }

    public User() {

       super();

    }

    @Override

    public String toString() {

       return"User [id=" + id + ", name=" + name + "]";

    }

   

   

}

publicclass Demo {

   

    publicstaticvoid main(String[] args) throws Exception {

//     writerObj();

       readObj();

    }

   

    publicstaticvoid readObj() throws Exception {

      

       File file = new File("f:/obj.txt");

      

       FileInputStream fis = new FileInputStream(file);

      

       ObjectInputStream ois = new ObjectInputStream(fis);

      

       User user = (User) ois.readObject();

      

       System.out.println(user);

    }

   

    publicstaticvoid writerObj() throws Exception {

      

       File file = new File("F:/obj.txt");

      

       FileOutputStream fos = new FileOutputStream(file);

      

       ObjectOutputStream oos = new ObjectOutputStream(fos);

      

       User user = new User(1,"genuine");

      

       oos.writeObject(user);

      

       oos.close();

    }

 

}

八、转换流

1、输入字节流的转换流

//  InputStreamReader : 输入字节流的转换流:

privatestaticvoid testInputStreamReader() throws IOException {

       InputStream in = System.in;

      

       InputStreamReader isr = new InputStreamReader(in);

      

       BufferedReader br = new BufferedReader(isr);

 

       String line = null;

      

       while((line = br.readLine()) != null) {

           System.out.println(line);

       }

}

2、输出字节流的转换流

//  OutputStreamWriter : 输出字节流的转换流

privatestaticvoid testOutputStreamWriter() throws IOException {

      

       FileOutputStream fos = new FileOutputStream(new File("f:/a.txt"));

      

       OutputStreamWriter osw = new OutputStreamWriter(fos);

      

       String data = "中国-广州";

      

       osw.write(data);

       osw.close();

}

九、输出流

/*

       PrintStream ps = new PrintStream(new File("f:/a.txt"));

      

       ps.print(3.123);

       ps.close();

*/

   

      

/*    

        //想要打印文件追加的方法:

       FileOutputStream fos = new FileOutputStream(new File("f:/a.txt"),true);

       PrintStream ps = new PrintStream(fos);

      

       try{

//         int a = 2/0;

           String str = null;

           System.out.println("字符个数"+str.length());

       }catch(Exception e) {

           e.printStackTrace(ps);

       }

*/

   

      

/*     //修改标准输出流

       PrintStream ps = new PrintStream(new File("f:/a.txt"));

       System.setOut(ps);

       System.out.println("修改标准输出流");

*/

 

 

 

 

猜你喜欢

转载自codergenuine.iteye.com/blog/2373654
今日推荐