读取存储在An Arraylist中的文件数据

时间:2015-12-29 22:47:55

标签: java arrays arraylist input output

我有这段代码读取板上的数据(高度,宽度,行,列)和块(其余项目)放在板上:

import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;

public class readFile {
private Scanner scanner;
public void openFile() {

    try {
        scanner = new Scanner(new
File("filePath.txt"));
    }
    catch (Exception e)

    {
        System.out.println("File not found");
    }
 }
public void readTheFile(){
    while (scanner.hasNext()){

        int height = scanner.nextInt();
        int width = scanner.nextInt();
        int row = scanner.nextInt();
        int col = scanner.nextInt();

        System.out.printf("%s %s %s %s\n", height, width,row,col);
    }
}
public void closeFile(){
    scanner.close();
 }
}

这是输出:

5 4 0 0  //the dimensions of a board ; height, width, row, column
2 1 0 0 /*the rest are dimensions-heigh,width,row,column of blocks placed on 
2 2 0 1   the board*/
2 1 0 3 
2 1 2 0  
1 2 2 1 
1 1 3 1 
1 1 3 2 
1 1 4 0 
1 1 4 3

我希望将它存储在Arraylist中并返回。请帮助

This is what i want to end up with finally

1 个答案:

答案 0 :(得分:0)

首先创建一个代表单行数据的POJO(普通旧Java对象)......

public class Row {

    private int height, width, row, col;

    public Row(int height, int width, int row, int col) {
        this.height = height;
        this.width = width;
        this.row = row;
        this.col = col;
    }

    public int getHeight() {
        return height;
    }

    public int getWidth() {
        return width;
    }

    public int getRow() {
        return row;
    }

    public int getCol() {
        return col;
    }

}

修改您的readTheFile方法,以List填充代表文件每一行的Row个对象的实例,并返回此List

public List<Row> readTheFile() {
    List<Row> rows = new ArrayList<>(25);
    while (scanner.hasNext()) {

        int height = scanner.nextInt();
        int width = scanner.nextInt();
        int row = scanner.nextInt();
        int col = scanner.nextInt();

        rows.add(new Row(height, width, row, col));
    }
    return rows;
}

有关详细信息,请查看Collections Trail