字节流读取文件

public  void readFileByBytes(String fileName) {
        File file = new File(fileName);
        InputStream in = null;
        try {
            System.out.println("以字节为单位读取文件内容,一次读一个字节:");
            // 一次读一个字节
            in = new FileInputStream(file);
            int tempbyte;
            while ((tempbyte = in.read()) != -1) {
                System.out.write(tempbyte);
            }
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
            return;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e1) {
                }
            }
        }
    }
Java字节流读取文件可以使用FileInputStream类。通过创建一个FileInputStream对象,并传入要读取文件路径作为参数,然后使用read()方法来逐个字节地读取文件内容。读取到的字节可以通过转换成字符来得到文件的内容。通常可以使用一个循环来读取文件中的所有字节,直到读取文件末尾的标志(-1)为止。最后,记得关闭流对象,释放资源。下面是一个示例代码: ```java public static void main(String[] args) { FileInputStream fis = null; try { // 创建一个FileInputStream对象,指向要读取文件 fis = new FileInputStream("example.txt"); // 创建一个StringBuilder对象,用于存储文件内容 StringBuilder sb = new StringBuilder(); // 逐个字节读取文件内容 int b; while ((b = fis.read()) != -1) { // 将字节转换为字符并追加到StringBuilder中 sb.append((char) b); } // 打印文件内容 System.out.println(sb.toString()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 关闭流对象,释放资源 try { if (fis != null) { fis.close(); } } catch (IOException e) { e.printStackTrace(); } } } ``` 以上代码通过创建一个FileInputStream对象fis来读取example.txt文件的内容,并将每个字节转换为字符追加到StringBuilder对象中。最后使用toString()方法将StringBuilder对象转换为字符串,并打印文件内容。注意在读取文件时,需要处理可能抛出的FileNotFoundException和IOException异常,并在最后关闭流对象。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值