我做了一个读取文本文件的程序,代码如下:
BufferedInputStream bis = null;
try {
bis = new BufferedInputStream(new FileInputStream(file)); byte[] b = new byte[65536];
int len;
while ((len = bis.read(b)) != -1) {
str = new String(b, 0, len, "GBK"); }
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
我定义了byte[65536]的动态数组,现在要读入的文件要大于65536,而且大小不固定,
我该如何分配byte?java不支持动态数组,有其他方法可以实现吗?谢谢

解决方案 »

  1.   

    其实不用的吧。
    你只要把读入的字符串相加就可以了。
    而这个byte数组的长度可以固定,
    你已经用了while循环,当循环结束,所有的内容就都读到了。
      

  2.   

    用缓存读,你这样读要是碰上大文件,即使数组足够大,也要内存溢出。如果确定读的是小文件,只要将数组声明为:byte[] b = new byte[bis.available()];,应该能满足你的需求。另,不知那个str变量做啥用,如果要打印出字符串的话,这样做是不合理的,因为很有中文字符2个字节,如果刚好读到两个字节之间,就会产生乱码。建议使用readline()
      

  3.   

    比如我有个文件,test.txt
    内容为12345678900987654321然后代码这样写:import java.io.BufferedInputStream;
    import java.io.FileInputStream;
    import java.io.IOException;/**
     * @author bzwm
     * 
     */
    public class ReadFile {
    public static void main(String args[]) {
    BufferedInputStream bis = null;
    try {
    bis = new BufferedInputStream(new FileInputStream("test.txt")); byte[] b = new byte[10];
    int len;
    String str = "";
    while ((len = bis.read(b)) != -1) {
    str += new String(b, 0, len, "GBK");
    }
    System.out.println(str);
    } catch (IOException e) {
    e.printStackTrace();
    } finally {
    if (bis != null) {
    try {
    bis.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }
    }
    }
      

  4.   

    欢迎做JAVA的朋友加入JAVA交流群交流:72923840