Как извлечь 2D Double Array из текстового файла ifs (Java) - PullRequest
0 голосов
/ 31 марта 2020
affine  2
 0.62367 -0.40337   0.40337  0.62367 0.00 0.00 0.75
-0.37633 -0.40337   0.40337 -0.37633 1.00 0.00 0.25
scale 500
height 690
width 410
xOffset 134
yOffset 112
name Golden Dragon

Из этого текстового файла я хочу извлечь массив с именем affine с шириной 2. Следующие значения, разделенные пробелом в следующих 2 строках, являются значениями внутри массива.

I был в состоянии прочитать другие переменные из текстового файла, но не может выяснить, массив.

Вот мой код до сих пор:

 public FileIfs(File path){

         try (BufferedReader ifsReader = new BufferedReader(new FileReader(path))) {
            String line = null;
            int i = 0; int j = 0;

             while((line = ifsReader.readLine()) != null) {
                if (line.startsWith("name")) {
                    name = line.substring(4).trim();
                    System.out.println("Name: " + name);
                 }
                 if (line.startsWith("scale")) {
                    scale = Double.parseDouble(line.substring(5).trim());
                    System.out.println("Scale: " + scale);
                 }
                 if (line.startsWith("height")) {
                    height = Integer.parseInt(line.substring(6).trim());
                    System.out.println("Height: " + height);
                 }
                 if (line.startsWith("width")) {
                    width = Integer.parseInt(line.substring(5).trim());
                    System.out.println("Width: " + width);
                 }
                 if (line.startsWith("xOffset")) {
                    xOffset = Integer.parseInt(line.substring(7).trim());
                    System.out.println("xOffset: " + xOffset);
                 }
                 if (line.startsWith("yOffset")) {
                    yOffset = Integer.parseInt(line.substring(7).trim());
                    System.out.println("yOffset: " + yOffset);
                 }
                 if (line.startsWith("affine")) {
                    int arrLeng = Integer.parseInt(line.substring(6).trim());
                    System.out.println("Array Length: " + arrLeng);

                    affine = new double[arrLeng][7];
                 }
                 else {
                    if (line.startsWith(" ")) {
                        line.trim();
                    } 

                    String currentLine [] = line.split("\\s+");

                    if (!line.trim().isEmpty()){
                        for (String s : currentLine) {
                            if (!s.trim().isEmpty()) {
                                affine[i][j++] = Double.parseDouble(s);
                            }
                        }
                        line = ifsReader.readLine();
                        i++;
                        j = 0;
                    }           

                 } //end of ifelse
             } //loop through every line of file
             ifsReader.close();
         }
         catch (Exception e) {
             System.out.println("could not find file");
         }  //end of try-catch
    }

Код в другом раздел, где я пытаюсь прочитать массив.

Если кто-нибудь может помочь или указать мне правильное направление, это было бы здорово.

Спасибо.

1 Ответ

0 голосов
/ 03 апреля 2020

Возможное решение. Он использует списки для сохранения данных массива. Если вам нужно, легко преобразовать список в реальный массив.

public void fileIfs(Path path) throws IOException {
    try (Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8)) {

        // ------- read parameters -------

        Pattern paramPattern = Pattern.compile("([A-Za-z]+)\\s+([\\w\\s]+)");
        Matcher paramMatcher = paramPattern.matcher(lines.collect(Collectors.joining(",")));
        Map<String, String> params = new HashMap<>();

        while (paramMatcher.find()) {
            params.put(paramMatcher.group(1), paramMatcher.group(2));
        }
        String name = params.get("name");
        int affine = Integer.parseInt(params.get("affine"));
        int scale = Integer.parseInt(params.get("scale"));
        int height = Integer.parseInt(params.get("height"));
        int width = Integer.parseInt(params.get("width"));
        int xOffset = Integer.parseInt(params.get("xOffset"));
        int yOffset = Integer.parseInt(params.get("yOffset"));

        // ------- read array -------

        List<List<Double>> affineList = new ArrayList<>();
        Pattern arrayPattern = Pattern.compile("([\\-\\d]+\\.\\d+)");

        lines.forEach(line -> {
            Matcher arrayMatcher = arrayPattern.matcher(line);
            List<Double> numbers = new ArrayList<>();
            while (arrayMatcher.find()) {
                numbers.add(Double.parseDouble(arrayMatcher.group(1)));
            }
            if (!numbers.isEmpty()) {
                affineList.add(numbers);
            }
        });

        // ---------------

        System.out.println("params: " + params);
        System.out.println("affineList: " + affineList);
    }
}

Вывод:

params: {yOffset=112, xOffset=134, width=410, name=Golden Dragon, scale=500, affine=2, height=690}
affineList: [[0.62367, -0.40337, 0.40337, 0.62367, 0.0, 0.0, 0.75], [-0.37633, -0.40337, 0.40337, -0.37633, 1.0, 0.0, 0.25]]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...