【JAVA】IO详解

综合各种网文得出此文

引用

[1]http://blog.csdn.net/yczz/article/details/38761237

[2]http://www.cnblogs.com/pepcod/archive/2013/01/20/2913435.html

[3]http://blog.csdn.net/zhangerqing/article/details/8466532

首先 先挂一图,这个图是java中类的层次结构 引用自[1] 。

Java的IO是基于流的。

流是什么:

  流相当于一个连续不间断的信息,中间不加某些分隔符,信息从源端传到目的端后不改变,传什么就拿到什么

  比如TCP就是面向流的,也就是从Client传到Server端,传的是什么就是什么 不会给第一次第二次send之间加上某些分隔符。

  而UDP是面向报文的,也就是第一次传会在前面加上报头,用来区分每一次传输的信息。

  举个例子:

    流就是 要传输 hello world   收到的就是 hello world

    非流的 就是传输hello world  可能收到的是 $hello $world 单词之间加上用于分割的信息。

  你可以想像

    面向流的相当于从你家到自来水公司连一个水管,自来水公司给你的就是你在家获得的

    而面向报文的(非流)的相当于自来水公司向你家里送水,一桶一桶的送。你获得的可能不只是水,还有水桶。

输入流和输出流:

  流的方向分为输入和输出

  计算机存储有内存和外存,也就是内存和硬盘

  硬盘可以看做是个仓库,内存才是工厂。你要进行工作要在工厂里做,要把原料从仓库拿到工厂里

  也就是从硬盘把文件送到内存里面,这叫输入。对于你的程序来说,这就是输入。因为关键的地点在内存

  而你处理之后的数据要把它保存到仓库中,就是输出,也就是从内存到硬盘

  从此,流根据方向的不同分成了两种

  输入流  从硬盘输入到内存  Input

  输出流 从内存输出到内存  Output

字节流和字符流:

  根据流中信息的基本单位的不同,流分为字节流和字符流,也就是字节流由一个一个字节组成,而字符流由一个一个字符组成,每个字符在java中由两个字节组成 Unicode16

  在硬盘中,所有文件都是由字节存储的,包括文本文件,但是实际中,很多文件都是文本文件,也就有了字符流的产生,

  从字面上就可以看出,字符流适合于对字符文件的输入输出操作,也就是文本文件。因为是以字符为单位处理的。

  字节流适用于没有不包含字符的文件,比如 音频 视频 图片等。

JavaIO操作的对象:

  字节数组,String,文件,管道,流,网络资源

  每个对象都有一个对应的类用来针对他们来操作。

JavaIO的基类:

  Java中根据字节流和字符流 输出和输入分成了四个类

      字节流         字符流

  输入  InputStream    Reader

  输出  OutputStream  Writer

File类:

  File从字面上来讲是文件,在Linux等系统文件分为两种,一种是普通文件,一种是目录文件

  File主要是为了进行磁盘操作,比如文件的创建,文件夹的创建等等。

  1.构造 File f=new File("C:/1.txt);  File就表示一个路径所表示的东西。

  2.如果是一个目录 那么可以调用list方法 f.list()来获得目录中的文件名返回的是String[]

  3.还有很多其他的功能,查看API即可

InputStream:

  抽象类,所有输入字节流的基类,主要操作就是read()

  对应的各种对象的子类:

  ByteArrayInputStream:处理字节数组的类,允许将内存的缓冲区当做InputStream使用。

  StringBufferInputStream:将String转换成InputStream,内部实现用的是StringBuffer。

  FileInputStream:从文件中读取数据。

  PipedInputStream:用于从管道中读取数据。

  SequenceInputStream:将多个流对象转化成一个InputStream。

  FilterInputStream:装饰器类,为其它InputStream类提供功能。

Reader

  抽象类,所有输入字符流的基类 只要也是read()

  对应各种对象的子类:

引用[3]中的javaio经典例子:

BufferedReader的使用:

  1.缓冲输入文件 用BufferedReader

     

 1 public static String read(String filename) throws Exception {  
 2 
 3            BufferedReader br = new BufferedReader(new FileReader(filename));  
 4 
 5            String s;  
 6 
 7            StringBuffer sb = new StringBuffer();       while ((s = br.readLine()) != null) {  
 8 
 9                 sb.append(s + "
");  
10 
11            }  
12 
13            br.close();  
14 
15       return sb.toString();  
16 
17        } 

    BufferedReader是一个包装器类,用来包装一个普通的Reader。让普通的Reader有更好的使用方式及性能

    一般来说用一个Reader或者Writer或者InputStream或者OutputStream都要仿佛Buffered里面进行提高性能操作

StringReader的使用:

  数据源是字符串String对象,

  相当于从内存读入。

  也可以按行读等。

 1 import java.io.*;
 2 public class SRDemo
 3 {
 4   public static void main(String args[]) throws IOException
 5   {
 6     String s1 = "For outsiders
the Software engineer
looks housed
in a golden cage";
 7     StringReader sreader = new StringReader(s1);
 8     BufferedReader breader = new BufferedReader(sreader);
 9         
10     String s2;
11     while( ( s2 = breader.readLine() ) != null)
12     {
13       System.out.println(s2);
14     }
15     breader.close();  sreader.close();
16   }
17 }

引用[3]:

  标准文件读写类的写法

  

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;

/**
 * 一个非常实用的文件操作类 . 2012-12-19
 * 
 * @author Bruce Eckel , edited by erqing
 * 
 */
public class TextFile extends ArrayList<String> {

    private static final long serialVersionUID = -1942855619975438512L;

    // Read a file as a String
    public static String read(String filename) {
        StringBuilder sb = new StringBuilder();
        try {
            BufferedReader in = new BufferedReader(new FileReader(new File(
                    filename).getAbsoluteFile()));
            String s;
            try {
                while ((s = in.readLine()) != null) {
                    sb.append(s);
                    sb.append("
");
                }
            } finally {
                in.close();
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return sb.toString();
    }

    // Write a single file in one method call
    public static void write(String fileName, String text) {
        try {
            PrintWriter out = new PrintWriter(
                    new File(fileName).getAbsoluteFile());
            try {
                out.print(text);
            } finally {
                out.close();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // Read a file,spilt by any regular expression
    public TextFile(String fileName, String splitter) {
        super(Arrays.asList(read(fileName).split(splitter)));
        if (get(0).equals(""))
            remove(0);
    }

    // Normally read by lines
    public TextFile(String fileName) {
        this(fileName, "
");
    }

    public void write(String fileName) {
        try {
            PrintWriter out = new PrintWriter(
                    new File(fileName).getAbsoluteFile());
            try {
                for (String item : this)
                    out.println(item);
            } finally {
                out.close();
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    // test,I have generated a file named data.d at the root
    public static void main(String[] args) {

        /* read() test */
        System.out.println(read("data.d")); // testing is OK!

        /* write() test */
        write("out.d", "helloworld
egg"); // testing is OK!

        /* constractor test */
        TextFile tf = new TextFile("data.d"); // testing is OK!

    }

}

 标准二进制文件操作类

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * to read the binary file
 * 
 * @author erqing
 * 
 */
public class BinaryFile {

    /* the parametre is a file */
    public static byte[] read(File file) throws IOException {
        BufferedInputStream bf = new BufferedInputStream(new FileInputStream(
                file));
        try {
            byte[] data = new byte[bf.available()];
            bf.read(data);
            return data;
        } finally {
            bf.close();
        }
    }

    /* the param is the path of a file */
    public static byte[] read(String file) throws IOException {
        return read(new File(file).getAbsoluteFile());
    }
}
原文地址:https://www.cnblogs.com/heanqing/p/4909485.html