我有一个文本文件,其中包含以下位置:
#p显示x,y坐标,因此#p行之后的第一个*位于(6,-1)。我想把文本文件读成块(一个块是从#p到下一个#p行)。
try {
File file = new File("filename.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append("\n");
if (line.startsWith("#P")){
Scanner s = new Scanner(line).useDelimiter(" ");
List<String> myList = new ArrayList<String>();
while (s.hasNext()) {
myList.add(s.next());
}
for (int i=0; i<myList.size(); i++){
System.out.println(myList.get(i));
}
System.out.println("xy: "+myList.get(1)+", "+myList.get(2));
}
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
我想将坐标存储在二维数组中,但是我的另一个问题就出现了。我怎样才能存储等-1,-1?
答案 0 :(得分:0)
byte[][] coords = new byte[X_MAX - X_MIN + 1][Y_MAX - Y_MIN + 1]; //your array with 0 and 1 as you wished
try {
File file = new File("filename.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
//StringBuffer stringBuffer = new StringBuffer(); //i don't c why you need it here
String line;
while ((line = bufferedReader.readLine()) != null) {
//stringBuffer.append(line);
//stringBuffer.append("\n");
if (line.startsWith("#P")){
String[] parts = line.split(" ");
int x = Integer.parseInt(parts[1]);
int y = Integer.parseInt(parts[2]);
coords[x - X_MIN][y - Y_MIN] = 1;
}
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
答案 1 :(得分:0)
Java中的数组索引始终从0开始。但是,如果您知道x和y值的总范围(X_MIN&lt; = x&lt; X_MAX和Y_MIN&lt; = y&lt; Y_MAX),那么这不是真正的问题:
coor[X_MAX - X_MIN + 1][Y_MAX - Y_MIN + 1];
...
void setValue( int x, int y, int value ) {
coor[x - X_MIN][y - Y_MIN] = value;
}
int getValue( int x, int y ) {
return coor[x + X_MIN][y + Y_MIN];
}
一个更好的解决方案是将数组包装到一个类中,提供范围检查,并可能使用不同的容器,如ArrayList<ArrayList<int>>
。
答案 2 :(得分:0)
这并不能完全解决您的问题,但这里的一个选项是使用地图存储每个文本块,其中对坐标是键,文本是值。
Map<String, String> contentMap = new HashMap<>();
String currKey = null;
StringBuffer buffer = new StringBuffer();
while ((line = bufferedReader.readLine()) != null) {
if (line.startsWith("#P")) {
// store previous paragraph in the map
if (currKey != null) {
contentMap.put(currKey, buffer.toString());
buffer = new StringBuffer();
}
currKey = line.substring(3);
}
else {
buffer.append(line).append("\n");
}
}
在内存中存储地图后,您可以按原样使用它,也可以迭代并以某种方式将其转换为数组。