当前位置: 代码迷 >> J2SE >> 下面文件流错哪了
  详细解决方案

下面文件流错哪了

热度:304   发布时间:2016-04-24 02:24:51.0
下面文件流哪里错了
Java code
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
第一个字符没有打印

------解决方案--------------------
奇怪的写法

Java code
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());
------解决方案--------------------
Java code
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();        }    }}
------解决方案--------------------
把循环去掉就可以了
因为你在判断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));
  相关解决方案