我有一个对象,我可以使用两个构造函数
创建它public Brick(int x, int y){
..........
}
和
public Brick(int x, int y, float sizeX, float sizeY){
}
在我的map.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())));
}
所以我需要阅读我的文件,我的两个构造函数都可以工作吗?
答案 0 :(得分:1)
如果每一行都有一个命令,那么我会逐行读取它:
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);
};
}
}
}
}
}