还是inputstream类的read方法返回值的问题

xiaobineric 2008-04-29 10:36:33
代码:

import java.io.*;
public class FileApp {
public static void main(String[] args){
byte[] buffer=new byte[25];
try{
FileInputStream fileIn = new FileInputStream("1.txt");
int bytes=fileIn.read(buffer);
System.out.println(bytes);
}
catch (Exception e){
System.out.println(e);
}
}
}

1.txt内容为“abc12345678”,read方法以字节数组为参数,结果返回24。把字节数组buffer的长度设为25以上,返回还是24。只有小于25时,返回的值和字节数组的长度才一致。read方法以字节数组为参数时,返回的整形值到底代表什么意思呢?
...全文
189 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
xiaobineric 2008-04-29
  • 打赏
  • 举报
回复
明白了。
刚才我使用的文本文件是unicode编码,所以返回24。改成ansi编码,返回11。正确了。
a_nuo 2008-04-29
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 a_nuo 的回复:]
public int read(byte[] b)
throws IOException从此输入流中将最多 b.length 个字节的数据读入一个字节数组中。在某些输入可用之前,此方法将阻塞。

覆盖:
类 InputStream 中的 read
参数:
b - 存储读取数据的缓冲区。
返回:
读入缓冲区的字节总数,如果因为已经到达文件末尾而没有更多的数据,则返回 -1。
抛出:
IOException - 如果发生 I/O 错误。
另请参见:
InputStream.read(byte[], int, int)
[/Quote]
a_nuo 2008-04-29
  • 打赏
  • 举报
回复
public int read(byte[] b)
throws IOException从此输入流中将最多 b.length 个字节的数据读入一个字节数组中。在某些输入可用之前,此方法将阻塞。

覆盖:
类 InputStream 中的 read
参数:
b - 存储读取数据的缓冲区。
返回:
读入缓冲区的字节总数,如果因为已经到达文件末尾而没有更多的数据,则返回 -1。
抛出:
IOException - 如果发生 I/O 错误。
另请参见:
InputStream.read(byte[], int, int)

62,623

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧