下面文件流哪里错了

chaoliu1024 2011-11-04 11:00:36
import java.io.*;
class bufferInputStream {

public static void main(String[] args) throws IOException
{
try {
File file=new File("f:/work/file2.txt");
long len=file.length();
System.out.println("changdu" + len);
byte[] bytes = new byte[(int)len];

FileInputStream f=new FileInputStream(file);
BufferedInputStream bs=new BufferedInputStream(f);
while(bs.read()!=-1)
{
bs.read(bytes,0,((int)len));
System.out.println(new String(bytes));
}
bs.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

文件内容是:1234567
打印结果是:
changdu7
234567
第一个字符没有打印
...全文
70 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
jiangzuzu 2011-11-04
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 leehom_zhang 的回复:]

把循环去掉就可以了
因为你在判断while的条件的时候,读了第一个字符,这时候流里边第一个字符已经没了,只剩下“234567”六个字符,所以你读7个的时候,只能读出“234567”,外加一个数组结束符\0,

你把代码改成这样就可以 读出7个数字了:
byte[] bytes = new byte[(int) len];

Fil……
[/Quote]
+1
歆鸿 2011-11-04
  • 打赏
  • 举报
回复
把循环去掉就可以了
因为你在判断while的条件的时候,读了第一个字符,这时候流里边第一个字符已经没了,只剩下“234567”六个字符,所以你读7个的时候,只能读出“234567”,外加一个数组结束符\0,

你把代码改成这样就可以 读出7个数字了:
byte[] bytes = new byte[(int) len];

FileInputStream f = new FileInputStream(file);
BufferedInputStream bs = new BufferedInputStream(f);

bs.read(bytes, 0, ((int) len));

System.out.println(new String(bytes));
JieTouLangRen 2011-11-04
  • 打赏
  • 举报
回复

class BufferInputStream {

public static void main(String[] args) throws IOException {
try {
File file = new File("F:/work/file2.txt");
long len = file.length();
System.out.println("changdu:" + len);
byte[] bytes = new byte[(int) len];

FileInputStream f = new FileInputStream(file);
BufferedInputStream bs = new BufferedInputStream(f);
while (true) { //楼主的代码此处就读了一次数据
int key = bs.read(bytes, 0, ((int) len));
System.out.println(new String(bytes));
if (key == -1)
break;
}
bs.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
beiouwolf 2011-11-04
  • 打赏
  • 举报
回复
奇怪的写法


File file=new File("f:/work/file2.txt");
byte[] buf = new byte[1024];
int size = 0;

StringBuilder sb = new StringBuilder();

InputStream is = new FileInputStream(file);
while((size = is.read(buf)) != -1)
sb.append(new String(buf,0,size));

is.close();
System.out.println(sb.toString());

62,614

社区成员

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

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