JavaSE_IO流_3

来源:互联网 发布:淘宝的匡威是正品吗 编辑:程序博客网 时间:2024/04/30 13:21

MyBufReader

package temp;import java.io.FileReader;import java.io.IOException;import java.io.Reader;//重点~自定义实现缓冲读取字符流~使用包装模式~(包裹 装饰)public class MyBufReader extends Reader{   private Reader r;//底层要用到它的int read(char[] buf)方法   private char[] buf=new char[1024];//1Kb 调试的时候用3字节观察   //定义指针,操作数组   private int index=0;   /*定义个计数器,统计缓冲区中剩余的字符个数,   如果为0,重新再读一批到数组   int read(char[] buf)!并且将指针index归零!*/   private int count=0;   //构造时,接收一个字符读取流~   public MyBufReader(Reader r) {      super();      this.r = r;   }   //自定义方法1:单个字符读取   public int myRead() throws IOException{      /*当计数器变成0的时候,即缓冲区(数组)的数据读完了      才调用FileReader的int read(char[] buf)方法,      从磁盘文件读取一批字符(1K)到缓冲区中      char[] buf=new char[1024]*/      if(count==0){         count=r.read(buf);         index=0;//同时将数组指针归零!      }      //如果r.read(buf)返回的是-1;      //即磁盘文件中字符取光了,就返回-1      if(count<0){         return -1;      }      char ch=buf[index];      //每读一个字符,指针就指向下一个字符,      //并且数组的总剩余字符数就减少一个      index++;      count--;      return ch;   }   //自定义方法2:逐行读取~   public String myReadLine() throws IOException{      /*调用自定义的方法1:逐个字符读取,      并用StringBuilder连接成串,      如果遇到行结束符号了,      就返回该一行的字符串*/      StringBuilder sb=new StringBuilder();      int ch=0;      while ((ch=myRead())!=-1) {         //如果是\r既不添加也不打印,不作任何处理         if(ch=='\r')            continue;         if(ch=='\n')            return sb.toString();         sb.append((char)ch);      }      //如果文章结尾了,但是没有'\n'回车,那么就不要忘记把最后一行返回!      if(sb.length()!=0)         return sb.toString();      return null;   }         public int myBufferedRead_1() throws IOException{//每次单个字符读取      //当计数器为0的时候,就用FileReader r的int read(char[] cbuf)方法,从磁盘文件读取字符到char[] cbuf=new char[1024]中!      if(count==0){         count=r.read(buf);         //如果磁盘文件中字符取光了,就返回-1         if(count<0){            return -1;         }         //同时将数组指针归零!         index=0;         char ch=buf[index];         //每读一个字符,指针就指向下一个字符,         //并且数组的总剩余字符数就减少一个         index++;         count--;         return ch;         }else{         char ch=buf[index];         //每读一个字符,指针就指向下一个字符,         //并且数组的总剩余字符数就减少一个         index++;         count--;         return ch;      }            }   //对于不需要增强的方法,调用原来的对象执行即可~   public void myClose() throws IOException{      r.close();//关闭的还是被缓冲的流对象!   }   public int read(char[] buf, int off, int len) throws IOException {      return 0;   }   public void close() throws IOException {      r.close();   }}


MyBufReader_Demo

package temp;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;import org.junit.Test;public class MyBufReader_Demo {@Test   public void method2() throws IOException {      // MyBufferedReader测试:myBufferedRead(从缓冲区单个字符读取)      FileReader fr=new FileReader("abc.txt");      MyBufReader mbr=new MyBufReader(fr);      int ch=0;      while((ch=mbr.myRead())!=-1){         System.out.print((char)ch);      }   }   @Test   public void method1() throws FileNotFoundException, IOException {      // MyBufferedReader测试:myBufferedReadLine      FileReader fr=new FileReader("abc.txt");      MyBufReader mbr=new MyBufReader(fr);      String line=null;      while((line=mbr.myReadLine())!=null){         System.out.println(line);      }      mbr.myClose();   }}


FileReaderDemo1

package temp;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import org.junit.Test;public class FileReaderDemo1 {private static final int BUFFER_SIZE = 1024*1024;// FileReader和FileWriter学以致用   @Test   public void method2() {      // 第2种复制方法, int read(char[] cbuf)/*      public int read(char[] cbuf)               throws IOException将字符读入数组。在某个输入可用、发生 I/O 错误或者已到达流的末尾前,此方法一直阻塞。       参数:   cbuf - 目标缓冲区       返回:   读取的字符数num_length,如果已到达流的末尾,则返回 -1       抛出:    IOException - 如果发生 I/O 错误*/      FileReader fr=null;      FileWriter fw=null;      try {         fr=new FileReader("abc.txt");         //FileNotFoundException: abc.txt (系统找不到指定的文件。)         fw=new FileWriter("abc_copy.txt");         char[] buf=new char[BUFFER_SIZE];         int len=0;         while ((len=fr.read(buf))!=-1) {            fw.write(buf, 0, len);         }      } catch (FileNotFoundException e) {         e.printStackTrace();      } catch (IOException e) {         e.printStackTrace();      }finally{         if(fr!=null){//超级关键的一句!            try {               fr.close();            } catch (IOException e) {               throw new RuntimeException("打开失败!");            }         }         if(fw!=null){            try {               fw.close();            } catch (IOException e) {               throw new RuntimeException("关闭失败!");            }         }      }         }   @Test   public void method1() throws IOException {      // FileReader和FileWriter学以致用,拷贝TXT//      在工程目录E:\javase\ework\java工程根目录下,将abc.txt复制一份为abc_copy.txt      FileReader fr=new FileReader("abc.txt");      //FileNotFoundException: abc.txt (系统找不到指定的文件。)      FileWriter fw=new FileWriter("abc_copy.txt");      int ch=0;      while ((ch=fr.read())!=-1) {         fw.write(ch);      }      fr.close();      fw.close();   }}/*下面这些全是运行时异常AnnotationTypeMismatchException, ArithmeticException, ArrayStoreException, BufferOverflowException, BufferUnderflowException, CannotRedoException, CannotUndoException, ClassCastException, CMMException, ConcurrentModificationException, DOMException, EmptyStackException, EnumConstantNotPresentException, EventException, IllegalArgumentException, IllegalMonitorStateException, IllegalPathStateException,IllegalStateException, ImagingOpException, IncompleteAnnotationException,IndexOutOfBoundsException, JMRuntimeException, LSException, MalformedParameterizedTypeException, MirroredTypeException, MirroredTypesException, MissingResourceException, NegativeArraySizeException, NoSuchElementException,NoSuchMechanismException, NullPointerException, ProfileDataException, ProviderException, RasterFormatException, RejectedExecutionException, SecurityException, SystemException, TypeConstraintException, TypeNotPresentException,UndeclaredThrowableException, UnknownAnnotationValueException, UnknownElementException, UnknownTypeException, UnmodifiableSetException, UnsupportedOperationException, WebServiceException */


BufferedWriterDemo1

package temp;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import org.junit.Test;//FileReader,文件不存在时会抛找不到文件异常~//FileWriter,文件不存在时会自动创建~public class BufferedWriterDemo1 {   // 为了提高效率,使用BufferedWriter   private static final String LINE_SEPARATOR = System.getProperty("line.separator");   @Test   public void method8() throws IOException {      //imgArray[0] =sgycw_1[0]+sgycw_2[0]+sgycw_3[0]+sgycw_4[0]+sgycw_5[0];      FileWriter fw=new FileWriter("imgArray4.js");      BufferedWriter bufw=new BufferedWriter(fw);      int i=0;      while (i<=978) {         bufw.write("imgArray["+i+"] =sgycw_1[0]+sgycw_2["+i+"]+sgycw_3[0]+sgycw_4["+i+"]+sgycw_5[0];");         i++;         bufw.newLine();//与 readLine 对应! line.separator      }      bufw.close();   }   @Test   public void method7() throws IOException {      // BufferedReader和BufferedWriter复制文本文件(readLine方式)      //FileReader,文件不存在时会抛找不到文件异常~      FileReader fr=new FileReader("E:\\图片收藏\\瀑布流\\beauty\\js\\main.txt");      BufferedReader bufr=new BufferedReader(fr);      //FileWriter,文件不存在时会自动创建~      FileWriter fw=new FileWriter("abc_copy.txt");      BufferedWriter bufw=new BufferedWriter(fw);            String line=null;      int i=0;      while ((line=bufr.readLine())!=null) {         bufw.write("imgArray["+i+++"] =\""+line+"\";");         bufw.newLine();//与 readLine 对应! line.separator      }            bufr.close();      bufw.close();   }   @Test   public void method6() throws IOException {      // BufferedReader和BufferedWriter复制文本文件(char[]读取)            FileReader fr=new FileReader("abc.txt");            BufferedReader bufr=new BufferedReader(fr);                        FileWriter fw=new FileWriter("abc_copy.txt");            BufferedWriter bufw=new BufferedWriter(fw);                        char[] buf=new char[1024];            int len=0;            while ((len=bufr.read(buf))!=-1) {               bufw.write(buf,0,len);            }                        bufr.close();            bufw.close();   }   @Test   public void method5() throws IOException {      // BufferedReader和BufferedWriter复制文本文件(单个单个读取,不提倡!)      FileReader fr=new FileReader("abc.txt");      BufferedReader bufr=new BufferedReader(fr);            FileWriter fw=new FileWriter("abc_copy.txt");      BufferedWriter bufw=new BufferedWriter(fw);            int ch=0;      while ((ch=bufr.read())!=-1) {         bufw.write(ch);      }            bufr.close();      bufw.close();   }   @Test   public void method4() throws IOException {      // 为了提高效率,使用BufferedReader的方法:public String readLine()      /*BufferedReader(Reader in)         创建一个使用默认大小输入缓冲区的缓冲字符输入流。*/      /*public String readLine()                throws IOException读取一个文本行。通过下列字符之一即可认为某行已终止:换行 ('\n')、回车 ('\r') 或回车后直接跟着换行。 返回:包含该行内容的字符串,不包含任何行终止符,如果已到达流末尾,则返回 null 抛出: IOException - 如果发生 I/O 错误*/      FileReader fr=new FileReader("abc.txt");      BufferedReader bufr=new BufferedReader(fr);      String line=null;      while ((line=bufr.readLine())!=null) {         System.out.println(line);      }   }   @Test   public void method3() throws IOException {      // FileReader老的方法读取!      FileReader fr=new FileReader("abc.txt");      char[] buf=new char[1024];      int len=0;      while ((len=fr.read(buf))!=-1) {         System.out.println(new String(buf, 0, len));      }   }   @Test   public void method2() throws IOException {      // BufferedWriter.newLine();//换行!      FileWriter fw=new FileWriter("abc.txt");      BufferedWriter bufw=new BufferedWriter(fw);      for (int i = 1; ; i++) {         bufw.write("红楼梦 第"+i+"回:");         if(i==80){            //并且做到最后一行,没有换行符~            bufw.close();            return;         }         bufw.newLine();//换行!      }   }   @Test   public void method1() throws IOException {      // BufferedWriter      /*将文本写入字符输出流,缓冲各个字符,       * 从而提供单个字符、数组和字符串的高效写入。       可以指定缓冲区的大小,或者接受默认的大小。      在大多数情况下,默认值就足够大了。       该类提供了 newLine() 方法,它使用平台自己的行分隔符概念,      此概念由系统属性 line.separator 定义。      并非所有平台都使用新行符 ('\n') 来终止各行。      因此调用此方法来终止每个输出行要优于直接写入新行符。       通常 Writer 将其输出立即发送到底层字符或字节流。      除非要求提示输出,否则建议用 BufferedWriter       包装所有其 write() 操作可能开销很高的 Writer      (如 FileWriters 和 OutputStreamWriters)。 *///      public BufferedWriter(Writer out)创建一个使用默认大小输出缓冲区的缓冲字符输出流。 //      参数:      out - 一个 Writer,多态,父类引用指向子类实例!      FileWriter fw=new FileWriter("abc.txt");      BufferedWriter bufw=new BufferedWriter(fw);                        // System.getProperty("line.separator");      bufw.write("abcedefghijkl"+LINE_SEPARATOR+"mnopqrstuvwxyz");      bufw.newLine();//换行!      bufw.write("abcedefghijklmnopqrstuvwxyz");      bufw.close();//      fw.write("");bufw.close的时候已经将参数fw即Writer对象关闭了!   }}


LineNumberReaderDemo

package temp;import java.io.FileReader;import java.io.IOException;import java.io.LineNumberReader;import org.junit.Test;/*类 LineNumberReaderjava.lang.Object  java.io.Reader      java.io.BufferedReader          java.io.LineNumberReader所有已实现的接口: Closeable, Readable --------------------------------------------------------------------------------public class LineNumberReaderextends BufferedReader跟踪行号的缓冲字符输入流。此类定义了方法 setLineNumber(int) 和 getLineNumber(),它们可分别用于设置和获取当前行号。 默认情况下,行编号从 0 开始。该行号随数据读取在每个行结束符处递增,并且可以通过调用 setLineNumber(int) 更改行号。但要注意的是,setLineNumber(int) 不会实际更改流中的当前位置;它只更改将由 getLineNumber() 返回的值。 可认为行在遇到以下符号之一时结束:换行符('\n')、回车符('\r')、回车后紧跟换行符。 从以下版本开始: JDK1.1 *//*readLinepublic String readLine()                throws IOException读取文本行。无论何时读取行结束符,当前行号都将加 1。 覆盖:类 BufferedReader 中的 readLine返回:包含行内容的字符串,不包括任何行结束符;如果已到达流的末尾,则返回 null 抛出: IOException - 如果发生 I/O 错误*/public class LineNumberReaderDemo {   @Test   public void method1() throws IOException {      FileReader fr=new FileReader("abc.txt");      LineNumberReader lnr=new LineNumberReader(fr);      String line=null;      lnr.setLineNumber(100);      //第一行便是101行      while ((line=lnr.readLine())!=null) {         System.out.println(lnr.getLineNumber()+"..."+line);      }      lnr.close();   }}


ByteStreamDemo1

package temp;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import org.junit.Test;public class ByteStreamDemo1 {   @Test   public void method9() throws IOException {      // 复制C盘下的MP3文件!方式5,直接用FileInputStream单个读写,没有效率!拒绝使用!      //超级慢!要人老命!            FileInputStream fis=new FileInputStream("C:\\红楼梦前80回(红研所校注本第二版-人民文学出版社2005).pdf");            FileOutputStream fos=new FileOutputStream("C:\\80.pdf");            int i=1/0;            int ch=0;            while ((ch=fis.read())!=-1) {               fos.write(ch);            }            fis.close();            fos.close();   }   @Test   public void method8() throws IOException {      // 复制文件方式4,直接用FileInputStream加fis.available()方法      //48.6M   两秒钟搞定~      //但是,不推荐使用这个方法,若文件过大,易造成内存溢出!            FileInputStream fis=new FileInputStream("C:\\红楼梦前80回(红研所校注本第二版-人民文学出版社2005).pdf");            FileOutputStream fos=new FileOutputStream("C:\\80.pdf");            //开辟一个和文件同样大小的内存做缓存            byte[] buf=new byte[fis.available()];            //FileInputStream读文件入缓存            fis.read(buf);            //FileOutputStream从缓存中写到磁盘文件            fos.write(buf);            fis.close();            fos.close();   }   @Test   public void method7() throws IOException {      // 复制C盘下的MP3文件!方式3,用BufferedInputStream加单个byte读写!开发时这个虽然可以!      FileInputStream fis=new FileInputStream("C:\\diamonds.mp3");      BufferedInputStream bufis=new BufferedInputStream(fis);               FileOutputStream fos=new FileOutputStream("C:\\diamonds_3.mp3");      BufferedOutputStream bufos=new BufferedOutputStream(fos);               int ch=0;      while ((ch=bufis.read())!=-1) {//单个byte读写!         bufos.write(ch);;//注意这个!写的是int      }      bufis.close();      bufos.close();   }   @Test   public void method6() throws IOException {      // 复制C盘下的MP3文件!方式2,用BufferedInputStream加数组,      //和方法1一样,只是全改成了缓冲区的方法,建议使用这个!            FileInputStream fis=new FileInputStream("C:\\diamonds.mp3");            BufferedInputStream bufis=new BufferedInputStream(fis);                     FileOutputStream fos=new FileOutputStream("C:\\diamonds_2.mp3");            BufferedOutputStream bufos=new BufferedOutputStream(fos);                     byte[] buf=new byte[1024];            int len=0;            while ((len=bufis.read(buf))!=-1) {               bufos.write(buf, 0, len);               bufos.flush();//别忘记这个缓冲区的flush还是有用的!            }            bufis.close();            bufos.close();   }   @Test   public void method5() throws IOException {      // 复制C盘下的MP3文件!方式1,直接用FileInputStream加FileOutputStream加数组      FileInputStream fis=new FileInputStream("C:\\diamonds.mp3");      FileOutputStream fos=new FileOutputStream("C:\\diamonds_1.mp3");      byte[] buf=new byte[1024];      int len=0;      while ((len=fis.read(buf))!=-1) {         fos.write(buf, 0, len);      }      fis.close();      fos.close();   }   @Test   public void method4() throws IOException {      // abc位于工程的根目录,字节流读入内存,并输出到屏幕      FileInputStream fis=new FileInputStream("abc.txt");      System.out.println(fis.available());//直接返回文件的总大小字节数      byte[] buf=new byte[fis.available()];      fis.read(buf);      System.out.println(new String(buf));      fis.close();   }   @Test   public void method3() throws IOException {      // FileInputStream的读取方法2(存放到字节数组)/*      public int read(byte[] b)               throws IOException从此输入流中将最多 b.length 个字节的数据读入一个 byte 数组中。               在某些输入可用之前,此方法将阻塞。       覆盖:      类 InputStream 中的 read      参数:      b - 存储读取数据的缓冲区。       返回:   读入缓冲区的字节总数,如果因为已经到达文件末尾而没有更多的数据,则返回 -1。       抛出:    IOException - 如果发生 I/O 错误。*/      FileInputStream fis=new FileInputStream("abc.txt");// abc位于工程的根目录      byte[] buf=new byte[1024];      int len=0;      while ((len=fis.read(buf))!=-1) {         System.out.print(new String(buf, 0, len));      }   }   @Test   public void method2() throws IOException {      //FileInputStream的读取方法1(读取一个数据字节,效率极低~)      /*public int read()               throws IOException从此输入流中读取一个数据字节。               如果没有输入可用,则此方法将阻塞。       指定者:      类 InputStream 中的 read      返回:      下一个数据字节;如果已到达文件末尾,则返回 -1。       抛出:    IOException - 如果发生 I/O 错误。*/      FileInputStream fis=new FileInputStream("abc.txt");// abc位于工程的根目录      int ch=0;      while ((ch=fis.read())!=-1) {         System.out.print((char)ch);      }   }   @Test   public void method1() throws IOException {      //FileOutputStream自己没有flush,而继承其父类,OutputStream的flush什么也没有写      FileOutputStream fos=new FileOutputStream("abc.txt");      fos.write("sgycw.com".getBytes());//字节流,都需要转换成bytes      fos.flush();//alt+单击,直接进入了其父类OutputStream的flush方法,里面什么也没写      fos.close();   }}


SystemInDemo1

package temp;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.OutputStreamWriter;import org.junit.Test;public class SystemInDemo1 {   @Test   public void method20() throws IOException {      /*测试准备,      1,先在java工程根目录新建一个X.txt      2,输入内容(能使妖魔胆尽摧,身如束帛气如雷。                     一声震得人方恐,回首相看已化灰。)      3,另存为abc.txt,注意选择编码:UTF-8      涉及指定编码就要想到用转换流InputStreamReader读取*/      InputStreamReader isr=new InputStreamReader(new FileInputStream("abc.txt"), "UTF-8");      char[] buf=new char[1024];      int len=isr.read(buf);      System.out.println(new String(buf,0,len));   }   @Test   public void method19() throws IOException {      //用FileReader(GBK)读入刚才method18用OutputStreamWriter参数UTF-8编码的文件      //结果必然是乱码~      FileReader fr=new FileReader("abc.txt");      char[] buf=new char[10];      int length=fr.read(buf);      System.out.println(new String(buf,0,length));   }   @Test   public void method18() throws IOException {      //字节流和字符流之间的编码解码,OutputStreamWriter可以指定码表!      OutputStreamWriter osw=new OutputStreamWriter(new FileOutputStream("abc.txt"),"UTF-8");      osw.write("中国");      //为啥这里是6个字节?!!!      osw.close();   }   @Test   public void method17() throws IOException {      //字节流和字符流之间的编码解码,      //OutputStreamWriter在不指定码表的时候,      //使用默认码表!等同于method16和method15            OutputStreamWriter osw=new OutputStreamWriter(new FileOutputStream("abc.txt"),"GBK");            osw.write("中国");            //四个字节,因为使用的是默认码表GBK            //可以确定的是GBK编码时,每个汉字是2个字节~            osw.close();   }   @Test   public void method16() throws IOException {      //字节流和字符流之间的编码解码,      //OutputStreamWriter在不指定码表的时候,使用默认码表!      OutputStreamWriter osw=new OutputStreamWriter(new FileOutputStream("abc.txt"));      osw.write("中国");      //四个字节,因为使用的是默认码表GBK      //可以确定的是GBK编码时,每个汉字是2个字节~      osw.close();   }   @Test   public void method15() throws IOException {      //字节流和字符流之间的编码解码,FileWriter只能使用默认码表!      FileWriter fw=new FileWriter("abc.txt");      fw.write("你好");//四个字节      //GBK一个中文,占2个字节!      //可以确定的是GBK编码时,每个汉字是2个字节~      fw.close();   }   @Test   public void method14() throws IOException {      //应用演示!将文本文件内容复制到另一个文本文件中!            // 简化!从键盘到控制台!两层转换流InputStreamReader和OutputStreamWriter      BufferedReader bufr=new BufferedReader(new InputStreamReader(new FileInputStream("abc.txt")));      BufferedWriter bufw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream("abc_copy.txt")));      //注意要传1个文件相关的字节流!               String line=null;               while ((line=bufr.readLine())!=null) {                  if("over".equals(line))                     break;                  bufw.write(line.toUpperCase());                  bufw.newLine();                  bufw.flush();                  //涉及到编码就要刷新                  //newLine和flush同在~~               }         }   @Test   public void method13() throws IOException {      //应用演示!将文本文件读入显示到控制台中!      // 简化!从键盘到控制台!两层转换流InputStreamReader和OutputStreamWriter      BufferedReader bufr=new BufferedReader(new InputStreamReader(new FileInputStream("abc.txt")));      BufferedWriter bufw=new BufferedWriter(new OutputStreamWriter(System.out));//注意要传1个文件相关的字节流!               String line=null;               while ((line=bufr.readLine())!=null) {                  if("over".equals(line))                     break;                  bufw.write(line.toUpperCase());                  bufw.newLine();                  bufw.flush();//涉及到编码就要刷新                  //newLine和flush同在~~               }   }   @Test   public void method12() throws IOException {      //应用演示!将键盘录入到文件当中!      // 简化!从键盘到控制台!两层转换流InputStreamReader和OutputStreamWriter   BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));   BufferedWriter bufw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream("abc.txt")));//注意要传1个文件相关的字节流!            String line=null;            while ((line=bufr.readLine())!=null) {               if("over".equals(line))                  break;               bufw.write(line.toUpperCase());               bufw.newLine();               bufw.flush();//涉及到编码就要刷新               //newLine和flush同在~~            }   }   @Test   public void method11() throws IOException {      // 简化!从键盘到控制台!两层转换流InputStreamReader和OutputStreamWriter      BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));      //下面是输出到控制台(字节流)      BufferedWriter bufw=new BufferedWriter(new OutputStreamWriter(System.out));      String line=null;      while ((line=bufr.readLine())!=null) {         if("over".equals(line))            break;         bufw.write(line.toUpperCase());         bufw.newLine();         bufw.flush();//涉及到编码就要刷新         //newLine和flush同在~~      }   }   @Test   public void method10() throws IOException {      //OutputStreamWriter字符流转字节流_编码_flush_文件到硬盘            InputStreamReader isr=new InputStreamReader(System.in);            //转换流,参数是字节流,类是字符流!            BufferedReader bufr=new BufferedReader(isr);            //下面是输出到控制台(字节流)            OutputStream out=System.out;            OutputStreamWriter osw=new OutputStreamWriter(out);            //将字符编码为字节后输出            BufferedWriter bufw=new BufferedWriter(osw);                        String line=null;            while ((line=bufr.readLine())!=null) {               if("over".equals(line))                  break;               bufw.write(line.toUpperCase());               bufw.newLine();               bufw.flush();//涉及到编码就要刷新               //newLine和flush同在~~            }   }   @Test   public void method9() throws IOException {      //OutputStreamWriter字符流转字节流_编码_flush_文件到硬盘      InputStream in=System.in;      InputStreamReader isr=new InputStreamReader(in);      //转换流,参数是字节流,类是字符流!      BufferedReader bufr=new BufferedReader(isr);      //下面是输出到控制台(字节流)      OutputStream out=System.out;      OutputStreamWriter osw=new OutputStreamWriter(out);//将字符编码为字节后输出      String line=null;      while ((line=bufr.readLine())!=null) {         if("over".equals(line))            break;         osw.write(line.toUpperCase());         osw.flush();//涉及到编码就要刷新      }   }   @Test   public void method8() throws IOException {      // 一个汉字,通过转换流,变成字符流后,只要读1次???      InputStream in=System.in;      InputStreamReader isr=new InputStreamReader(in);      //转换流,构造接收参数是字节流,返回的是字符流!      int ch=isr.read();      System.out.println((char)ch);      //输入:中,返回:中      //因为查默认码表了(即使转换流构造的时候没有指定码表)   }   @Test   public void method7() throws IOException {      // 为什么:一个汉字,字节流要读2次???      //因为在GBK的编码表中,一个汉字占2个字节      InputStream in=System.in;      int ch1=in.read();      System.out.println(ch1);      int ch2=in.read();      System.out.println(ch2);      //输入:中,返回:   214   208   }   @Test   public void method6() throws IOException {      // 记录键盘,并将其输出3:转换成大写后输出,输入OVER,结束!使用转换流,readLine      InputStream in=System.in;      InputStreamReader isr=new InputStreamReader(in);      //转换流,参数是字节流,类是字符流!      BufferedReader bufr=new BufferedReader(isr);      //再加个缓冲流包装一下      String line=null;      while ((line=bufr.readLine())!=null) {         if("over".equals(line))            break;         System.out.println(line.toUpperCase());      }   }   @Test   public void method5() throws IOException {      //  记录键盘,并将其输出3:转换成大写后输出,输入OVER,结束!      InputStream in=System.in;      StringBuilder sb=new StringBuilder();      int ch=0;      while ((ch=in.read())!=-1) {         //如果是\r,不作任何处理~继续下次循环         if(ch==13)            continue;         //如果是\n,输出         if(ch==10){            String str=sb.toString();            if("over".equals(str)){               //退出系统~               System.exit(0);            }            System.out.println(sb.toString().toUpperCase());            //清空缓冲区            sb.delete(0, sb.length());         }else {            sb.append((char)ch);//否则,才会添加进来!避免把换行添加进来了!         }      }   }   @Test   public void method4() throws IOException {      // 记录键盘,并将其输出2,并判断,如果是回车符\r :就continue;      //如果是回车符\r :  13,不作任何处理            //如果是换行符\n :  10,那就换行后,再continue      InputStream in=System.in;      int ch=0;      while ((ch=in.read())!=-1) {         if(ch==13)   //      回车符\r :  13            continue;         if(ch==10){//      换行符\n :  10            System.out.println();            continue;         }         System.out.print(ch);         //System.out.print((char)ch);输入中,回车是??      }      /*a      97      中      214208      国      185250      中国      214208185250*/   }   @Test   public void method3() throws IOException {      // 记录键盘,并将其输出1      InputStream in=System.in;      int ch=0;      while ((ch=in.read())!=-1) {         sop(ch+"");      }      /*a      97      13      10      中      214      208      13      10*/   }   @Test   public void method2() {      sop("回车符\\r :  "+(int)'\r');      sop("换行符\\n :  "+(int)'\n');      /*回车符\r :  13      换行符\n :  10*/   }   @Test   public void method1() throws IOException {       /*public static final InputStream in“标准”输入流。      此流已打开并准备提供输入数据。      通常,此流对应于键盘输入或者由主机环境或用户指定的另一个输入源。*/       InputStream in=System.in;      int ch1=in.read();      int ch2=in.read();      int ch3=in.read();      sop(ch1+"");      sop(ch2+"");      sop(ch3+"");      /*输入1个:a      返回这三个:97      13      10*/   }   public static void sop(String string) {      System.out.println(string);   }}


PrintStreamDemo1

package temp;import java.io.FileNotFoundException;import java.io.FileWriter;import java.io.IOException;import java.io.PrintStream;import org.junit.Test;/*类 OutputStream的方法:public abstract void write(int b) int共32位        throws IOException将指定的字节写入此输出流。        write 的常规协定是:向输出流写入一个字节。        要写入的字节是参数 b 的八个低位。        b 的 24 个高位将被忽略。           OutputStream 的子类必须提供此方法的实现。     参数:b - 字节 PrintStream 为其他输出流添加了功能, * 使它们能够方便地打印各种数据值表示形式。 * 它还提供其他两项功能。 * 与其他输出流不同,PrintStream 永远不会抛出 IOException; * 而是,异常情况仅设置可通过 checkError 方法测试的内部标志。 * 另外,为了自动刷新,可以创建一个 PrintStream; * 这意味着可在写入 byte 数组之后自动调用 flush 方法, * 可调用其中一个 println 方法,或写入一个换行符或字节 ('\n')。 PrintStream 打印的所有字符都使用平台的默认字符编码转换为字节。在需要写入字符而不是写入字节的情况下,应该使用 PrintWriter 类。PrintStream(File file)           创建具有指定文件且不带自动行刷新的新打印流。 PrintStream(File file, String csn)           创建具有指定文件名称和字符集且不带自动行刷新的新打印流。 PrintStream(OutputStream out)           创建新的打印流。 PrintStream(OutputStream out, boolean autoFlush)           创建新的打印流。 常用~PrintStream(OutputStream out, boolean autoFlush, String encoding)           创建新的打印流。 PrintStream(String fileName)           创建具有指定文件名称且不带自动行刷新的新打印流。 PrintStream(String fileName, String csn)           创建具有指定文件名称和字符集且不带自动行刷新的新打印流。*/ public class PrintStreamDemo1 {   @Test   public void method4_1() throws IOException  {      /*PrintStream(String fileName)         创建具有指定文件名称且不带自动行刷新的新打印流。*/      PrintStream ps=new PrintStream("abc.txt");      //注意区分:FileWriter fw=new FileWriter("abc.txt");      ps.write(97);//将int 97的二进制的最低八位写到了文件!0100-0001      ps.close();//文件打开后,显示结果:a,文件大小 :1个字节   }   @Test   public void method4() throws IOException {         PrintStream ps=new PrintStream("abc.txt");         //如果文件不存在,会自动创建         //如果文件已经存在,会自动覆盖~         //它不会抛文件找不着异常         ps.write(609);         //字节流的write(int)方法,只会写低八位~         //将int 609的二进制的最低八位写到了文件!0100-0001         ps.close();//文件打开后,显示结果仍然为:a,文件大小 还是1个字节   }   @Test   public void method3() throws IOException {      //如果文件不存在,会自动创建      //如果文件已经存在,会自动覆盖~      FileWriter fw=new FileWriter("abc.txt");      fw.write(602);//文件打开后,显示一个问号(大小是1字节)      fw.close();   }   @Test   public void method2() throws IOException {      /* PrintStream(String fileName) 创建具有指定文件名称且不带自动行刷新的新打印流。        * 如果文件不存在,会自动创建       * 如果文件已经存在,会自动覆盖~        * 它不会抛文件找不着异常*/      PrintStream ps=new PrintStream("abc.txt");      ps.print(97);//原样打印:显示结果是一模一样!97      ps.close();//文件打开后,显示结果:97,文件大小 :2个字节      /*其实print内部是这样的代码:         public void print(int i) {             write(String.valueOf(i));              //其实是将数字转换成字符串,然后按write(String)的方法保存         }*/   }}


PrintWriterDemo1

package temp;import java.io.BufferedReader;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import org.junit.Test;/*public class PrintWriter  extends Writer向文本输出流打印对象的格式化表示形式。 此类实现在 PrintStream 中的所有 print 方法。 它不包含用于写入原始字节的方法, 对于这些字节,程序应该使用未编码的字节流进行写入。 与 PrintStream 类不同,如果启用了自动刷新,则只有在调用 println、printf 或 format 的其中一个方法时才可能完成此操作,而不是每当正好输出换行符时才完成。这些方法使用平台自有的行分隔符概念,而不是换行符。 此类中的方法不会抛出 I/O 异常,尽管其某些构造方法可能抛出异常。客户端可能会查询调用 checkError() 是否出现错误。PrintWriter(File file)           使用指定文件创建不具有自动行刷新的新 PrintWriter。 PrintWriter(File file, String csn)           创建具有指定文件和字符集且不带自动刷行新的新 PrintWriter。 PrintWriter(OutputStream out)           根据现有的 OutputStream 创建不带自动行刷新的新 PrintWriter。 PrintWriter(OutputStream out, boolean autoFlush)           通过现有的 OutputStream 创建新的 PrintWriter。 PrintWriter(String fileName)           创建具有指定文件名称且不带自动行刷新的新 PrintWriter。 PrintWriter(String fileName, String csn)           创建具有指定文件名称和字符集且不带自动行刷新的新 PrintWriter。 PrintWriter(Writer out)           创建不带自动行刷新的新 PrintWriter。 PrintWriter(Writer out, boolean autoFlush)           创建新 PrintWriter。 */public class PrintWriterDemo1 {   @Test   public void method3()  throws IOException {      // PrintWriter如何实现既能写到文件,又能自动刷新?      //把文件用FileOutputStream封装起来不就OK      BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));      PrintWriter pw=new PrintWriter(new FileOutputStream("abc.txt"),true);      String line=null;      while ((line=bufr.readLine())!=null) {         if ("over".equals(line)) {            break;         }         pw.println(line);         //因为PrintWriter构造时autoFlush设置为true,         //同时又是使用println方法,所以不需手动刷新pw.flush()      }      bufr.close();      pw.close();   }   @Test   public void method2() throws IOException {      /* PrintWriter(OutputStream out,boolean autoFlush)      通过现有的 OutputStream 创建新的 PrintWriter。      此便捷构造方法创建必要的中间 OutputStreamWriter,      后者使用默认字符编码将字符转换为字节。       参数:out - 输出流      autoFlush - boolean 变量;如果为 true,      则PrintWriter调用println、printf 或 format 方法时      将自动刷新输出缓冲区*/      BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));      PrintWriter pw=new PrintWriter(System.out,true);      //true,则使用方法println、printf 或 format将自动刷新输出缓冲区      String line=null;      while ((line=bufr.readLine())!=null) {         if ("over".equalsIgnoreCase(line)) {            break;         }         pw.println(line);         //因为PrintWriter构造时autoFlush设置为true,         //同时又是使用println方法,所以不需手动刷新pw.flush()      }      bufr.close();      pw.close();   }   @Test   public void method1() throws IOException {      BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));      PrintWriter pw=new PrintWriter(System.out);      String line=null;      while ((line=bufr.readLine())!=null) {         if ("over".equals(line)) {            break;         }         pw.println(line);         pw.flush();      }      bufr.close();      pw.close();   }}


SequenceInputStreamDemo1

package temp;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.SequenceInputStream;import java.util.ArrayList;import java.util.Collections;import java.util.Enumeration;import java.util.Iterator;import java.util.Vector;/*public class SequenceInputStream extends InputStream     * SequenceInputStream 表示其他输入流的逻辑串联。 * 它从输入流的有序集合开始,并从第一个输入流开始读取, * 直到到达文件末尾,接着从第二个输入流读取,依次类推, * 直到到达包含的最后一个输入流的文件末尾为止。 从以下版本开始: JDK1.0 *//*构造方法摘要 SequenceInputStream(Enumeration<? extends InputStream> e)      通过记住参数来初始化新创建的 SequenceInputStream,     该参数必须是生成运行时类型为 InputStream 对象的 Enumeration 型参数。 SequenceInputStream(InputStream s1, InputStream s2)           通过记住这两个参数来初始化新创建的 SequenceInputStream将按顺序读取这两个参数,先读取 s1,然后读取 s2),以提供从此 SequenceInputStream 读取的字节。 public SequenceInputStream(Enumeration<? extends InputStream> e) * 通过记住参数来初始化新创建的 SequenceInputStream, * 该参数必须是生成运行时类型为 InputStream 对象的 Enumeration 型参数。 * 将按顺序读取由该枚举生成的输入流, * 以提供从此 SequenceInputStream 读取的字节。 * 在用尽枚举中的每个输入流之后,将通过调用该流的 close 方法将其关闭。 参数:e - 输入流的一个枚举。另请参见:Enumeration*/import org.junit.Test;public class SequenceInputStreamDemo1 {   @Test   public void method3() throws IOException {      //利用集合工具类Collections的enumeration方法,返回一个指定 collection 上的枚举      /*public static <T> Enumeration<T> enumeration(Collection<T> c)       * 返回一个指定 collection 上的枚举。       * 此方法提供与遗留 API 的互操作性,       * 当遗留的API 需要一个枚举作为参数时。             参数:   c - 将返回其枚举的 collection。             返回:      指定 collection 上的一个枚举。*/            ArrayList<FileInputStream> al=new ArrayList<FileInputStream>();            for (int i = 1; i < 4; i++) {               al.add(new FileInputStream(i+".txt"));               //如果java工程的根目录下没有1.txt               //会抛FileNotFoundExcetpion            }            Enumeration enu=Collections.enumeration(al);            SequenceInputStream sis=new SequenceInputStream(enu);            FileOutputStream fos=new FileOutputStream("125.txt");            byte[] buf=new byte[1024];            int len=0;            while ((len=sis.read(buf))!=-1) {               fos.write(buf, 0, len);            }            fos.close();            sis.close();   }   @Test   public void method2() throws IOException{      /*经典! SequenceInputStream构造函数的参数接收枚举,      但是却又没有枚举可用~      此时,就自己构造一个枚举,底层使用迭代器,      new个匿名类,实现枚举器接口(及其方法)*/       ArrayList<FileInputStream> al=new ArrayList<FileInputStream>();      for (int i = 1; i < 4; i++) {         al.add(new FileInputStream(i+".txt"));      }      //内部类访问局部变量,该局部变量要被final修饰(延长扩大该局部变量的作用范围)      final Iterator<FileInputStream> it=al.iterator();      //没有枚举器,就自己用匿名内部类new 一个!底层的实现,使用的是迭代器      //内部类访问局部变量,该局部变量要被final修饰(延长扩大该局部变量的作用范围)      Enumeration<FileInputStream> enu=new Enumeration<FileInputStream>() {         public boolean hasMoreElements() {            return it.hasNext();         }         public FileInputStream nextElement() {            return it.next();         }      };      //将上面自己实现的枚举传给SequenceInputStream构造函数的参数      SequenceInputStream sis=new SequenceInputStream(enu);      FileOutputStream fos=new FileOutputStream("124.txt");      byte[] buf=new byte[1024];      int len=0;      while ((len=sis.read(buf))!=-1) {         fos.write(buf, 0, len);      }      fos.close();      sis.close();   }   @Test   public void method1() throws IOException {      //读入3个Txt,将内容合并写入123.txt      Vector<FileInputStream> v=new Vector<FileInputStream>();      v.add(new FileInputStream("1.txt"));      v.add(new FileInputStream("2.txt"));      v.add(new FileInputStream("3.txt"));      //只有古典的Vector才使用Enumeration      Enumeration<FileInputStream> enu=v.elements();      //刚巧SequenceInputStream的构造函数参数枚举作参数      SequenceInputStream sis=new SequenceInputStream(enu);      FileOutputStream fos=new FileOutputStream("123.txt");      byte[] buf=new byte[1024];      int len=0;      while ((len=sis.read(buf))!=-1) {         fos.write(buf, 0, len);      }      fos.close();      sis.close();   }}


SplitMergeFile

package temp;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.SequenceInputStream;import java.util.ArrayList;import java.util.Collections;import java.util.Enumeration;import java.util.Properties;import org.junit.Test;import IO.FilenameFilterBySuffix;public class SplitMergeFile {   // 切割和合并文件   private static final int SIZE = 1024*1024*1;//定义1M的缓冲区   @Test   // 合并文件!过滤器+读配置   public void mergeFile() throws IOException {      File file=new File("c:\\partfiles");//碎片文件所在目录      //此处 省略健壮性判断      if (!file.exists()) {         throw new RuntimeException("碎片文件目录不存在!");      }      //获取配置文件个数,进行完整性判断!      File[] files=file.listFiles(new FilenameFilterBySuffix(".properties"));      if (files.length!=1) {         throw new RuntimeException(file+"目录下没有配置文件,或不唯一");      }      //拿到配置文件如:i.properties      File configFile=files[0];      //流关联配置文件      FileInputStream fis=new FileInputStream(configFile);      Properties prop=new Properties();      prop.load(fis);      //取得碎片文件个数filecount,和文件名称filename(只是名称如:A.TXT)      String filename=prop.getProperty("filename");      int count=Integer.parseInt(prop.getProperty("filecount"));      //获取碎片文件个数,进行完整性判断!            File[] partFiles=file.listFiles(new FilenameFilterBySuffix(".part"));            if (partFiles.length!=(count)) {               throw new RuntimeException("碎片文件数目不符合要求");            }      //下面开始用集合装碎片            ArrayList<FileInputStream> al=new ArrayList<FileInputStream>();            for (int i = 0; i < partFiles.length; i++) {               //al.add(new FileInputStream(new File(file,i+".part")));               al.add(new FileInputStream(partFiles[i]));//上下两句是等效!            }            //集合工具类实现将Collection转枚举            Enumeration enu=Collections.enumeration(al);            //SequenceInputStream构造参数需要枚举            SequenceInputStream sis=new SequenceInputStream(enu);            //不存在,会自动创建            FileOutputStream fos=new FileOutputStream(new File(file,filename));            byte[] buf=new byte[SIZE];            int len=0;            while ((len=sis.read(buf))!=-1) {               fos.write(buf, 0, len);            }            fos.close();            sis.close();   }   @Test   // 切割文件,带配置信息!每个小文件1M:1024*1024   public void splitFile() throws IOException, IOException {            Properties prop=new Properties();            /*File file=new File("c:\\desk.bmp");            File file=new File("c:\\diamonds.mp3");            File file=new File("c:\\红楼梦前80回(红研所校注本第二版-人民文学出版社2005).pdf");*/            //File file=new File("c:\\Adele - Someone Like You.mp3");            //File file=new File("g:\\央视87版红楼梦插曲集锦.mkv");50M播放才1分钟~            File file=new File("c:\\Java_Learn1.java");            FileInputStream fis=new FileInputStream(file);//用文件字节流文联文件            /*此处应该先判断文件的长度,如果太大比如3G以上抛异常算了~            如果小于1G,则20M以下,缓冲区固定为1M            如果小于1G,且大于20M,缓冲区动态为20分之一文件大小,取整*/            //System.out.println(file.length());            //System.out.println((int)22433.9);            int fileTotalSize=(int) (file.length()/1024/1024);            int fileSingleSize;            System.out.println(fileTotalSize);            if (fileTotalSize>1024*3) {               throw new RuntimeException("文件大于3G~");            } else if(fileTotalSize>500) {               //如果文件大于500M,单个文件设置为50M               fileSingleSize=1024*1024*50;            }else if (fileTotalSize>20) {               //如果文件XXX大于20M,单个文件设置为1M*XXX/20)               fileSingleSize=1024*1024*Math.round(fileTotalSize/20);            } else {               //小于20M的全部设置为1M               fileSingleSize=1024*1024;            }            //byte[] buf=new byte[SIZE];//定义1M的缓冲区:1024*1024            byte[] buf=new byte[fileSingleSize];//动态定义缓冲区            int len=0;            int count=0;            File dir=new File("c:\\partfiles");            //健壮性            if (!dir.exists()) {               dir.mkdirs();            }            FileOutputStream fos =null;            //文件后缀应该与源文件一样(如.avi)            String fileName=file.getName();            while ((len=fis.read(buf))!=-1) {               fos=new FileOutputStream(new File(dir,(count++)+".part"));               fos.write(buf, 0, len);               fos.close();//每开一个就关闭一个输出流            }            prop.setProperty("filecount", count+"");//文件分卷!            prop.setProperty("filename",fileName);//源文件名称            prop.setProperty("filepath",file.getAbsolutePath());//源文件名称            FileOutputStream out =new FileOutputStream(new File(dir,count+".properties"));            prop.store(out, "splitfile_information");            fis.close();   }   @Test   public void method2() throws IOException {      // 合并文件_简单处理      ArrayList<FileInputStream> al=new ArrayList<FileInputStream>();      File file=new File("c:\\partfiles");      //此处 省略健壮性判断      if (!file.exists()) {         throw new RuntimeException("碎片文件目录不存在!");      }      //通过看文件夹,知道有4个文件~      for (int i = 0; i < 4; i++) {         al.add(new FileInputStream(new File(file,i+".part")));      }      //合并需要序列输入流,构造参数需要枚举      Enumeration enu=Collections.enumeration(al);      SequenceInputStream sis=new SequenceInputStream(enu);      FileOutputStream fos=new FileOutputStream(new File(file,"4.bmp"));//没有会自动创建      byte[] buf=new byte[SIZE];      int len=0;      while ((len=sis.read(buf))!=-1) {         fos.write(buf, 0, len);      }      fos.close();      sis.close();   }   @Test   public void method1() throws IOException {      //切割指定文件,每个小文件1M      //简单分割处理,没有配置文件~      File file=new File("c:\\desk.bmp");      //此处应健壮性判断      if (!file.exists()) {         throw new RuntimeException("系统找不到指定的文件~");      }      FileInputStream fis=new FileInputStream(file);//用文件字节流文联文件      byte[] buf=new byte[SIZE];//定义1M的缓冲区:1024*1024      int len=0;      int count=0;      File dir=new File("c:\\partfiles");      //健壮性      if (!dir.exists()) {         dir.mkdirs();      }      FileOutputStream fos =null;      while ((len=fis.read(buf))!=-1) {         fos=new FileOutputStream(new File(dir,(count++)+".part"));         fos.write(buf, 0, len);         fos.close();//每开一个就关闭一个输出流      }      //最后关闭输入流      fis.close();   }}





0 0
原创粉丝点击