Java流(Stream)

来源:互联网 发布:pop3 端口号 编辑:程序博客网 时间:2024/04/28 10:34

根据流的方向可以分为:输入流和输出流。用户可以从输入流中读取数据,但不可以写它,相反,对于输出流只能写而不能读。其实,输入/输出是相对于内存来说的。

根据流的操作对象的类型可分为:字节流和字符流。在Java中字节流统一由InputStream和OutputStream来做处理,而字符流则由Reader和Writer来做处理。

InputStream、OutputStream、Reader、Writer都是抽象类,所以不能直接new。

以字节为向导的stream(表示以字节为单位从stream中读取或往stream中写入信息):
      1) ByteArrayInputStream:把内存中的一个缓冲区作为InputStream使用
      2) FileInputStream:把一个文件作为InputStream,实现对文件的读取操作
      3) ByteArrayOutputStream:把信息存入内存中的一个缓冲区中
      4) FileOutputStream:把信息存入文件中

以字符为向导的stream(表示以Unicode字符为单位从stream中读取或往stream中写入信息)
      1) CharArrayReader:与ByteArrayInputStream对应
      2) FileReader:与FileInputStream对应
      3) CharArrayWrite:与ByteArrayOutputStream对应
      4) FileWrite:与FileOutputStream对应

两种不限导向的stream之间的转换InputStreamReader和OutputStreamWriter:把一个以字节为导向的stream转换成一个以字符为导向的stream。
      InputStreamReader是字节流通向字符流的桥梁:它使用指定的charset读取字节并将其解码为字符。它使用的字符集可以由名称指定或显式给定,或者可以接受平台默认的字符集。
      OutputStreamWriter是字符流通向字节流的桥梁:可使用指定的charset将要写入流中的字符编码成字节。它使用的字符集可以由名称指定或显式给定,否则将接受平台默认的字符集。

FileInputStream(InputStream的子类)
      1) DataInputStream:从Stream中读取基本类型(int、char等)数据
      2) BufferedInputStream:使用缓冲区
      3) LineNumberInputStream:会记录input stream内的行数,然后可以调用getLineNumber()和setLineNumber(int)
      4) 没有与DataInputStream对应的类。除非在要使用readLine()时改用BufferedReader,否则使用DataInputStream   
      5) BufferedReader:与BufferedInputStream对应
      6) LineNumberReader:与LineNumberInputStream对应

FileOutputStream(OutputStream的子类)
      1) DataIOutStream:往stream中输出基本类型(int、char等)数据。
      2) BufferedOutStream:使用缓冲区
      3) BufferedWrite:与BufferedOutStream对应

//用字节流的方式读取文件内容InputStream is = new BufferedInputStream(new FileInputStream(new File("G:/lee.txt")));//用字符流的方式读取文件内容Reader r = new BufferedReader(new FileReader(new File("G:/lee.txt")));//用字节流的方式读取文件内容之后再转为字符流输入Reader ri = new BufferedReader(new InputStreamReader(new FileInputStream(new File("G:/lee.txt"))));//用字节流的方式输出内容OutputStream os = new BufferedOutputStream(new FileOutputStream(new File("G:/copy.txt")));//用字符流的方式输出内容Writer w = new BufferedWriter(new FileWriter(new File("G:/copy.txt")));//用字符流读取内存中的内容之后再转为字节流输出Writer wo = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("G:/copy.txt"))));

Writer或者OutputStream中的flush(): 刷新该流的缓冲,用于确保数据的输出。close(): 关闭流并释放与之关联的所有系统资源。


try {File file = new File("G:/lee.txt");System.out.println("请输入存储内容:");BufferedReader br = new BufferedReader(new InputStreamReader(System.in));BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));String line;while((line = br.readLine()) != null){if(line.toLowerCase().equals("end")){break;}bw.write(line);bw.newLine();}bw.flush();BufferedReader bb = new BufferedReader(new FileReader(file));String lineValue ;while((lineValue = bb.readLine()) != null){System.out.println(lineValue);}bw.close();br.close();bb.close();} catch (Exception e) {e.printStackTrace();}

try {//将lee.txt中的数据复制到lz.txt中File file1 = new File("G:/lee.txt");File file2 = new File("G:/lz.txt");BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file1), "gbk")); //解决中文乱码//BufferedReader br = new BufferedReader(new FileReader(file1)); //会出现中文乱码BufferedWriter bw = new BufferedWriter(new FileWriter(file2));String line;while((line = br.readLine()) != null){System.out.println(line);bw.write(line);bw.newLine();}bw.flush();bw.close();br.close();} catch (Exception e) {e.printStackTrace();}

public class ReadFromFile {        /**      * @param args      */      public static void main(String[] args) {          // TODO Auto-generated method stub          String fileName = "C:/Users/Administrator/Desktop/Noname1.txt";          //readFileByBytes(fileName);          //readFileByChars(fileName);          //readFileByLines(fileName);          readFileByRandomAccess(fileName);      }            /**      * 随机读取文件内容      */      public static void readFileByRandomAccess(String fileName) {          RandomAccessFile randomFile = null;          try {              System.out.println("随机读取一段文件内容:");              // 打开一个随机访问文件流,按只读方式              randomFile = new RandomAccessFile(fileName, "r");              // 文件长度,字节数              long fileLength = randomFile.length();              // 读文件的起始位置              int beginIndex = (fileLength > 4) ? 0 : 0;              // 将读文件的开始位置移到beginIndex位置。              randomFile.seek(beginIndex);              byte[] bytes = new byte[10];              int byteread = 0;              // 一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。              // 将一次读取的字节数赋给byteread              while ((byteread = randomFile.read(bytes)) != -1) {                  System.out.write(bytes, 0, byteread);              }          } catch (IOException e) {              e.printStackTrace();          } finally {              if (randomFile != null) {                  try {                      randomFile.close();                  } catch (IOException e1) {                  }              }          }      }      /**      * 以行为单位读取文件,常用于读面向行的格式化文件      */      public static void readFileByLines(String fileName) {          File file = new File(fileName);          BufferedReader reader = null;          try {              System.out.println("以行为单位读取文件内容,一次读一整行:");              reader = new BufferedReader(new FileReader(file));              String tempString = null;              int line = 1;              // 一次读入一行,直到读入null为文件结束              while ((tempString = reader.readLine()) != null) {                  // 显示行号                  System.out.println("line " + line + ": " + tempString);                  line++;              }              reader.close();          } catch (IOException e) {              e.printStackTrace();          } finally {              if (reader != null) {                  try {                      reader.close();                  } catch (IOException e1) {                  }              }          }      }            /**      * 以字符为单位读取文件,常用于读文本,数字等类型的文件      */      public static void readFileByChars(String fileName) {          File file = new File(fileName);          Reader reader = null;          try {              System.out.println("以字符为单位读取文件内容,一次读一个字节:");              // 一次读一个字符              reader = new InputStreamReader(new FileInputStream(file));              int tempchar;              while ((tempchar = reader.read()) != -1) {                  // 对于windows下,\r\n这两个字符在一起时,表示一个换行。                  // 但如果这两个字符分开显示时,会换两次行。                  // 因此,屏蔽掉\r,或者屏蔽\n。否则,将会多出很多空行。                  if (((char) tempchar) != '\r') {                      System.out.print((char) tempchar);                  }              }              reader.close();          } catch (Exception e) {              e.printStackTrace();          }          try {              System.out.println("\n以字符为单位读取文件内容,一次读多个字节:");              // 一次读多个字符              char[] tempchars = new char[30];              int charread = 0;              reader = new InputStreamReader(new FileInputStream(fileName));              // 读入多个字符到字符数组中,charread为一次读取字符数              while ((charread = reader.read(tempchars)) != -1) {                  // 同样屏蔽掉\r不显示                  if ((charread == tempchars.length)                          && (tempchars[tempchars.length - 1] != '\r')) {                      System.out.print(tempchars);                  } else {                      for (int i = 0; i < charread; i++) {                          if (tempchars[i] == '\r') {                              continue;                          } else {                              System.out.print(tempchars[i]);                          }                      }                  }              }            } catch (Exception e1) {              e1.printStackTrace();          } finally {              if (reader != null) {                  try {                      reader.close();                  } catch (IOException e1) {                  }              }          }      }      /**      * 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。      */      public static void readFileByBytes(String fileName) {          File file = new File(fileName);          InputStream in = null;          try {              System.out.println("以字节为单位读取文件内容,一次读一个字节:");              // 一次读一个字节              in = new FileInputStream(file);              int tempbyte;              while ((tempbyte = in.read())!=-1) {                  System.out.println(tempbyte);              }          } catch (Exception e) {              // TODO: handle exception              e.printStackTrace();          }                    try {              System.out.println("以字节为单位读取文件内容,一次读多个字节:");              // 一次读多个字节              byte[] tempbytes = new byte[100];              int byteread = 0;              in = new FileInputStream(fileName);              ReadFromFile.showAvailableBytes(in);              // 读入多个字节到字节数组中,byteread为一次读入的字节数              while ((byteread = in.read(tempbytes)) != -1) {                  System.out.write(tempbytes, 0, byteread);//好方法,第一个参数是数组,第二个参数是开始位置,第三个参数是长度              }          } catch (Exception e1) {              e1.printStackTrace();          } finally {              if (in != null) {                  try {                      in.close();                  } catch (IOException e1) {                  }              }          }      }            /**      * 显示输入流中还剩的字节数      */      private static void showAvailableBytes(InputStream in) {          try {              System.out.println("当前字节输入流中的字节数为:" + in.available());          } catch (IOException e) {              e.printStackTrace();          }      }  }  


0 0