只在char数组中放入一定数量的行

时间:2015-04-29 10:25:16

标签: java arrays file-io char

我有一个2939行的文件,我试图将这五行保存在一个2D char数组的索引中。 所以,

 char [][] myArray;
 myArray[0] = {} //<--char array of first five lines
 myArray[1]= //char array of next five lines

我实现这个的方式是:

int countLines=0; 
while (sc.hasNext() countLines <5) { //sc is scanner
   //read each line and append to a string builder
   //then convert stringbuilder to char array and
   //store in myArray[0]

   countLines++;
 }

我被困在myArray [1]中存储接下来的五行。任何帮助,将不胜感激。谢谢!

3 个答案:

答案 0 :(得分:0)

首选使用列表而不是数组:

    List<String> myArray = new ArrayList<String>();
    while (sc.hasNext()) {
       myArray.add(sc.nextLine());
    }
    // your 5 first line:
    // your 5 first line array:
    List<String> fiveLines = myArray.subList(0, 5);

答案 1 :(得分:0)

使用数组列表,因为你不知道数组的大小

 ArrayList<String> strs = new ArrayList<String>();

现在添加为

 strs.add("your string");

获取大小

strs.size();

答案 2 :(得分:0)

你可以试试这个

while(sc.hasNext()) {
    if(countLines < 5) {
        //store in myArray[0]
    } else if(countLines >= 5 && countLines < 10) {
        //store in myArray[1]
    }
    countLines++;
 }