FileInputStream文件输入流,读取文件内容

本文展示了一个使用Java FileInputStream类从文件中读取数据的例子。通过创建FileInputStream实例并使用read方法,可以逐字节读取文件内容。文章详细解释了如何处理文件未找到和I/O异常。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

public class FileInputStreamTest {

    public static void main(String[] args) {
    
        try {
            
            //找到目标文件
            File file = new File("D:\\test.txt");
            
            //建立数据的输入通道
            FileInputStream fileInputStream = new FileInputStream(file);
            
            //建立缓冲数组配合循环读取文件的数据。
            int length = 0; //保存每次读入缓冲区的字节总数
            byte[] buf = new byte[1024]; //存储读取到的数据  
            StringBuilder StringBuilder = new StringBuilder();
            
            while((length = fileInputStream.read(buf))!=-1){ // read方法如果已经到达文件末尾而没有更多的数据,则返回 -1。
                StringBuilder.append(new String(buf,0,length));
            }
            System.out.println("test.txt文件内容是:\n" + StringBuilder.toString());
            
            //关闭资源
            fileInputStream.close();
     
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

青春1314

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值