创建对象并从文件读取



我有一个对象,我可以用两个构造函数创建它

public Brick(int x, int y){
    ..........
}

public Brick(int x, int y, float sizeX, float sizeY){
}

在我的地图中.txt我有这个

Brick 320 0
Brick 640 64 64 128
Spike 5 12
Spike 75 25
...
...
...

这是我如何阅读该文件的

        FileHandle file = Gdx.files.internal("data/map.txt");
        StringTokenizer tokens = new StringTokenizer(file.readString());
        while(tokens.hasMoreTokens()){
            String type = tokens.nextToken();
            if(type.equals("Block")){
                list.add(new Brick(Integer.parseInt(tokens.nextToken()), Integer.parseInt(tokens.nextToken()), Float.parseFloat(tokens.nextToken()), Float.parseFloat(tokens.nextToken())));
            }

所以我需要读取我的文件,我的两个构造函数都可以工作?

如果每行都有一个命令,那么我会像这样逐行阅读它:

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.StringTokenizer;
public class readFile {
    public static class Brick{
        public Brick(int a,int b){System.out.println("constructor for 2 params: "+a+", "+b);}
        public Brick(int a,int b,int c,int d){System.out.println("constructor for 4 params: "+a+", "+b+", "+c+", "+d);}
    }
    public static void main(String[] args) throws Exception {
        String line;
        InputStream fis = new FileInputStream("map.txt");
        InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8"));
        BufferedReader br = new BufferedReader(isr);
        while ((line = br.readLine()) != null) {
            //System.out.println(line);
            StringTokenizer tokens = new StringTokenizer(line.trim());
            while(tokens.hasMoreTokens()){
                String type = tokens.nextToken();
                if(type.equals("Brick")){
                    int params = tokens.countTokens();
                    switch(params){
                        case 2: new Brick(Integer.parseInt(tokens.nextToken()),
                                          Integer.parseInt(tokens.nextToken()));
                            break;
                        case 4: new Brick(Integer.parseInt(tokens.nextToken()),
                                          Integer.parseInt(tokens.nextToken()),
                                          Integer.parseInt(tokens.nextToken()),
                                          Integer.parseInt(tokens.nextToken()));
                            break;
                        default: throw new Exception("Wrong line:"+line);
                    };
                }
            }
        }
    }
}

相关内容

  • 没有找到相关文章

最新更新