星星博客 »  > 

Java基础-IO流(BIO)

IO

  • 文件
    • 什么是文件?
    • 文件一般存储在哪里?
    • Java程序如何访问文件属性
    • File使用
    • 流的基本概念
    • 流的分类
      • InputStream输入字节流
        • FileInputSteam
        • ByteArrayInputStream
        • ObjectInputStream
        • DataInputStream
        • BufferedInputStream
      • OutputStream字节输入流
        • FileOutputStream
        • ByteArrayOutputStream
        • BufferedOutputStream
        • ObjectOutputStream
        • DataArrayOutputStream
        • PrintSream
      • Reader输入字符流
        • FileReader
        • CharArrayReader
        • BufferedReader
      • Writer输出字符流
        • FileWriter
        • CharArrayWriter
        • BufferedWriter
      • 处理流
        • InputStreamReader
        • OutputStreamWriter

文件

什么是文件?

  • 文件可认为是相关记录或放在一起的数据集合

文件一般存储在哪里?

  • 机械硬盘,固态硬盘,光盘,软盘等

Java程序如何访问文件属性

  • 从磁盘中读取文件是以页为单位的,单位大小是可能4kb,也可能是4kb的N倍,电脑配置不一样大小不一样,但是都是以页为单位的,并不是说你想读取多大字节就读多大的字节,这样效率太低了。
  • 磁盘预读(预读的长度一般为页(page)的整数倍):页是存储器的逻辑块,操作系统往往将主存和磁盘存储区分割为连续的大小相等的块,每个存储块称为一页(在许多操作系统中,一页的大小为4kb)。主存和磁盘以页为单位来交换数据
  • 局部性原理:发现程序和数据都有聚集成群的倾向,在一个时间段内,仅使用其中的一小部分称空间局部性;或者最近心访问过的程序代码和数据,很快又被访问的可能性很大称时间局部性

File使用

import java.io.File;
import java.io.IOException;

/**
 *
 */
public class FileDemo {
    public static void main(String[] args) {
        File file = new File("abc.txt");
        System.out.println(file.canExecute());
        System.out.println(file.canRead());
        System.out.println(file.canWrite());
        try {
           file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //判断当前文件是否存在
        System.out.println(file.exists());
        //获取当前文件名称
        System.out.println(file.getName());
        //获取当前文件绝对路径
        System.out.println(file.getAbsolutePath());
        //获取当前文件的规范路径
        System.out.println(file.getAbsoluteFile());
        //获取操作系统文件分隔符
        System.out.println(File.separator);
        //获取当前文件的父路径名称,如果没有返回空,如有有返回父路径名称
        System.out.println(file.getParent());

        //无论当前路径是否存在只要给出具体路径,都可以返回响应的路径名称
        File file1 = new File("c:/ccc.txt");
        System.out.println(file1.getAbsolutePath());

        System.out.println(file1.isDirectory());
        System.out.println(file1.isFile());

        File file2 = new File("c:/");
        String[] list = file2.list();
        for (String s : list) {
            System.out.println(s);
        }
        File[] files = file2.listFiles();
        for (File file3 : files) {
            System.out.println(file3);
        }

        File file3 = new File("c:/a");
        //创建一级目录
        file3.mkdir();

        File file4 = new File("c:/a");
        //创建多级目录
        file4.mkdirs();
        //文件在遍历的时候,会出现控制着异常的情况,原因是当前文件受系统保护,某些文件没有访问的权限,此时会报空指针异常
        println(new File("c:/"));
    }

    public static void println(File file){
        if (file.isDirectory()){
            File[] files = file.listFiles();
            for (File file1 : files) {
                println(file1);
            }
        }else {
            System.out.println("单个文件直接打印");
            System.out.println(file.getAbsolutePath());
        }
    }
}

流的基本概念

  • 如何读写文件?
  • 通过流来读写文件
    流是指一连串流动的字符,先进先出的方式
  • 送信息的通过
    数据源:inputStream ->目的地:outputStream

流的分类

InputStream输入字节流

FileInputSteam

/**
 * 在Java中需要读写文件中的数据的时候,需要使用流的概念
 *      流表示从一个文件将数据传送到到另一个文件,包含一个流向的问题
 *          最终需要选择一个参照物,当前程序作为参照物
 *          从一个文件中的数据读取到程序里面来叫做输入流
 *          从程序输出数据到另一个文件做输出流
 *  数据源:
 *      - data source 提供原始数据的
 *      - 原始媒介。常见的:数据库、文件、其他程序、内存、网络连接、io设备
 *      - 数据源就像冰箱,流就像水管中流着的水流,程序是我们最终的用户
 *      - 流是一个抽象动态的概念,是一连串连续动态的数据集合
 *   注意:在编写io流的时候,一定要注意关闭流,因为在进行文件写入写出的数据需要建立起连接,在数据传输或者写入完成后不关闭的话
 *   会占用系统资源(内存资源、磁盘资源等等)。例如在Linux(一切皆文件)中是有文件个数限制的,1g代表10万个文件,而且打开多少个文件
 *   是和资源挂钩的
 *      步骤:
 *          1、选择合适的io流对象
 *          2、创建对象
 *          3、传输数据
 *          4、关闭流对象
 */
public class InputStreamDemo {
    public static void main(String[] args) {
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream("abc.txt"); //变量作用域在try里面
            int length = 0;
            //添加到缓冲区的方式进行读取,每次将数据添加到缓冲区,一次读取,当缓冲区满了之后,一个个字节进行读取
            byte[] buffer = new byte[1024];
            //length代表有多少个字节
            while((length = inputStream.read(buffer)) != -1){
                System.out.println(new String(buffer,5,length));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

ByteArrayInputStream

public class ByteArrayInputStreamDemo {
    public static void main(String[] args) {
        String s = "byte";
        //把字符串转为字节,并存在字节缓冲区
        byte[] bytes = s.getBytes();
        //把字节存放在ByteArrayInputStream 对象里面
        ByteArrayInputStream byteOutputStream = new ByteArrayInputStream(bytes);
        int read = 0;
        while((read = byteOutputStream.read())!=-1){
        	//跳过此输入流中的输入字节。
            byteOutputStream.skip(2);
            System.out.println((char) read);
        }
        try {
            byteOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

ObjectInputStream

/**
 *  如果需要将对象进行IO流进行传输,必须要实现序列化接口
 *  当前类中必须声明一个
 *  transient:使用此关键字修饰的变量,在进行序列化的时候,不会被序列化
 */
public class Person implements Serializable {
    long serialVersionUID = 1L;
    private int id;
    private String name;
    transient private String pwd;

    public Person(int id, String name, String pwd) {
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", pwd='" + pwd + '\'' +
                '}';
    }
}
/**
 * ObjectInputStream 对象输入字符流
 */
public class ObjectInputStreamDemo {
    public static void main(String[] args) {
        FileInputStream fileInputStream = null;
        ObjectInputStream objectInputStream = null;
        try {
             fileInputStream = new FileInputStream("123.txt");
            objectInputStream = new ObjectInputStream(fileInputStream);
            Object o = objectInputStream.readObject();
            if (o instanceof Person){
                Person person =(Person) o;
                System.out.println(person);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                objectInputStream.close();
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

DataInputStream

DataInputStream:数据字节流 可以输入各种类型的字节流
public class DataInputStreamDemo {
    public static void main(String[] args) {
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        DataInputStream dataInputStream = null;
        DataOutputStream dataOutputStream = null;

        try {
            fileOutputStream = new FileOutputStream("bb.txt");
            fileInputStream = new FileInputStream("bb.txt");
            dataOutputStream = new DataOutputStream(fileOutputStream);
            dataInputStream = new DataInputStream(fileInputStream);
            dataOutputStream.writeUTF("cc");//写入字符串
            dataOutputStream.writeBoolean(true);//写入布尔类型的值
            dataOutputStream.writeInt(11);//写入整数类型的值
            //读的顺序要和写入的顺序类型一致
            System.out.println(dataInputStream.readUTF());
            System.out.println(dataInputStream.readBoolean());
            System.out.println(dataInputStream.readInt());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                dataInputStream.close();
                dataOutputStream.close();
                fileInputStream.close();
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

BufferedInputStream

public class BufferInputStreamDemo {
    public static void main(String[] args) {
        //当创建一个bufferInputStream,将创建一个内部缓冲区数组,把数据先放到缓冲区里而不是一个一个的进行读取
        BufferedInputStream bufferedInputStream = null;
        try {
            bufferedInputStream = new BufferedInputStream(new FileInputStream("aaa.txt"));
            //System.out.println(bufferedInputStream.skip(1));
            //System.out.println(bufferedInputStream.read());
            byte[] buffer = new byte[1024];
            int length = 0;
            while ((length = bufferedInputStream.read(buffer))!= -1){
                System.out.println(new String(buffer,0,length));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bufferedInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

OutputStream字节输入流

FileOutputStream

public class OutputStreamDemo {
    public static void main(String[] args) {

        File file = new File("aaa.txt");
        OutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(file);
            outputStream.write(99);
            outputStream.write("\r\nmashibing".getBytes());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

ByteArrayOutputStream

public class ByteArrayInputStreamDemo {

    public static void main(String[] args) {

        String str = "ccc";
        byte[] buffer = str.getBytes();
        ByteArrayInputStream byteArrayInputStream = null;
        byteArrayInputStream = new ByteArrayInputStream(buffer);
        int read = 0;
        while((read = byteArrayInputStream.read())!=-1){
            byteArrayInputStream.skip(4);
            System.out.println((char)read);
        }
        try {
            byteArrayInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

BufferedOutputStream

public class BufferedOutputStreamDemo {
    public static void main(String[] args) {

        File file = new File("123.txt");
        FileOutputStream fileOutputStream = null;
        BufferedOutputStream bufferedOutputStream =null;
        try {
            fileOutputStream = new FileOutputStream(file);
            bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
            bufferedOutputStream.write(98);
            bufferedOutputStream.write("www.baidu.com".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                bufferedOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

ObjectOutputStream

/**
*ObjectOutputStream在进行对象传输的时候,对象以字节形式传输
*/
public class ObjectOutputStreamDemo {
    public static void main(String[] args) {

        FileOutputStream fileOutputStream = null;
        ObjectOutputStream objectOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream("abc.txt");
            objectOutputStream = new ObjectOutputStream(fileOutputStream);
            objectOutputStream.writeUTF("ccc");
            objectOutputStream.writeObject(new Person(1,"zhangsan","123456"));
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                objectOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

DataArrayOutputStream

PrintSream

/**
*PrintSream:打印流
*/
public class PrintStreamDemo {
    public static void main(String[] args) {
        PrintStream printStream = new PrintStream(System.out);
        printStream.print("dfd");
        printStream.write(11);
        try {
            printStream.write("asa".getBytes());
            printStream.println();
            //格式化输出 %s字符串="aaa" %d整数==123 %.2f浮点数=111.11小数点后保留2位
            printStream.printf("%s--%d--%.2f","aaa",123,111.111);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
        }
        printStream.close();
    }
}

Reader输入字符流

FileReader

/**
 * 字符流可以直接读取中文汉字,而字节流在处理的时候会出现中文乱码
 */
public class ReaderDemo3 {
    public static void main(String[] args) {
        Reader reader = null;
        try {
            reader = new FileReader("abc.txt");
            int length = 0;
            char[] chars = new char[1024];
            //添加缓冲区
            while((length = reader.read(chars))!=-1){
                System.out.println(new String(chars,0,length));
            }
//            int read = reader.read();
//            System.out.println((char)read);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

CharArrayReader

public class CharArrayReaderTest {
    public static void main(String[] args) {

        char[] chars = "cc".toCharArray();
        CharArrayReader charArrayReader = new CharArrayReader(chars);
        try {
            int read = 0;
            while((read = charArrayReader.read())!=-1){
                System.out.println((char)read);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            charArrayReader.close();
        }

    }
}

BufferedReader

public class BufferedReaderTest {
    public static void main(String[] args) {

        BufferedReader  reader = null;

        try {
            reader = new BufferedReader(new FileReader("aaa.txt"));
            String read = null;
            //readLind()读取一行数据效率很高
            while((read = reader.readLine())!=null){
                System.out.println(read);
            };
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

Writer输出字符流

FileWriter

/*
* 什么时候需要加flush,什么时候不加flush
*      最保险的方式,在输出流关闭之前每次都flush一下,然后再关闭
*      当某一个输出流对象中带有缓冲区的时候,就需要进行flush
*
* */

public class WriterDemo {
    public static void main(String[] args) {
        File file = new File("writer.txt");
        Writer writer = null;
        try {
            writer = new FileWriter(file);
            writer.write("www.ccc.com");
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

CharArrayWriter

public class charArrayWriterTest {

    public static void main(String[] args) {
        CharArrayWriter charArrayWriter = new CharArrayWriter();
        charArrayWriter.write(97);
        charArrayWriter.write(98);
        charArrayWriter.write(99);
        System.out.println(charArrayWriter);
        charArrayWriter.close();
    }
}

BufferedWriter

public class BufferedWriterTest {

    public static void main(String[] args) {

        BufferedWriter bufferedWriter = null;
        FileWriter fileWriter = null;
        try {
            fileWriter =  new FileWriter(new File("abc.txt"));
            bufferedWriter = new BufferedWriter(fileWriter);
            bufferedWriter.append("ccc");//追加写
            bufferedWriter.newLine();//换行
            bufferedWriter.append("bbb");
            bufferedWriter.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                fileWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                bufferedWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

处理流

InputStreamReader

public class InputStreamReaderDemo {
    public static void main(String[] args) {


        File file = new File("abc.txt");
        FileInputStream fileInputStream = null;
        InputStreamReader inputStreamReader = null;

        try {
            fileInputStream = new FileInputStream(file);
            inputStreamReader = new InputStreamReader(fileInputStream);
            //为什么没有用循环的方式,因为数据比较少,无法占用1024个缓存区,只需要读取一次即可
            char[] chars = new char[1024];
            int length = inputStreamReader.read(chars);
            System.out.println(new String(chars,0,length));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                inputStreamReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

OutputStreamWriter

public class OutputStreamWriterDemo {
    public static void main(String[] args) {

        File file = new File("abc.txt");
        OutputStreamWriter outputStreamWriter = null;
        FileOutputStream fileOutputStream = null;


        try {
            long time = System.currentTimeMillis();
            fileOutputStream = new FileOutputStream(file);
            outputStreamWriter = new OutputStreamWriter(fileOutputStream,"iso8859-1");
            outputStreamWriter.write(99);
            outputStreamWriter.write("ccc");
            outputStreamWriter.write("abcdefg",0,5);
            long end = System.currentTimeMillis();
            System.out.println(end-time);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭流对象的时候,建议按照创建的顺序的逆序来进行关闭
            try {
                outputStreamWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }


    }
}

相关文章