用偶数和奇数分隔文件中的行

时间:2013-02-02 04:21:34

标签: java arrays file-io bufferedreader

我有一个设置如下的文件:

10   10
12   32
38   12

我需要将行放在一个数组中的偶数槽中,而将行放在另一个数组中的奇数槽中。我是java新手,我不知道如何做到这一点。我一直在网上搜索几个小时,但没有找到任何东西。请帮我!我真的很感激!

我正在使用Buffered Reader读取文件。我已经编写了一个程序来读取文件并将所有行放在一个数组中,现在我只需要知道如何对它进行编码以分隔行。所以1,3,5,7,9行将在一个数组中,而2,4,6,8行将在另一个数组中。

我将它们放在一个数组中的代码:

 private static final String FILE = "file.txt";
    private static Point[] points;


    public static void main(final String[] args){
        try{
            final BufferedReader br = new BufferedReader(new FileReader(new File(FILE)));
            points = new Point[Integer.parseInt(br.readLine())];
            int i = 0;
            int xMax = 0;
            int yMax = 0;
            while(br.ready()){
                final String[] split = br.readLine().split("\t");
                final int x = Integer.parseInt(split[0]);
                final int y = Integer.parseInt(split[1]);
                xMax = Math.max(x, xMax);
                yMax = Math.max(y, yMax);
                points[i++] = new Point(x, y);




            }

2 个答案:

答案 0 :(得分:3)

    List<String> list1 = new ArrayList<>();
    List<String> list2 = new ArrayList<>();
    String line;
    for (int i = 0; (line = br.readLine()) != null; i++) {
        if (i % 2 == 0) {
            list1.add(line);
        } else {
            list2.add(line);
        }
    }
    String[] even = list1.toArray(new String[list1.size()]);
    String[] odd = list2.toArray(new String[list2.size()]);

答案 1 :(得分:1)

String[] even = new String[100];
String[] odd = new String[100];
int counter = 0;
String text;

while(text=readLine() != null) {
    if(counter%2 == 0) {
         even[counter/2] = text;
    } else {
         odd[(counter-1)/2] = text;
    }

     counter++;
}

您需要根据文件的行数调整数组的大小。

代码做了什么:循环保持读取行。如果计数器是偶数,则计数器%2 == 0为真。如果counter是偶数,counter / 2将是一个没有余数的整数,所以什么都不会丢失。如果counter是奇数,则(counter-1)/ 2也是如此。