输出22行以前读取 - Java

时间:2013-09-22 22:35:09

标签: java data-structures arraylist

我正在尝试从文件中读取,并且当读取空白行时,它将在空行之前输出22行。例如,如果程序读取所有在第44行的第一个空白行排成一行,那么它将打印第22行。

目前我已经将它工作,以便它将输入读取并存储到arrayList中然后输出它。我想知道最有效的方法是什么?我也试图确保一次存储不超过23行。 arraylist是适合的数据结构吗?

public static void test(BufferedReader r, PrintWriter w) throws IOException {

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

    String line;
    int n = 0;
    while ((line = r.readLine()) != null) {
        s.add(line);
        n++;
    }
    Iterator<String> i = s.iterator();
    while (i.hasNext()) {
        w.println(i.next());
    }
}

感谢任何建议/输入

4 个答案:

答案 0 :(得分:1)

您可以使用尺寸为22的简单String[]并执行插入和“获取”模数22. 您的代码应如下所示:

public static void test(BufferedReader r, PrintWriter w) throws IOException {

    String[] prev22 = new String[22];
    String line;
    int n = 0;
    while ((line = r.readLine()) != null) {
        prev22[n % 22] = line;
        if(line.trim() == null){
            w.println(prev22[n-22 % 22]);
        }
        else{
            w.println(line);
        }
        n++;
    }
}

答案 1 :(得分:1)

ArrayList有点矫枉过正。由于您确切知道可以使用String数组的总行数。

但是,您必须保留有关当前“开始指针”的信息(如果您想保留订单并以有效的循环方式使用它。

示例:使用自定义循环数组

 public class CircularStringArray {

    private int currenInsertIndex = 0;

    private String[] array = new String[22];

    public void addString(String element)
    {
        array[currenInsertIndex++] = element;
        currenInsertIndex = currenInsertIndex % array.length;
    }   

    public String printStrings()
    {
        String result = "";
        for(int i=currenInsertIndex; i<array.length; i++)
        result+=i+")"+array[i]+"\n";

        for(int i=0; i<currenInsertIndex; i++)
        result+=i+")"+array[i]+"\n";

        return result;
    }

    public static void main(String args[])
    {
        CircularStringArray test = new CircularStringArray();
        for (int i=0; i<50; i++)
        test.addString(new String(new char[]{(char)i}));

        System.out.println(test.printStrings());            
    }
}

答案 2 :(得分:0)

ArrayList将存储所有行,直到空白。您可以使用大小为22的队列。队列的 enqueue dequeue 操作需要持续的O(1)时间和内存使用量也将是最小的

答案 3 :(得分:-1)

这应该有效

public static void test(BufferedReader r, PrintWriter w) throws IOException {

   String[] s = new String[22];

   String line;
   int n = 0;
   while ((line = r.readLine()) != null) {
       s[n] = line;
        //This will take n to 0 when n is 21 i.e. last array position
       n = (n+1) % 22;
   }
   int last = n;

   //Will print it in the same order in which those lines were read.
   do{
         w.println(s[n]);
         n = (n+1) % 22;
     } while(n != last);
}