如何从 java 中的文件中读取特定字符到特定字符?

How to read certain char to certain char from file in java?

我有一个文本文件,其中包含如下位置:

#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();
    }

我想将坐标存储在一个二维数组中,但是我遇到了另一个问题。如何存储 etc -1、-1?

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();
}

Java 中的数组索引始终从 0 开始。但如果您知道 x 和 y 值的总范围(X_MIN <= x < [=17=,这并不是真正的问题] 和 Y_MIN <= y < 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];
}

更好的解决方案是将数组包装到 class 中,提供范围检查并可能使用不同的容器,例如 ArrayList<ArrayList<int>>

这并不能完全解决您的问题,但这里的一个选择是使用地图来存储每个文本块,其中 坐标是一个键,并且文本一个值。

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");
    }
}

一旦你在内存中有了地图,你可以按原样使用它,或者你可以迭代并以某种方式将它转换为数组。