Java IO流

来源:互联网 发布:tensorflow如何入门 编辑:程序博客网 时间:2024/06/07 05:43

 

Java IO流 Stream

 

 

InputStream/OutputStream抽象类-字节Reader/Writer抽象类-字符FileInputStream/FileOutputStream文件-字节FileReader/FileWriter文件-字符BufferedInputStream/BufferedOutputStream缓冲区-字节BufferedReader(可以整行读)/BufferedWriter缓冲区-字符ByteArrayInputStream/ByteArrayOutputStream内存字节数组读写InputStreamReader/OutputStreamWriter转换流-字节转字符DataInputStream/DataOutputStream直接写基础数据类型,utf-8的字符串PrintStream/PrintWriter打印流-字节-字符ObjectInputStream/ObjectOutputStream
Object流,serializable、externalizable接口,transient关键字

  • 节点流

 字节流字符流输入流InputStreamReader输出流OutputStreamWriter


FileOutputStream、FileWriter这些输出流,打开文件的时候,如果文件没有会自动创建该文件。(目录好像不会自动创建)



  • 缓冲流:


缓冲流要“套接”在相应的节点流之上,对读写的数据提供了缓冲的功能,
提高了读写的效率,同时增加了一写新的方法。

缓冲输入流支持其父类的markreset方法。

BufferedReader提供了readLine方法用于读取一行字符串(以\r或\n分割)。

BufferedWriter提供了newLine用于写入一个行分割符。

对于输出的缓冲流,写出的数据会先在内存中缓存,使用flush方法将会使内存中的数据立刻写出。


BufferedInputStream
BufferedOutputStream

BufferedInputStream(InputStream in)
          创建一个 BufferedInputStream 并保存其参数,即输入流 in,以便将来使用。BufferedInputStream(InputStream in, int size)
          创建具有指定缓冲区大小的 BufferedInputStream 并保存其参数,即输入流 in,以便将来使用。

  • 转换流:

InputStreamReader  是字节流通向字符流的桥梁
OutputStreamWrier  是字符流通向字节流的桥梁
 

InputStreamReader(InputStream in)
          创建一个使用默认字符集的 InputStreamReader。InputStreamReader(InputStream in, Charset cs)
          创建使用给定字符集的 InputStreamReader。InputStreamReader(InputStream in, CharsetDecoder dec)
          创建使用给定字符集解码器的 InputStreamReader。InputStreamReader(InputStream in, String charsetName)
          创建使用指定字符集的 InputStreamReader。

OutputStreamWriter(OutputStream out)
          创建使用默认字符编码的 OutputStreamWriter。OutputStreamWriter(OutputStream out, Charset cs)
          创建使用给定字符集的 OutputStreamWriter。OutputStreamWriter(OutputStream out, CharsetEncoder enc)
          创建使用给定字符集编码器的 OutputStreamWriter。OutputStreamWriter(OutputStream out, String charsetName)
          创建使用指定字符集的 OutputStreamWriter。



//由于FileOutputStream不支持直接写字符串,仅支持字节byte
//采用OutputStreamWriter支持字符串,起到一个转换的功能。

public class TestTransForm1 {
public static void main(String[] args) {
 try {
   OutputStreamWriter osw = new OutputStreamWriter(
        new FileOutputStream("d:\\bak\\char.txt" ));
   osw.write("mircosoftibmsunapplehp");
   System.out.println(osw.getEncoding());
   osw.close();
   osw = new OutputStreamWriter(
                                           new FileOutputStream("d:\\bak\\char.txt", true),
                                           "ISO8859_1"); // latin-1 西欧语言
   osw.write("mircosoftibmsunapplehp");
   System.out.println(osw.getEncoding());
   osw.close();
 } catch (IOException e) {
   e.printStackTrace();
 }
}
}


//读取控制台的标准输入

public class TestTransForm2 {
public static void main(String args[]) {
 // to get input stream form keyboard[System.in]
  // 添加转换流,防止中文汉字被截断
 InputStreamReader isr =
         new InputStreamReader(System.in);
  // 添加缓冲流,为了使用readLine
 BufferedReader br = new BufferedReader(isr);
 String s = null;
 try {
   s = br.readLine();
   while(s!=null){
      //阻塞,直到用户输入exit
     if(s.equalsIgnoreCase( "exit")) break;
     System.out.println(s.toUpperCase());
     s = br.readLine();
   }
   br.close();
 } catch (IOException e) {
   e.printStackTrace();
 }
}
}

  • 数据流:

DataInputStream:数据输入流允许应用程序以与机器无关方式从底层输入流中读取基本 Java 数据类型。应用程序可以使用数据输出流写入稍后由数据输入流读取的数据。

DataOutputStream:数据输出流允许应用程序以适当方式将基本 Java 数据类型写入输出流中。然后,应用程序可以使用数据输入流将数据读入。

 

             // 此类实现了一个输出流,其中的数据被写入一个 byte 数组。
             // 缓冲区会随着数据的不断写入而自动增长。
             // 可使用 toByteArray() 和 toString() 获取数据
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
             // DataOutputStream 将基本 Java 数据类型写入输出流
            DataOutputStream dos = new DataOutputStream(baos);
             try {
                   // 输出随机数Double 和 true Boolean
                  dos.writeDouble(Math. random());
                  dos.writeBoolean( true);
             
                   // ByteArrayInputStream 包含一个内部缓冲区,
                  // 该缓冲区包含从流中读取的字节
                  ByteArrayInputStream bais = 
                       new ByteArrayInputStream(baos.toByteArray());
                  System. out.println(bais.available());
                  DataInputStream dis = new DataInputStream(bais);
                   // 先写先读,队列
                  System. out.println(dis.readDouble());
                  System. out.println(dis.readBoolean());
                  dos.close();  dis.close();
            } catch (IOException e) {
                  e.printStackTrace();
            }
-------------------------------------------------------------------------------------
OutPut: 
9
0.24384757082225805
true
-----------------------------------------------------------------------------------


  • Print流:
PrintWriter和PrintStream都属于输出流,分别针对于字符字节。不会抛出异常,有自动flush功能。



//  system.out重新设置
// 输出到文件中

public class TestPrintStream1 {
  public static void main(String[] args) {
    PrintStream ps = null;
    try {
      FileOutputStream fos =
              new FileOutputStream("d:\\bak\\log.dat");
      ps = new PrintStream(fos);
    } catch (IOException e) {
      e.printStackTrace();
    }
    if(ps != null){
      System.setOut(ps);
    }
    int ln = 0;
    for(char c = 0; c <= 60000; c++){
      System.out.print(c+ " ");
      if(ln++ >=100){ System.out.println(); ln = 0;}
    }
  }
}


// open file , read, print to screen

public class TestPrintStream2 {
  public static void main(String[] args) {
    String filename = args[0];
    if(filename!=null){list(filename,System.out);}
  }
  public static void list(String f,PrintStream fs){
    try {
      BufferedReader br =
                  new BufferedReader(new FileReader(f));

      String s = null;
      while((s=br.readLine())!=null){
        fs.println(s);           
      }
      br.close();
    } catch (IOException e) {
      fs.println("无法读取文件");
    }
  }
}


// read standard system.in, write to file
public class TestPrintStream3 {
  public static void main(String[] args) {
    String s = null;
    BufferedReader br = new BufferedReader(
                        new InputStreamReader(System.in));

    try {
      FileWriter fw = new FileWriter
                           ("d:\\bak\\logfile.log", true); //Log4J
      PrintWriter log = new PrintWriter(fw);
      while ((s = br.readLine())!=null) {
        if(s.equalsIgnoreCase("exit")) break;
        System.out.println(s.toUpperCase());
        log.println("-----");
        log.println(s.toUpperCase());
        log.flush();
      }
      log.println("==="+new Date()+"===");
      log.flush();
      log.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}




  • Object流:
直接将Object写入或读出

如果想把对象序列化,那么要继承serializable【空接口,标记类为可序列化】
transient 透明,修饰的成员变量在序列化的时候不予考虑
externalizable接口【控制类是如何序列化的】(实现了它,等于实现了serializable)【很少用】

// 先将t对象写入文件
// 然后读取t对象

public class TestObjectIO {
     public static void main(String args[]) throws Exception {
          T t = new T();
          t.k = 8;
          FileOutputStream fos = new FileOutputStream("d:/share/java/io/testobjectio.dat");
          ObjectOutputStream oos = new ObjectOutputStream(fos);
          oos.writeObject(t);
          oos.flush();
          oos.close();
         
          FileInputStream fis = new FileInputStream("d:/share/java/io/testobjectio.dat");
          ObjectInputStream ois = new ObjectInputStream(fis);
          T tReaded = (T)ois.readObject();
          System.out.println(tReaded.i + " " + tReaded.j + " " + tReaded.d + " " + tReaded.k);
         
     }
}


// transient 透明,修饰的成员变量在序列化的时候不予考虑
class T
     implements Serializable
{
     int i = 10;
     int j = 9;
     double d = 2.3;
     transient int k = 15;
}


 

0 0
原创粉丝点击