CSV парсер

mail@pastecode.io avatar
unknown
java
2 months ago
2.2 kB
3
Indexable
Never
public CollectionHandler() throws Exception {
        //Loading file and storing information in string
        // Code for loading and parsing the collection from a file

        if(pathToCollection == null){
            System.out.println("There is no environment variable with collection file path");
            return;
        }

        File file = FileHandler.process(pathToCollection);

        if (file != null) {
            FileInputStream fis;
            try {
                 fis = new FileInputStream(pathToCollection);
            } catch (Exception e) {
                System.out.println("Access is denied or file doesn't exist");
                return;
            }
            InputStreamReader isr = new InputStreamReader(fis);
            String csv = "";
            int data = isr.read();

            while (data != -1) {
                csv += (char) data;
                data = isr.read();
            }
            fis.close();
            isr.close();

            var i = 0;

            for (String line: csv.split("(\\r\\n|\\r|\\n)")) {
                if (i == 0) {
                    i++;
                    continue;
                }
                var results = new ArrayList<String>();
                Matcher m = Pattern.compile("(?:^|,)(\\\"(?:[^\\\"]+\\\"\\\"|[^\\\"])*\\\")|([^,\\r\\n]*)").matcher(line);

                while (m.find()) {
                    var s = m.group();
                    if (s.trim() == "") {
                        continue;
                    }
                    if (s.startsWith(",")) {
                        s = s.substring(1);
                    }
                    results.add(s);
                }

                if (results.isEmpty()) {
                    continue;
                }

                try {
                    // TODO put(parsed_key, route)
                    this.collection.put(Integer.parseInt(results.get(0)), new Route(results));
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                    System.out.println("Skipping this Route...");
                }
            }
        }
    }
Leave a Comment