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, Charset cs) throws IOException 

Source Link

Document

Read all lines from a file.

Usage

From source file:org.onehippo.cms7.essentials.dashboard.utils.GlobalUtils.java

/**
 * Read text file content (UTF-8)/* ww w. ja v  a  2 s  .co m*/
 *
 * @param path path to read from
 * @return StringBuilder instance containing file content.
 */
public static StringBuilder readTextFile(final Path path) {
    final StringBuilder builder = new StringBuilder();
    try {
        final List<String> strings = Files.readAllLines(path, Charsets.UTF_8);
        for (String string : strings) {
            builder.append(string).append(System.getProperty("line.separator"));
        }
    } catch (IOException e) {
        log.error("Error reading source file", e);
    }
    return builder;
}

From source file:com.khepry.utilities.GenericUtilities.java

public static void displayLogFile(String logFilePath, long logSleepMillis, String xsltFilePath,
        String xsldFilePath) {/*from w w  w  .  j  a v a2s.c  o  m*/
    Logger.getLogger("").getHandlers()[0].close();
    // only display the log file
    // if the logSleepMillis property
    // is greater than zero milliseconds
    if (logSleepMillis > 0) {
        try {
            Thread.sleep(logSleepMillis);
            File logFile = new File(logFilePath);
            File xsltFile = new File(xsltFilePath);
            File xsldFile = new File(xsldFilePath);
            File tmpFile = File.createTempFile("tmpLogFile", ".xhtml", logFile.getParentFile());
            if (logFile.exists()) {
                if (xsltFile.exists() && xsldFile.exists()) {
                    String xslFilePath;
                    String xslFileName;
                    String dtdFilePath;
                    String dtdFileName;
                    try {
                        xslFileName = new File(logFilePath).getName().replace(".xhtml", ".xsl");
                        xslFilePath = logFile.getParentFile().toString().concat("/").concat(xslFileName);
                        FileUtils.copyFile(new File(xsltFilePath), new File(xslFilePath));
                        dtdFileName = new File(logFilePath).getName().replace(".xhtml", ".dtd");
                        dtdFilePath = logFile.getParentFile().toString().concat("/").concat(dtdFileName);
                        FileUtils.copyFile(new File(xsldFilePath), new File(dtdFilePath));
                    } catch (IOException ex) {
                        String message = Level.SEVERE.toString().concat(": ").concat(ex.getLocalizedMessage());
                        Logger.getLogger(GenericUtilities.class.getName()).log(Level.SEVERE, message, ex);
                        GenericUtilities.outputToSystemErr(message, logSleepMillis > 0);
                        return;
                    }
                    BufferedWriter bw = Files.newBufferedWriter(Paths.get(tmpFile.getAbsolutePath()),
                            Charset.defaultCharset(), StandardOpenOption.CREATE);
                    List<String> logLines = Files.readAllLines(Paths.get(logFilePath),
                            Charset.defaultCharset());
                    for (String line : logLines) {
                        if (line.startsWith("<!DOCTYPE log SYSTEM \"logger.dtd\">")) {
                            bw.write("<!DOCTYPE log SYSTEM \"" + dtdFileName + "\">\n");
                            bw.write("<?xml-stylesheet type=\"text/xsl\" href=\"" + xslFileName + "\"?>\n");
                        } else {
                            bw.write(line.concat("\n"));
                        }
                    }
                    bw.write("</log>\n");
                    bw.close();
                }
                // the following statement is commented out because it's not quite ready for prime-time yet
                // Files.write(Paths.get(logFilePath), transformLogViaXSLT(logFilePath, xsltFilePath).getBytes(), StandardOpenOption.CREATE);
                Desktop.getDesktop().open(tmpFile);
            } else {
                Logger.getLogger(GenericUtilities.class.getName()).log(Level.SEVERE, logFilePath,
                        new FileNotFoundException());
            }
        } catch (InterruptedException | IOException ex) {
            Logger.getLogger(GenericUtilities.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:org.cyclop.test.EmbeddedCassandra.java

private void executeScript(Session session, String scriptName) throws Exception {
    URL scriptURL = getClass().getResource(scriptName);
    assertNotNull(scriptName, scriptURL);
    Path scriptPath = Paths.get(scriptURL.toURI());
    List<String> lines = Files.readAllLines(scriptPath, Charset.forName("UTF-8"));
    for (String line : lines) {
        line = line.replaceAll("\\p{Cc}", "");
        line = StringUtils.trimToNull(line);
        if (line == null) {
            continue;
        }/* w  w  w .j  ava2s.  co  m*/
        try {
            session.execute(line);
        } catch (Exception e) {
            throw new Exception("Error executing:" + line + " - got: " + e.getMessage(), e);
        }
    }
}

From source file:nl.vumc.biomedbridges.galaxy.metadata.parsers.GalaxyWorkflowMetadataParser.java

/**
 * Parse the workflow definition (.ga) file. The file is in json format.
 *
 * @param filePath the file path to the workflow definition (.ga) file.
 * @return the workflow metadata object.
 *//*from   ww  w.jav  a 2 s.  com*/
private GalaxyWorkflowMetadata parseWorkflowDefinition(final String filePath) {
    GalaxyWorkflowMetadata result;
    try {
        final String jsonContent = Joiner.on("\n")
                .join(Files.readAllLines(Paths.get(filePath), Charsets.UTF_8));
        final JSONObject workflowJson = (JSONObject) new JSONParser().parse(jsonContent);
        logger.trace("workflowJson: " + workflowJson);
        logger.trace("");
        result = new GalaxyWorkflowMetadata(workflowJson);
        logger.trace("");
    } catch (final IOException | ParseException e) {
        result = null;
        e.printStackTrace();
    }
    return result;
}

From source file:org.openbaton.vnfm.utils.Utils.java

public static String getUserdataFromFS() {
    File folder = new File("/etc/openbaton/scripts/ms-vnfm");
    List<String> lines = new ArrayList<String>();
    if (folder.exists() && folder.isDirectory()) {
        for (File file : folder.listFiles()) {
            if (file.getAbsolutePath().endsWith(".sh")) {
                try {
                    lines.addAll(Files.readAllLines(Paths.get(file.getAbsolutePath()), StandardCharsets.UTF_8));
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }/*ww  w  . j a  v a  2s .c om*/
            }
            lines.add("\n");
        }
    }
    //Create the script
    StringBuilder script = new StringBuilder();
    for (String line : lines) {
        script.append(line).append("\n");
    }
    return script.toString();
}

From source file:org.diorite.impl.plugin.PluginManagerImpl.java

public PluginManagerImpl(final File directory) {
    this.directory = directory;
    final File cache = new File("pluginsCache.txt");
    try {//from   w  w  w .  jav  a 2s.  com
        if (cache.exists()) {
            try {
                Files.readAllLines(cache.toPath(), StandardCharsets.UTF_8).forEach(s -> {
                    try {
                        final String[] parts = CACHE_PATTERN.split(s, 2);
                        if ((parts != null) && (parts.length == 2)) {
                            mainClassCache.put(parts[1], parts[0]);
                        }
                    } catch (final Exception e) {
                        if (CoreMain.isEnabledDebug()) {
                            e.printStackTrace();
                        }
                    }
                });
            } catch (final IOException e) {
                e.printStackTrace();
            }
        } else {
            try {
                cache.createNewFile();
            } catch (final IOException e) {
                e.printStackTrace();
            }
        }
    } catch (final Exception t) {
        System.err.println("Error when loading plugin main classes cache: " + t.getClass().getName() + ", "
                + t.getMessage());
        if (CoreMain.isEnabledDebug()) {
            t.printStackTrace();
        }
        try {
            cache.delete();
        } catch (final Exception e) {
            if (CoreMain.isEnabledDebug()) {
                e.printStackTrace();
            }
        }
    }
}

From source file:stroom.headless.TestHeadless.java

@Ignore
public void test() throws Exception {
    String newTempDir = null;/*ww w .  ja  va 2s. c  o m*/

    try {
        // Let tests update the database
        //            StroomProperties.setOverrideProperty("stroom.jpaHbm2DdlAuto", "update", "test");
        //            StroomProperties.setOverrideProperty("stroom.connectionTesterClassName",
        //                    "stroom.entity.server.util.StroomConnectionTesterOkOnException", "test");

        newTempDir = FileUtil.getTempDir().getCanonicalPath() + File.separator + "headless";
        StroomProperties.setOverrideProperty("stroom.temp", newTempDir, StroomProperties.Source.TEST);

        // Make sure the new temp directory is empty.
        final File tmpDir = new File(newTempDir);
        if (tmpDir.isDirectory()) {
            FileUtils.deleteDirectory(tmpDir);
        }

        final String dir = StroomProcessTestFileUtil.getTestResourcesDir().getCanonicalPath() + File.separator
                + "TestHeadless";

        final String inputDirPath = dir + File.separator + "input";
        final String outputDirPath = dir + File.separator + "output";
        new File(inputDirPath).mkdir();
        new File(outputDirPath).mkdir();

        final String configFilePath = dir + File.separator + "config.zip";
        final String configUnzippedDirPath = dir + File.separator + "configUnzipped";
        final String inputFilePath = inputDirPath + File.separator + "001.zip";
        final String inputUnzippedDirPath = dir + File.separator + "inputUnzipped";
        final String outputFilePath = outputDirPath + File.separator + "output";
        final String expectedOutputFilePath = dir + File.separator + "expectedOutput";

        // Clear out any files from previous runs
        Files.deleteIfExists(new File(inputFilePath).toPath());
        Files.deleteIfExists(new File(configFilePath).toPath());

        // build the input zip file from the source files
        // the zip files created are transient and are ignored by git. They
        // are left in place to make it
        // easier to see the actual file when debugging the test
        final File inputZipFile = new File(inputFilePath);
        ZipUtil.zip(inputZipFile, new File(inputUnzippedDirPath));

        // build the config zip file from the source files
        // the zip files created are transient and are ignored by git. They
        // are left in place to make it
        // easier to see the actual file when debugging the test
        final File configZipFile = new File(configFilePath);
        ZipUtil.zip(configZipFile, new File(configUnzippedDirPath));

        final Headless headless = new Headless();

        headless.setConfig(configFilePath);
        headless.setInput(inputDirPath);
        headless.setOutput(outputFilePath);
        headless.setTmp(newTempDir);
        headless.run();

        final List<String> expectedLines = Files.readAllLines(new File(expectedOutputFilePath).toPath(),
                Charset.defaultCharset());
        final List<String> outputLines = Files.readAllLines(new File(outputFilePath).toPath(),
                Charset.defaultCharset());

        // same number of lines output as expected
        Assert.assertEquals(expectedLines.size(), outputLines.size());

        // make sure all lines are present in both
        Assert.assertEquals(new HashSet<String>(expectedLines), new HashSet<String>(outputLines));

        // content should exactly match expected file
        ComparisonHelper.compareFiles(new File(expectedOutputFilePath), new File(outputFilePath));

    } finally {
        StroomProperties.removeOverrides();
    }
}

From source file:com.spotify.docker.client.CompressedDirectory.java

static ImmutableSet<PathMatcher> parseDockerIgnore(Path dockerIgnorePath) throws IOException {
    final ImmutableSet.Builder<PathMatcher> matchersBuilder = ImmutableSet.builder();

    if (Files.isReadable(dockerIgnorePath) && Files.isRegularFile(dockerIgnorePath)) {
        for (final String line : Files.readAllLines(dockerIgnorePath, StandardCharsets.UTF_8)) {
            final String pattern = line.trim();
            if (pattern.isEmpty()) {
                log.debug("Will skip '{}' - cause it's empty after trimming", line);
                continue;
            }//from   ww  w.  j av  a  2s.  com
            matchersBuilder.add(goPathMatcher(dockerIgnorePath.getFileSystem(), pattern));
        }
    }

    return matchersBuilder.build();
}

From source file:com.github.wellcomer.query3.core.Autocomplete.java

/**
    ?.   ?,  TreeSet ?  ? ?. ? TreeSet   .
        //from w  w w  . j  a v a  2 s .  c o  m
    @param queryList ?? ?.
    @param scanModifiedOnly ?   ?.
    @param mergePrevious ?? ?  ??  .
*/
public void autolearn(QueryList queryList, boolean scanModifiedOnly, boolean mergePrevious) throws IOException {

    FileTime timestamp;
    long modifiedSince = 0;
    Path timestampFilePath = Paths.get(filePath, ".timestamp");

    if (scanModifiedOnly) { //   
        try { //  ?   ? ?
            timestamp = Files.getLastModifiedTime(timestampFilePath);
            modifiedSince = timestamp.toMillis();
        } catch (IOException e) { //    ?    ? 
            Files.createFile(timestampFilePath);
        }
    }

    HashMap<String, TreeSet<String>> fields = new HashMap<>(); //  - ? ?,  -  ? 
    Iterator<Query> queryIterator = queryList.iterator(modifiedSince); // ? ?? ? ?  ?

    String k, v;

    while (queryIterator.hasNext()) {

        Query query = queryIterator.next();

        for (Map.Entry<String, String> entry : query.entrySet()) {

            k = entry.getKey().toLowerCase();
            v = entry.getValue().trim();

            if (v.length() < 2)
                continue;

            if (!fields.containsKey(k)) {

                TreeSet<String> treeSet = new TreeSet<>();

                try {
                    if (mergePrevious) { // ? ?  
                        List<String> lines = Files.readAllLines(Paths.get(filePath, k), charset);
                        treeSet.addAll(lines);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

                fields.put(k, treeSet);
            }
            TreeSet<String> treeSet = fields.get(k);
            treeSet.add(v);
        }
    }

    for (Map.Entry<String, TreeSet<String>> entry : fields.entrySet()) {

        k = entry.getKey();
        ArrayList<String> lines = new ArrayList<>(fields.get(k));

        FileWriter fileWriter = new FileWriter(Paths.get(filePath, k).toString());
        fileWriter.write(StringUtils.join(lines, System.getProperty("line.separator")));
        fileWriter.flush();
        fileWriter.close();
    }

    try {
        Files.setLastModifiedTime(timestampFilePath, FileTime.fromMillis(System.currentTimeMillis()));
    } catch (IOException e) {
        if (e.getClass().getSimpleName().equals("NoSuchFileException"))
            Files.createFile(timestampFilePath);
        e.printStackTrace();
    }
}

From source file:de.fatalix.book.importer.CalibriImporter.java

private static BookEntry parseOPF(Path pathToOPF, BookEntry bmd) throws IOException {
    List<String> lines = Files.readAllLines(pathToOPF, Charset.forName("UTF-8"));
    boolean multiLineDescription = false;
    String description = "";
    for (String line : lines) {
        if (multiLineDescription) {
            multiLineDescription = false;
            if (line.split("<").length == 1) {
                multiLineDescription = true;
                description = description + line;
            } else {
                description = description + line.split("<")[0];
                description = StringEscapeUtils.unescapeXml(description);
                bmd.setDescription(description);
            }//from   ww  w .  j  a v a 2 s .c om
        } else {
            if (line.contains("dc:title")) {
                String title = line.split(">")[1].split("<")[0];
                bmd.setTitle(title);
            } else if (line.contains("dc:creator")) {
                String creator = line.split(">")[1].split("<")[0];
                bmd.setAuthor(creator);
            } else if (line.contains("dc:description")) {
                String value = line.split(">")[1];
                if (value.split("<").length == 1) {
                    multiLineDescription = true;
                    description = value;
                } else {
                    value = value.split("<")[0];
                    value = StringEscapeUtils.unescapeXml(value);
                    bmd.setDescription(value);
                }
            } else if (line.contains("dc:publisher")) {
                String value = line.split(">")[1].split("<")[0];
                bmd.setPublisher(value);
            } else if (line.contains("dc:date")) {
                String value = line.split(">")[1].split("<")[0];
                DateTime dtReleaseDate = new DateTime(value);
                if (dtReleaseDate.getYear() != 101) {
                    bmd.setReleaseDate(dtReleaseDate.toDate());
                }
            } else if (line.contains("dc:language")) {
                String value = line.split(">")[1].split("<")[0];
                bmd.setLanguage(value);
            } else if (line.contains("opf:scheme=\"ISBN\"")) {
                String value = line.split(">")[1].split("<")[0];
                bmd.setIsbn(value);

            }
        }
    }
    return bmd;
}