Example usage for java.nio.file Files readAllLines

List of usage examples for java.nio.file Files readAllLines

Introduction

In this page you can find the example usage for java.nio.file Files readAllLines.

Prototype

public static List<String> readAllLines(Path path) throws IOException 

Source Link

Document

Read all lines from a file.

Usage

From source file:fr.afcepf.atod.wine.data.parser.XmlParser.java

private static String getResourcePath() {
    try {//from  www . ja  va 2s  .  c om
        URI resourcePathFile = System.class.getResource("/RESOURCE_PATH").toURI();
        String resourcePath = Files.readAllLines(Paths.get(resourcePathFile)).get(0);
        URI rootURI = new File("").toURI();
        URI resourceURI = new File(resourcePath).toURI();
        URI relativeResourceURI = rootURI.relativize(resourceURI);
        return relativeResourceURI.getPath();
    } catch (Exception e) {
        return null;
    }
}

From source file:pr.ui.InputForm.java

private void testDataBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_testDataBtnActionPerformed
    jfc = new JFileChooser(lastUsedDirectory);
    int returnVal = jfc.showOpenDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        testBtn.setEnabled(true);/*w  w w  . j  a  v a 2s.com*/
        File file = jfc.getSelectedFile();
        testDataTF.setText("Loaded");
        lastUsedDirectory = file.getParent();
        try {
            // Read the data
            List<String> lines = Files.readAllLines(Paths.get(file.getAbsolutePath()));

            testData = Utils.getTestDataFromRawDataList(lines);

        } catch (IOException ex) {
            Logger.getLogger(InputForm.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:ca.osmcanada.osvuploadr.JPMain.java

private void Process(String dir, String accessToken) {
    File dir_photos = new File(dir);
    //filter only .jpgs
    FilenameFilter fileNameFilter = new FilenameFilter() {
        public boolean accept(File dir, String name) {
            if (name.lastIndexOf('.') > 0) {
                int lastIndex = name.lastIndexOf('.');
                String str = name.substring(lastIndex);
                if (str.toLowerCase().equals(".jpg")) {
                    return true;
                }/*www .  jav a  2  s.  c  o  m*/
            }
            return false;
        }
    };
    File[] file_list = dir_photos.listFiles(fileNameFilter);
    System.out.println("Pictures found:" + String.valueOf(file_list.length));

    System.out.println("Sorting files");
    //sort by modified time
    Arrays.sort(file_list, new Comparator<File>() {
        public int compare(File f1, File f2) {
            return Long.valueOf(Helper.getFileTime(f1)).compareTo(Helper.getFileTime(f2));
        }
    });
    System.out.println("End sorting");
    File f_sequence = new File(dir + "/sequence_file.txt");
    Boolean need_seq = true;
    long sequence_id = -1;
    System.out.println("Checking " + f_sequence.getPath() + " for sequence_file");
    if (f_sequence.exists()) {
        try {
            System.out.println("Found file, reading sequence id");
            List<String> id = Files.readAllLines(Paths.get(f_sequence.getPath()));
            if (id.size() > 0) {
                sequence_id = Long.parseLong(id.get(0));
                need_seq = false;
            }
        } catch (Exception ex) {
            need_seq = true;
        }
    } else {
        System.out.println("Sequence file not found, will need to request new id");
        need_seq = true;
    }
    //TODO: Load count from file
    System.out.println("Looking for count file");
    int cnt = 0;
    File f_cnt = new File(dir + "/count_file.txt");
    if (f_cnt.exists()) {
        System.out.println("Found count file:" + f_cnt.toString());
        try {
            List<String> id = Files.readAllLines(Paths.get(f_cnt.getPath()));
            if (id.size() > 0) {
                cnt = Integer.parseInt(id.get(0));
            }
        } catch (Exception ex) {
            cnt = 0;
        }
    } else {
        try {
            System.out.println("Creating new count file:" + f_cnt.getPath());
            f_cnt.createNewFile();
        } catch (Exception ex) {
            Logger.getLogger(JPMain.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    System.out.println("Current count at:" + String.valueOf(cnt));
    if (cnt > 0) {
        if (file_list.length > cnt) {
            File[] tmp = new File[file_list.length - cnt];
            int local_cnt = 0;
            for (int i = cnt; i < file_list.length; i++) {
                tmp[local_cnt] = file_list[i];
                local_cnt++;
            }
            file_list = tmp;
        }
    }

    System.out.println("Processing photos...");
    //Read file info
    for (File f : file_list) {
        try {
            System.out.println("Processing:" + f.getPath());
            ImageProperties imp = Helper.getImageProperties(f);
            System.out.println("Image Properties:");
            System.out.println("Lat:" + String.valueOf(imp.getLatitude()) + " Long:"
                    + String.valueOf(imp.getLongitude()) + "Created:" + String.valueOf(Helper.getFileTime(f)));
            //TODO: Check that file has GPS coordinates
            //TODO: Remove invalid photos
            if (need_seq) {
                System.out.println("Requesting sequence ID");
                sequence_id = getSequence(imp, accessToken);
                System.out.println("Obtained:" + sequence_id);
                byte[] bytes = Long.toString(sequence_id).getBytes(StandardCharsets.UTF_8);
                Files.write(Paths.get(f_sequence.getPath()), bytes, StandardOpenOption.CREATE);
                need_seq = false;
            }
            imp.setSequenceNumber(cnt);
            cnt++; //TODO: Write count to file
            System.out.println("Uploading image:" + f.getPath());
            Upload_Image(imp, accessToken, sequence_id);
            System.out.println("Uploaded");
            String out = String.valueOf(cnt);
            Files.write(Paths.get(f_cnt.getPath()), out.getBytes("UTF-8"),
                    StandardOpenOption.TRUNCATE_EXISTING);

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR);
        }

    }
    System.out.println("Sending finish for sequence:" + sequence_id);
    SendFinished(sequence_id, accessToken);
}

From source file:es.upm.dit.xsdinferencer.XSDInferencer.java

/**
 * Method that, given an args array, does the whole inference process by calling the appropriate submodules.
 * @param args the args array, as provided by {@link XSDInferencer#main(String[])}
 * @return a {@link Results} object with the inference results (both statistics and XSDs)
 * @throws XSDConfigurationException if there is a problem with the configuration
 * @throws IOException if there is an I/O problem while reading the input XML files or writing the output files
 * @throws JDOMException if there is any problem while parsing the input XML files 
 *//*w  w  w  .  j a va  2s . c  o  m*/
public Results inferSchema(String[] args) throws XSDInferencerException {
    try {
        XSDInferenceConfiguration configuration = new XSDInferenceConfiguration(args);
        FilenameFilter filenameFilter;
        if (configuration.getWorkingFormat().equals("xml")) {
            filenameFilter = FILE_NAME_FILTER_XML_EXTENSION;
            List<File> xmlFiles = getInstanceFileNames(args, filenameFilter);
            List<Document> xmlDocuments = new ArrayList<>(xmlFiles.size());
            SAXBuilder saxBuilder = new SAXBuilder();
            for (int i = 0; i < xmlFiles.size(); i++) {
                File xmlFile = xmlFiles.get(i);
                System.out.print("Reading input file " + xmlFile.getName() + "...");
                FileInputStream fis = new FileInputStream(xmlFile);
                //BufferedReader reader = new BufferedReader(new InputStreamReader(fis, Charsets.UTF_8));
                Document xmlDocument = saxBuilder.build(fis);
                xmlDocuments.add(xmlDocument);
                System.out.println("OK");
            }
            return inferSchema(xmlDocuments, configuration);
        } else if (configuration.getWorkingFormat().equals("json")) {
            filenameFilter = FILE_NAME_FILTER_JSON_EXTENSION;
            List<File> jsonFiles = getInstanceFileNames(args, filenameFilter);
            List<JSONObject> jsonDocumentWithRootObjects = new ArrayList<>(jsonFiles.size());
            List<JSONArray> jsonDocumentWithRootArrays = new ArrayList<>(jsonFiles.size());
            for (int i = 0; i < jsonFiles.size(); i++) {
                File jsonFile = jsonFiles.get(i);
                String jsonString = Joiner.on(System.lineSeparator())
                        .join(Files.readAllLines(jsonFile.toPath()));
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(jsonString);
                } catch (JSONException e) {
                }

                if (jsonObject != null) {
                    jsonDocumentWithRootObjects.add(jsonObject);
                } else {
                    JSONArray jsonArray = null;
                    try {
                        jsonArray = new JSONArray(jsonString);
                    } catch (JSONException e) {
                    }
                    if (jsonArray != null) {
                        jsonDocumentWithRootArrays.add(jsonArray);
                    } else {
                        throw new JSONException("Invalid JSON Document " + jsonFile);
                    }

                }
            }
            return inferSchema(jsonDocumentWithRootObjects, jsonDocumentWithRootArrays, configuration);
        } else {
            throw new InvalidXSDConfigurationParameterException(
                    "Unknown working format. Impossible to load files");
        }
    } catch (IOException | JDOMException | RuntimeException e) {
        throw new XSDInferencerException(e);
    }

}

From source file:pr.ui.InputForm.java

private void textDataBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textDataBtnActionPerformed
    jfc = new JFileChooser(lastUsedDirectory);
    int returnVal = jfc.showOpenDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        trainBtn.setEnabled(true);/*from   w  w w .  j ava2 s.  com*/
        File file = jfc.getSelectedFile();
        trainDataTF.setText(file.getName());
        lastUsedDirectory = file.getParent();
        try {
            // Read the data
            List<String> lines = Files.readAllLines(Paths.get(file.getAbsolutePath()));

            // Obtain the classes and data from the raw data
            classes = new ArrayList();
            data = new ArrayList();
            Utils.getTrainingListsFromRawDataList(lines, data, classes);

        } catch (IOException ex) {
            Logger.getLogger(InputForm.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:com.facebook.buck.io.filesystem.impl.DefaultProjectFilesystemTest.java

@Test
public void moveChildrenMergesOneDirectoryIntoAnother() throws IOException {
    Path srcDir = tmp.newFolder("dir1");
    Files.write(tmp.newFile("dir1/file1"), "new file 1".getBytes(Charsets.UTF_8));

    tmp.newFolder("dir1/subdir1");
    Files.write(tmp.newFile("dir1/subdir1/file2"), "new file 2".getBytes(Charsets.UTF_8));

    tmp.newFolder("dir1/subdir1/subdir2");
    Files.write(tmp.newFile("dir1/subdir1/subdir2/file3"), "new file 3".getBytes(Charsets.UTF_8));

    tmp.newFolder("dir1/subdir1/subdir2/subdir3");

    tmp.newFolder("dir2");
    Path destRoot = tmp.newFolder("dir2/dir3");
    Files.write(tmp.newFile("dir2/dir3/file1"), "old file 1".getBytes(Charsets.UTF_8));
    Files.write(tmp.newFile("dir2/dir3/file1_1"), "old file 1_1".getBytes(Charsets.UTF_8));

    tmp.newFolder("dir2/dir3/dir4");
    tmp.newFolder("dir2/dir3/subdir1");

    filesystem.mergeChildren(Paths.get("dir1"), Paths.get("dir2/dir3"), StandardCopyOption.REPLACE_EXISTING);

    assertTrue(Files.isDirectory(srcDir));
    assertEquals("new file 1", Files.readAllLines(destRoot.resolve("file1")).get(0));
    assertEquals("old file 1_1", Files.readAllLines(destRoot.resolve("file1_1")).get(0));

    assertTrue(Files.isDirectory(destRoot.resolve("dir4")));
    assertTrue(Files.isDirectory(destRoot.resolve("subdir1")));
    assertEquals("new file 2", Files.readAllLines(destRoot.resolve("subdir1").resolve("file2")).get(0));

    assertTrue(Files.isDirectory(destRoot.resolve("subdir1").resolve("subdir2")));
    assertEquals("new file 3",
            Files.readAllLines(destRoot.resolve("subdir1").resolve("subdir2").resolve("file3")).get(0));

    assertTrue(Files.isDirectory(destRoot.resolve("subdir1").resolve("subdir2").resolve("subdir3")));

    assertFalse(Files.exists(srcDir.resolve("subdir1")));
    assertFalse(Files.exists(srcDir.resolve("file1")));
}

From source file:de.ist.clonto.Ontogui.java

private void runQueryButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_runQueryButtonActionPerformed
    List<String> lines = null;
    try {//from  w ww . j  a v  a 2s .  com
        lines = Files.readAllLines(queryPath);
    } catch (IOException ex) {
        Logger.getLogger(Ontogui.class.getName()).log(Level.SEVERE, null, ex);
    }
    String queryString = "";
    for (String line : lines) {
        queryString += line + System.lineSeparator();
    }
    Query query = QueryFactory.create(queryString, Syntax.syntaxARQ);
    queryResultArea.setText("Starting query: " + queryPath.toFile().getName() + "\n");
    Thread t = new Thread(
            new QueryProcessor(query, new QueryAreaStream(queryResultArea), dataset, checkbox1.getState()));
    t.start();
}

From source file:de.ist.clonto.Ontogui.java

private void runSmellAnalysisButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_runSmellAnalysisButtonActionPerformed
    String filename = smellName;/*from  www. j  av a  2  s . co  m*/
    File smellFile = new File(
            System.getProperty("user.dir") + "/sparql/smells/" + filename.replaceAll(" ", "") + ".sparql");

    List<String> lines = null;

    try {
        lines = Files.readAllLines(smellFile.toPath());
    } catch (IOException ex) {
        Logger.getLogger(Ontogui.class.getName()).log(Level.SEVERE, null, ex);
    }
    String queryString = "";
    for (String line : lines) {
        queryString += line + System.lineSeparator();
    }
    Query query = QueryFactory.create(queryString, Syntax.syntaxARQ);
    queryResultArea.setText("Starting analysis: " + smellName + "\n");
    Thread t = new Thread(
            new QueryProcessor(query, new QueryAreaStream(queryResultArea), dataset, checkbox1.getState()));
    t.start();
}

From source file:de.ist.clonto.Ontogui.java

private void displayTransformationInfo(boolean isPruning) {// GEN-FIRST:event_displayPruningButtonActionPerformed
    String filename = "";
    String path;/* w w w  . ja v  a 2 s .  c om*/
    if (isPruning) {
        filename = pruneName.replace(" ", "");
        path = "/sparql/transfdescr/prunings/";
    } else {
        filename = refactorName.replace(" ", "");
        path = "/sparql/transfdescr/refactorings/";
    }

    File textFile = new File(System.getProperty("user.dir") + path + filename + "C.txt");

    List<String> lines = null;

    try {
        if (textFile.exists())
            lines = Files.readAllLines(textFile.toPath());
        else
            throw new Exception();
        contextArea.setText("Context:");
        for (String line : lines)
            contextArea.append("\n" + line);
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(this, "Reading context file for " + filename + " failed!");
    }

    textFile = new File(System.getProperty("user.dir") + "/sparql/transfdescr/prunings/" + filename + "T.txt");

    lines = null;

    try {
        if (textFile.exists())
            lines = Files.readAllLines(textFile.toPath());
        else
            throw new Exception();
        descriptionArea.setText("Transformations:");
        for (String line : lines)
            descriptionArea.append("\n" + line);
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(this, "Reading transformation file for " + filename + " failed!");
    }

}

From source file:de.ist.clonto.Ontogui.java

private void runMetricsButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_runMetricsButtonActionPerformed
    String folder = metricName.split(":")[0].toLowerCase();
    String filename = metricName.split(":")[1];
    File metricFile = new File(
            System.getProperty("user.dir") + "/sparql/metrics/" + folder + "/" + filename + ".sparql");

    List<String> lines = null;

    try {// ww  w.  j  a va  2 s .  c o  m
        lines = Files.readAllLines(metricFile.toPath());
    } catch (IOException ex) {
        Logger.getLogger(Ontogui.class.getName()).log(Level.SEVERE, null, ex);
    }
    String queryString = "";
    for (String line : lines) {
        queryString += line + System.lineSeparator();
    }
    Query query = QueryFactory.create(queryString, Syntax.syntaxARQ);
    queryResultArea.setText("Starting analysis:" + metricName + "\n");
    System.err.println(checkbox1.isEnabled());
    Thread t = new Thread(
            new QueryProcessor(query, new QueryAreaStream(queryResultArea), dataset, checkbox1.getState()));
    t.start();
}