用InputStream读出来转换成String类型

本文展示了一个使用Java进行文件读取的基本示例,通过FileInputStream将本地文件e:/123.txt的内容读入内存,并将读取的数据转换为字符串输出。

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

public class demo {
    public static void main(String[] args) {
        //先把图片读入到内存--然后写到 文件
         FileInputStream fis=null;     
            File q=new File("e:/123.txt");
            //因为File没有读写的能力,所以需要使用InputStream;
            try {
                fis=new FileInputStream(q);
                //定义一个字节数组,相当于缓存
                byte[] bytes=new byte[1024];
                int n=0;//得到实际读取到的字节数 读到最后返回-1
                //循环读取
                while((n=fis.read(bytes))!=-1)//把fis里的东西读到bytes数组里去
                {
                    //把字节转成String 从0到N变成String
                    String w=new String(bytes,0,n);
                    System.out.println(w);

                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            finally{
                //一定要关闭文件流。并且关闭文件流必须放在finally里面
                try {
                    fis.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
          }
}

 

转载于:https://www.cnblogs.com/NuoChong/p/11133880.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值