繁体   English   中英

读取存储在数组列表中的文件数据

[英]Read File Data stored in An Arraylist

我有这段代码,它读取板子(第一个项目)的数据(高度,宽度,行,列),并读取放置在板上的块(其余项目):

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中并返回。请帮助

这就是我最后要结束的

首先创建一个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方法以使用代表文件每一行的Row对象的实例填充List并返回此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了解更多详细信息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM