Java IO流简单使用

Java IO流简单使用

也许是以前IO方面接触的比较少,我对于读和写的概念老是混淆。 
趁着现在实习比较闲小结一下,我个人理解读和写都是针对程序,分别就是程序的输入和输出,或者叫读入写出。

 

 

字节流:

  • InputStream
  • OutputStream

字符流:

  • Writer
  • Reader

字节流到字符流的转换

  • InputStreamReader
  • OutputStreamWriter 
    (字符到字节: byte[] bs=str.getBytes(“UFT-8”)自己注意编码格式,当然还有很多转换方法)

File相关的读和写

实例

首先File类与文件读写无关,主要是一些文件的属性和一些创建、删除、结构列出等操作 
创建如下的文件结构,然后列出所有文件和目录。

  1. root 
    • 123.txt
    • child 
      1. 456.txt
package www.zcs.com;
import java.io.File;
import java.io.IOException;

public class FileTest {

    public static void main(String[] args) throws IOException, IllegalAccessException {
        File root = new File("E:\\test");
        if (!root.exists())
            root.mkdir();
        File file1 = new File("E:\\test\\123.txt");
        if (!file1.exists())
            file1.createNewFile();
        File file2 = new File("E:\\test\\child");
        if (!file2.exists())
            file2.mkdir();
        File file11 = new File("E:\\test\\child\\456.txt");
        if (!file11.exists())
            file11.createNewFile();
        listDiretory(root);
    }

    /**
     * 列出指定目录下的所有文件和目录
     * 
     * @param dir
     * @throws IllegalAccessException
     */
    public static void listDiretory(File dir) throws IllegalAccessException {
        for (File f : dir.listFiles()) {
            if (f.isFile())
                System.out.println(f);
            if (f.isDirectory()) {
                System.out.println(f);
                listDiretory(f);
            }
        }
    }

}

 

输出如图

Alt text

File的读写

下面也包含关于字节和字符的转换

package www.zcs.com;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

public class StreamWithRW {

    public static void main(String[] args) throws IOException {
        String file = "C:/Users/Administrator/Desktop/stream.txt";
        String charset = "UTF-8";
        FileOutputStream outputStream = new FileOutputStream(file);//默认如果文件存在,则会覆盖。若想在文件里追加内容new FileOutputStream(file,true)
        OutputStreamWriter writer = new OutputStreamWriter(outputStream, charset);
        try {
            writer.write("这是我要写入的中文");
        } finally {
            writer.close();
        }
        // 可以替换成如下代码
        // try{
        // outputStream.write("这是我要写入的中文".getBytes(charset));
        // }finally{
        // outputStream.flush();
        // outputStream.close();
        // }
        FileInputStream inputStream = new FileInputStream(file);
        InputStreamReader reader = new InputStreamReader(inputStream, charset);
        StringBuffer buffer = new StringBuffer();
        char[] buf = new char[64];
        int count = 0;
        try {
            while ((count = reader.read(buf)) != -1)
                buffer.append(buf, 0, count);
        } finally {
            reader.close();
        }
        System.out.print(buffer.toString());
    }

}

小结:

字节流

OutputStream本身只能读取一个字节,读一个Int可以通过右移来实现的 

DataOutputStream:对”OutputStream”功能的扩展,可以更加方便的读取int,long,字符等类型数据 
writeInt()/writeDouble()/writeUTF()。 

BufferedOutputStream缓冲读取,大文件时效率更高 

字符流 
BufferedReader readLine 一次读一行 
BufferedWriter/PrintWriter 中write方法不识别换行,需要writeNewLine/println可以识别

扩展

对象序列化和反序列化简单使用 
1、对象序列化就是将Object转换为byte序列,反之叫对象的反序列化 
2、序列化流(ObjectinputStream)是过滤流—writeobject 反序列化流(ObjectInputStream)–readObject 
3、序列化接口(Serializable) 
对象必须实现序列化借口,才能进行序列化 

把自己创建的一个类序列化写到某个.dat文本里,然后反序列化读出
package www.zcs.com.ioTest;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class SerializedTest {

    public static void main(String[] args) throws FileNotFoundException, ClassNotFoundException, IOException {
        Student s=new Student(12,"小明");
        String sc="./data/test.dat";
        serializedWrite(s,sc);
        deserializedPrint(sc);
    }

    /*
     * 任务: 把自己创建的一个类序列化写到某个.dat文本里,然后反序列化读出
     */
    public static void serializedWrite(Object ob,String sc) {
         try {
            ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream(sc));
            out.writeObject(ob);
            out.flush();
            out.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void deserializedPrint(String sc) throws FileNotFoundException, IOException, ClassNotFoundException {
        ObjectInputStream  in=new ObjectInputStream(new FileInputStream(sc));
        Student s=(Student)in.readObject();
        s.show();
    }
}

class Student implements Serializable{
    private int age;
    private String name;

    public Student(int age, String name) {
        super();
        this.age = age;
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    public void show(){
        System.out.println(age+"  "+name);
    }
} 
 
posted @ 2017-04-19 14:51  leftcity  阅读(268)  评论(0编辑  收藏  举报