Java IO 对字节的读取和写出

1 字节的读取

对于字节流的输入,可以分为网络上的字节如文件下载,以及文件如读取文件。

1.1 文件的读取
使用java.io.FileInputStream类来进行对文件的读取,以下是源码中几个重要的方法

package java.io;

public class FileInputStream extends InputStream {

    /**
     *  根据文件绝对路径构造次对象
     */
    public FileInputStream(String name) throws FileNotFoundException {
        this(name != null ? new File(name) : null);
    }

    /**
     * 根据文件构造次对象
     */
    public FileInputStream(File file) throws FileNotFoundException {
        String name = (file != null ? file.getPath() : null);
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkRead(name);
        }
        if (name == null) {
            throw new NullPointerException();
        }
        if (file.isInvalid()) {
            throw new FileNotFoundException("Invalid file path");
        }
        fd = new FileDescriptor();
        fd.attach(this);
        path = name;
        open(name);
    }

    /**
     * 读取一个字节数据
     */
    public int read() throws IOException {
        return read0();
    }

    /**
     * 读取一个字节数组数据
     */
    public int read(byte b[]) throws IOException {
        return readBytes(b, 0, b.length);
    }

    /**
     * 根据指定长度读取一个字节数组数据
     */
    public int read(byte b[], int off, int len) throws IOException {
        return readBytes(b, off, len);
    }

    /**
     * 跳过指定的字节数据后开始读取
     */
    public native long skip(long n) throws IOException;

    /**
     * 返回可读取的数据大小
     */
    public native int available() throws IOException;

    /**
     * 关闭流,释放资源
     */
    public void close() throws IOException {
        synchronized (closeLock) {
            if (closed) {
                return;
            }
            closed = true;
        }
        if (channel != null) {
           channel.close();
        }

        fd.closeAll(new Closeable() {
            public void close() throws IOException {
               close0();
           }
        });
    }
}

1.2 读取文件的demo例子如下:

/**
 * @param file 文件对象
 */
public static void readFile(File file) {
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(file);
        byte[] buffer = new byte[1024 * 1024 * 10];
        int len = 0;
        while (-1 != (len = fis.read(buffer))) {
            System.out.println(new String(buffer, 0, len));
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (null != fis) {
                fis.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

/**
 * @param filePath 文件路径
 */
public static void readFile(String filePath) {
    readFile(new File(filePath));
}

/**
 * 
 * @param file
 *            文件对象
 */
public static void readFile(File file) {
    // java 7 新特性 try-with-resource
    // 不用手动释放资源,程序自动释放,因为FileInputStream实现了AutoCloseable接口
    try (FileInputStream fis = new FileInputStream(file)) {
        byte[] buffer = new byte[1024 * 1024 * 10];
        int len = 0;
        while (-1 != (len = fis.read(buffer))) {
            System.out.println(new String(buffer, 0, len));
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

2 字节的写出

对于字节流的输出,可以分为相应网络请求,以及文件如输出到文件。

2.1 文件的写出
使用java.io.FileOutputStream类来进行对文件的写出操作。以下是源码中比较重要的几个方法:

package java.io;

public class FileOutputStream extends OutputStream {

    /**
     * 创建一个文件输出流,输出到指定文件
     */
    public FileOutputStream(String name) throws FileNotFoundException {
        this(name != null ? new File(name) : null, false);
    }

    /**
     * 创建一个文件输出流,输出到指定文件
     * 如果第二个参数为true,则从此文件末尾开始输出而不是文件头部开始
     */
    public FileOutputStream(String name, boolean append)
        throws FileNotFoundException
    {
        this(name != null ? new File(name) : null, append);
    }

    /**
     * 创建一个文件输出流,输出到指定文件
     */
    public FileOutputStream(File file) throws FileNotFoundException {
        this(file, false);
    }

    /**
     * 创建一个文件输出流,输出到指定文件
     * 如果第二个参数为true,则从此文件末尾开始输出而不是文件头部开始
     */
    public FileOutputStream(File file, boolean append)
        throws FileNotFoundException
    {
        String name = (file != null ? file.getPath() : null);
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkWrite(name);
        }
        if (name == null) {
            throw new NullPointerException();
        }
        if (file.isInvalid()) {
            throw new FileNotFoundException("Invalid file path");
        }
        this.fd = new FileDescriptor();
        fd.attach(this);
        this.append = append;
        this.path = name;

        open(name, append);
    }

    /**
     * 写一个字节到流中,append为true时,写到此文件的末尾
     */
    private native void write(int b, boolean append) throws IOException;

    /**
     * 写一个字节到流中
     */
    public void write(int b) throws IOException {
        write(b, append);
    }

    /**
     * 写一个字节数组或字节数组的一部分到流中
     * append为true时,写到此文件的末尾
     */
    private native void writeBytes(byte b[], int off, int len, boolean append)
        throws IOException;

    /**
     * 写一个字节数组到流中
     */
    public void write(byte b[]) throws IOException {
        writeBytes(b, 0, b.length, append);
    }

    /**
     * 写一个字节数组或字节数组的一部分到流中
     */
    public void write(byte b[], int off, int len) throws IOException {
        writeBytes(b, off, len, append);
    }

    /**
     * 关闭流,释放资源
     */
    public void close() throws IOException {
        synchronized (closeLock) {
            if (closed) {
                return;
            }
            closed = true;
        }

        if (channel != null) {
            channel.close();
        }

        fd.closeAll(new Closeable() {
            public void close() throws IOException {
               close0();
           }
        });
    }
}

2.2 文件输出流的Demo例子如下:

/**
 * 
 * @param file 指定输出文件
 * @param msg 输出内容
 * @param append 是否追加,true 追加 false 不追加
 */
private static void writeToFile(File file, String msg, boolean append) {
    FileOutputStream bos = null;
    try {
        bos = new FileOutputStream(file);
        bos.write(msg.getBytes(), 0, msg.getBytes().length);
        bos.flush();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (null != bos) {
                bos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

/**
 * 
 * @param filePath 指定输出文件路径
 * @param msg 输出内容
 * @param append 是否追加,true 追加 false 不追加
 */
private static void writeToFile(String filePath, String msg, boolean append) {
    writeToFile(new File(filePath), msg, append);
}

/**
* jdk 7 新特性(与FileInputStream一致)
 * @param file 指定输出文件
 * @param msg 输出内容
 * @param append 是否追加,true 追加 false 不追加
 */
private static void writeToFile(File file, String msg, boolean append) {
    try (FileOutputStream bos = new FileOutputStream(file)){
        bos.write(msg.getBytes(), 0, msg.getBytes().length);
        bos.flush();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
发布了40 篇原创文章 · 获赞 11 · 访问量 3万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章