Search code examples
javaarraysfilejava.util.scannercoordinate

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


I have a text file, which contains positions like this:

enter image description here

The #p shows the x, y coordinates, so the first * after the #p row is at (6, -1). I would like to read the text file as blocks (one block is from the #p to the next #p row).

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

I want to store the coordinates in a two dimensional array, but there goes my other problem. How can I store etc -1, -1?


Solution

  • This doesn't completely solve your problem, but one option here is to use a map to store each block of text, where a pair of coordinates is a key, and the text a value.

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

    Once you have the map in memory, you can either use it as is, or you could iterate and somehow convert it to an array.