BufferedReader br = new BufferedReader(new FileReader("test.txt"); 我想把test的内容读出来,存到一个string数组里面去,数组一个元素代表一行。 可是,在没全部读完之前,我不知道行数啊,要怎么初始化那个string数组? 

解决方案 »

  1.   

    在没读完之前没办法行数,如果真要这么做的话就放在list里吧!而且list也可以调用toArray方法转换成数组
      

  2.   

    你可以自己在读之前声明一个int rowCount=0;然后每读一行就 rowCount++;
      

  3.   

    嗯,正如一楼所说的,你只能采用 List 再转为 String 数组就行了,
    因为在读之前根本不知道有多少行的,除非读两遍(第一遍数数,第一遍读行)。
      

  4.   


    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;public class Test{
    public static void main(String args[]){
    String[] strings=new String[0]; 
    String line=null;
    try {
    BufferedReader br = new BufferedReader(new FileReader("f:/user.txt"));
    while((line=br.readLine())!=null){
    String[] temp=new String[strings.length+1];
    System.arraycopy(strings, 0, temp, 0, strings.length);
    temp[temp.length-1]=line;
    strings=temp;
    }
    for(String str:strings){
    System.out.println(str);
    }
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }你如果不用List的话,这样做吧!
      

  5.   

    谢谢大家,还是用list吧,问题解决。
      

  6.   

    谢谢大家,还是用list吧,问题解决。
      

  7.   

    实际上List也这么做的,只是它里面用了个cache而已!