Java read file and store text in an array

前端 未结 7 1855
心在旅途
心在旅途 2020-11-30 06:25

I know how to read a file with Java using Scanner and File IOException, but the only thing I don\'t know is how to store the text in the files as a

7条回答
  •  -上瘾入骨i
    2020-11-30 06:55

    If you don't know the number of lines in your file, you don't have a size with which to init an array. In this case, it makes more sense to use a List :

    List tokens = new ArrayList();
    while (inFile1.hasNext()) {
        tokens.add(inFile1.nextLine());
    }
    

    After that, if you need to, you can copy to an array :

    String[] tokenArray = tokens.toArray(new String[0]);
    

提交回复
热议问题