将具有重复模式的文本文件读入列表

时间:2016-11-22 21:06:31

标签: java file format delimiter file-handling

我正在尝试为Java创建一个Tile Map Editor,但我仍然坚持打开文件。打开文件本身并不是很多,但是只要我在文本文件中放入空格,它就会产生运行时错误。每个图块由一个图像(黑色或白色方形atm)以及它是否为实线(1)或不是(0)组成。瓷砖地图目前将以如下格式保存:

1:1 1:1 1:1 1:1 1:1 1:1
1:1 0:0 0:0 0:0 0:0 1:1
1:1 0:0 0:0 0:0 0:0 1:1
1:1 1:1 1:1 1:1 1:1 1:1

例如,这可能是一个简单的房间,黑色的墙壁是坚固的,将阻止播放器。这将是一个6x4瓷砖地图。如何定义格式x:x(此处为空格)?

List<Integer> list = new ArrayList<Integer>();
File file = new File("file.txt");
BufferedReader reader = null;
try 
{
    reader = new BufferedReader(new FileReader(file));
    String text = null;
    while ((text = reader.readLine()) != null) 
    {
    list.add(Integer.parseInt(text));
    }
}
catch (FileNotFoundException e) 
{
    e.printStackTrace();
}
catch (IOException e) 
{
    e.printStackTrace();
}

2 个答案:

答案 0 :(得分:0)

虽然猜测这是你要求的东西,但是这样......

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ReadTextFile {

    public static void main(String[] args) {
        List<Tile> list = new ArrayList<Tile>();
        String path = "C:/whatever/your/path/is/";
        File file = new File(path + "file.txt");
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String text = null;
            while ((text = reader.readLine()) != null) {
                String[] pairs = text.split(" ");
                for(String pair : pairs) {
                    String[] chars = pair.split(":");
                    int id = Integer.parseInt(chars[0]);
                    int type = Integer.parseInt(chars[1]);
                    list.add(new Tile(id, type));
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } 

    }
}

class Tile {
    int id;
    int type;

    Tile(int id, int type) {
        this.id = id;
        this.type = type;
    }

    @Override
    public String toString() {
        return "Tile [id=" + id + ", type=" + type + "]";
    }


}

答案 1 :(得分:0)

如果您只是被空白所困扰,请将代码更改为

 while ((text = reader.readLine()) != null) 
{
    list.add(Integer.parseInt(text.trim()));
}

但我认为这不起作用,因为你无法将整行转换为整数,所以我建议:

 while ((text = reader.readLine()) != null) 
{
    String[] values = text.split(":")
    for(String val : values)
    {
        list.add(Integer.parseInt(val.trim()));
    }
}