文件读写中的inputStream和outputStream

本文介绍了Java中InputStream和OutputStream在文件读写中的作用。InputStream用于读取数据,如通过read()方法读取字节;OutputStream用于写入数据,如FileOutputStream的构造函数用于指定文件写入。关键参数append决定了是否追加内容到文件。此外,讨论了如何实现文件的持续性和换行写入,以及在复制文件时,OutputStream如何确保容量并限制其最大值。同时指出,如果指定文件不存在,FileOutputStream会尝试创建它,但需确保有相应权限。
摘要由CSDN通过智能技术生成

InputStream(输入流)用来读取数据

OutputStream(输出流)用来写出数据

 

public int read();//从此输入流中读取一个数据字节

public int read(byte[] b);//从此输入流中将最多b.length个字节数据读取到byte数组中

public int read(byte b[]) throws IOException {
    Object traceContext = IoTrace.fileReadBegin(path);
    int bytesRead = 0;
    try {
        bytesRead = readBytes(b, 0, b.length);
    } finally {
        IoTrace.fileReadEnd(traceContext, bytesRead == -1 ? 0 : bytesRead);
    }
    return bytesRead;
}

public int read(byte[] b,int off,int len);//从此输入流中将最多 len 个字节的数据读入一个 byte 数组中。off:目标数组 b 中的起始偏移量。

public int read(byte b[], int off, int len) throws IOException {
    Object traceContext = IoTrace.fileReadBegin(path);
    int bytesRead = 0;
    try {
        bytesRead = readBytes(b, off, len);
    } finally {
        IoTrace.fileReadEnd(traceContext, bytesRead == -1 ? 0 : bytesRead);
    }
    return bytesRead;
}
package fileDo;

import java.io.FileInputStream;

/**
 * @auther **
 * @date 7/31/2018 3:02 PM
 */
public class FileReadStream {
    public static void main(String[] args){
        String content = null;
        try{
            int size = 0;
            //定义一个字节缓冲区,该缓冲区的大小根据需要来定义
            byte[] buffer = new byte[1024];
            FileInputStream fis = new FileInputStream("d:/read.txt");
            //循环读取文件中的数据
            while((size = fis.read(buffer)) != -1){
                content = new String(buffer, 0, size);
                System.out.println(content);
            }
            fis.close();
        }catch (Exception e){
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值