java fileinputstream.read(byte[])_java.io.FileInputStream.read(byte[] b)

本文介绍了如何使用Java的FileInputStream类中的read(byte[])方法来读取文件内容,并通过示例展示了如何读取指定路径下的文本文件。

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

全屏

java.io.FileInputStream.read(byte[] b)读取从此文件输入流b.length个字节数组中。该方法一直阻塞到某些输入可用。

声明

以下是java.io.FileInputStream.read(byte[] b) 方法的声明:public int read(byte[] b)

参数b - 读取字节数组数据。

返回值

该方法将返回读入缓冲区的总字节数,或如果没有更多的数据被读取则返回-1。

异常IOException - 如果发生I/ O错误

例子

下面的例子显示java.io.FileInputStream.read(byte[] b)方法的用法。package cn.sxt;

import java.io.IOException;

import java.io.FileInputStream;

public class FileInputStreamDemo {

public static void main(String[] args) throws IOException {

FileInputStream fis = null;

int i = 0;

char c;

byte[] bs = new byte[4];

try{

// create new file input stream

fis = new FileInputStream("C://test.txt");

// read bytes to the buffer

i=fis.read(bs);

// prints

System.out.println("Number of bytes read: "+i);

System.out.print("Bytes read: ");

// for each byte in buffer

for(byte b:bs)

{

// converts byte to character

c=(char)b;

// print

System.out.print(c);

}

}catch(Exception ex){

// if any error occurs

ex.printStackTrace();

}finally{

// releases all system resources from the streams

if(fis!=null)

fis.close();

}

}}

假设我们有一个文本文件c:/ test.txt,它具有以下内容。该文件将被用作输入到我们的示例程序:ABCDEF

让我们来编译和运行上面的程序,这将产生以下结果:Number of bytes read: 4

Bytes read: ABCD

分享到:

0评论

14487a65ea137d8f9ac97cdce44a0324.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值