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:rapture.series.file.FileSeriesStore.java

@Override
public SeriesValue getLastPoint(String key) {
    File seriesFile = FileRepoUtils.makeGenericFile(parentDir, key + Parser.COLON_CHAR);
    if (!seriesFile.isFile())
        return null;
    try {//from   w w w .  j  ava2  s. co m
        List<String> lines = Files.readAllLines(seriesFile.toPath(), StandardCharsets.UTF_8);
        if (!lines.isEmpty()) {
            String line = lines.get(lines.size() - 1);
            char c = line.charAt(0);
            int i = line.indexOf(c, 1);
            String column = line.substring(1, i);
            byte[] bytes = line.substring(i + 1).getBytes();
            return SeriesValueCodec.decode(column, bytes);
        }
    } catch (IOException e) {
        log.debug(ExceptionToString.format(e));
    }
    return null;
}

From source file:org.schedulesdirect.grabber.Grabber.java

private void loadRetryIds(Path p) {
    try {/*from   www . ja v a2 s .  com*/
        for (String s : Files.readAllLines(p, ZipEpgClient.ZIP_CHARSET))
            missingSeriesIds.add(s.trim());
    } catch (IOException e) {
        LOG.debug("IOError", e);
    }
}

From source file:org.structr.rest.resource.LogResource.java

private int storeLogEntry(final Path path) throws IOException, FrameworkException {

    final App app = StructrApp.getInstance(securityContext);
    final String fileName = path.getFileName().toString();
    int count = 0;

    if (fileName.length() == 64) {

        final String subjectId = fileName.substring(0, 32);
        final String objectId = fileName.substring(32, 64);

        for (final String line : Files.readAllLines(path, Charset.forName("utf-8"))) {

            final int pos1 = line.indexOf(",", 14);

            final String part0 = line.substring(0, 13);
            final String part1 = line.substring(14, pos1);
            final String part2 = line.substring(pos1 + 1);

            final long timestamp = Long.valueOf(part0);
            final String action = part1;
            final String message = part2;

            final PropertyMap properties = new PropertyMap();

            properties.put(LogEvent.messageProperty, message);
            properties.put(LogEvent.actionProperty, action);
            properties.put(LogEvent.subjectProperty, subjectId);
            properties.put(LogEvent.objectProperty, objectId);
            properties.put(LogEvent.timestampProperty, new Date(timestamp));
            properties.put(LogEvent.visibleToPublicUsers, true);
            properties.put(LogEvent.visibleToAuthenticatedUsers, true);

            app.create(LogEvent.class, properties);

            count++;/*from w  w  w . jav  a 2s  .c o  m*/
        }

    } else {

        System.out.println("Skipping entry " + fileName);
    }

    return count;
}

From source file:org.apache.taverna.robundle.TestBundles.java

@Test
public void setReference() throws Exception {
    try (Bundle bundle = Bundles.createBundle()) {

        Path ref = bundle.getRoot().resolve("ref");
        Bundles.setReference(ref, URI.create("http://example.org/test"));

        URI uri = URI.create("http://example.org/test");
        Path f = Bundles.setReference(ref, uri);
        assertEquals("ref.url", f.getFileName().toString());
        assertEquals(bundle.getRoot(), f.getParent());
        assertFalse(Files.exists(ref));

        List<String> uriLines = Files.readAllLines(f, Charset.forName("ASCII"));
        assertEquals(3, uriLines.size());
        assertEquals("[InternetShortcut]", uriLines.get(0));
        assertEquals("URL=http://example.org/test", uriLines.get(1));
        assertEquals("", uriLines.get(2));
    }/*from w w w  .  j a  v  a 2  s.c  om*/
}

From source file:org.apache.taverna.robundle.TestBundles.java

@Test
public void setReferenceIri() throws Exception {
    try (Bundle bundle = Bundles.createBundle()) {
        Path ref = bundle.getRoot().resolve("ref");
        URI uri = new URI("http", "xn--bcher-kva.example.com", "/s\u00F8iland/\u2603snowman", "\u2605star");
        Path f = Bundles.setReference(ref, uri);
        List<String> uriLines = Files.readAllLines(f, Charset.forName("ASCII"));
        // TODO: Double-check that this is actually correct escaping :)
        assertEquals("URL=http://xn--bcher-kva.example.com/s%C3%B8iland/%E2%98%83snowman#%E2%98%85star",
                uriLines.get(1));/*from  ww w .  j  ava 2 s . c  o m*/
    }
}

From source file:org.apache.taverna.robundle.TestBundles.java

@Test
public void setStringValue() throws Exception {
    try (Bundle bundle = Bundles.createBundle()) {
        Path file = bundle.getRoot().resolve("file");
        String string = "A string";
        Bundles.setStringValue(file, string);
        assertEquals(string, Files.readAllLines(file, Charset.forName("UTF-8")).get(0));
    }// ww  w  .  java2  s  . c  om
}

From source file:org.jboss.additional.testsuite.jdkall.present.logging.profiles.LoggingProfilesTestCase.java

@RunAsClient
@ATTest({ "modules/testcases/jdkAll/Wildfly/logging/src/main/java#12.0.0.Final",
        "modules/testcases/jdkAll/Eap7/logging/src/main/java#7.1.0.GA",
        "modules/testcases/jdkAll/Eap71x/logging/src/main/java#7.1.1.GA",
        "modules/testcases/jdkAll/Eap71x-Proposed/logging/src/main/java#7.1.1.GA" })
public void separateApplicationLoggingTest() throws Exception {
    URL testURL = new URL("http://" + managementClient.getMgmtAddress() + ":8080/Application1");

    CloseableHttpClient httpClient = HttpClients.createDefault();
    final HttpGet request = new HttpGet(testURL.toString());

    CloseableHttpResponse response = null;
    response = httpClient.execute(request);

    testURL = new URL("http://" + managementClient.getMgmtAddress() + ":8080/Application2");

    httpClient = HttpClients.createDefault();
    final HttpGet request2 = new HttpGet(testURL.toString());

    response = httpClient.execute(request2);

    List<String> logfile = new LinkedList<>();

    final String logDir = System.getProperty("server.dir") + "/standalone/log";
    if (logDir == null) {
        throw new RuntimeException("Could not resolve jboss.server.log.dir");
    }// w  w  w. j a va2  s .  c o  m
    final java.nio.file.Path logFile = Paths.get(logDir, "myapp1.log");
    if (!Files.notExists(logFile)) {
        logfile = Files.readAllLines(logFile, StandardCharsets.UTF_8);
    }

    assertTrue("Should not have messages from second App...",
            !StringUtils.join(logfile, ", ").contains("Application 2"));
}

From source file:com.splicemachine.derby.impl.load.HdfsUnsafeImportIT.java

public void helpTestConstraints(long maxBadRecords, int insertRowsExpected, boolean expectException)
        throws Exception {
    String tableName = "CONSTRAINED_TABLE";
    TableDAO td = new TableDAO(methodWatcher.getOrCreateConnection());
    td.drop(spliceSchemaWatcher.schemaName, tableName);

    methodWatcher.getOrCreateConnection().createStatement()
            .executeUpdate(format("create table %s ", spliceSchemaWatcher.schemaName + "." + tableName)
                    + "(EMPNO CHAR(6) NOT NULL CONSTRAINT EMP_PK PRIMARY KEY, "
                    + "SALARY DECIMAL(9,2) CONSTRAINT SAL_CK CHECK (SALARY >= 10000), "
                    + "BONUS DECIMAL(9,2),TAX DECIMAL(9,2),CONSTRAINT BONUS_CK CHECK (BONUS > TAX))");

    PreparedStatement ps = methodWatcher
            .prepareStatement(format("call SYSCS_UTIL.IMPORT_DATA_UNSAFE(" + "'%s'," + // schema name
                    "'%s'," + // table name
                    "'%s'," + // insert column list
                    "'%s'," + // file path
                    "','," + // column delimiter
                    "null," + // character delimiter
                    "null," + // timestamp format
                    "null," + // date format
                    "null," + // time format
                    "%d," + // max bad records
                    "'%s'," + // bad record dir
                    "null," + // has one line records
                    "null)", // char set
                    spliceSchemaWatcher.schemaName, tableName, "EMPNO,SALARY,BONUS,TAX",
                    getResourceDirectory() + "test_data/salary_check_constraint.csv", maxBadRecords,
                    BADDIR.getCanonicalPath()));

    try {//from  ww w . j  a v a  2  s. c om
        ps.execute();
    } catch (SQLException e) {
        if (!expectException) {
            throw e;
        }
    }
    ResultSet rs = methodWatcher
            .executeQuery(format("select * from %s.%s", spliceSchemaWatcher.schemaName, tableName));
    List<String> results = Lists.newArrayList();
    while (rs.next()) {
        String name = rs.getString(1);
        String title = rs.getString(2);
        int age = rs.getInt(3);
        Assert.assertTrue("age was null!", !rs.wasNull());
        assertNotNull("Name is null!", name);
        assertNotNull("Title is null!", title);
        assertNotNull("Age is null!", age);
        results.add(String.format("name:%s,title:%s,age:%d", name, title, age));
    }
    Assert.assertEquals(format("Expected %s row1 imported", insertRowsExpected), insertRowsExpected,
            results.size());

    boolean exists = existsBadFile(BADDIR, "salary_check_constraint.csv.bad");
    String badFile = getBadFile(BADDIR, "salary_check_constraint.csv.bad");
    assertTrue("Bad file " + badFile + " does not exist.", exists);
    List<String> badLines = Files.readAllLines((new File(BADDIR, badFile)).toPath(), Charset.defaultCharset());
    assertEquals("Expected 2 lines in bad file " + badFile, 2, badLines.size());
    assertContains(badLines, containsString("BONUS_CK"));
    assertContains(badLines, containsString(spliceSchemaWatcher.schemaName + "." + tableName));
    assertContains(badLines, containsString("SAL_CK"));
}

From source file:de.prozesskraft.pkraft.Manager.java

/**
 * erstellt fuer jeden running step einen watchkey
 * es soll jedes stepverzeichnis mit dem status 'working' observiert werden bis das file ".exit" erscheint
 * @param process//ww w  . j  a  va  2  s  .  com
 * @throws IOException 
 */
private static void createWatchKeysForAllRunningSteps(Process process) throws IOException {
    // diesen Thread ablegen, damit er vom zyklischen thread gekillt werden kann
    watcherThread = Thread.currentThread();

    // einen neuen map erzeugen fuer die watchKeys
    keys = new HashMap<WatchKey, Path>();

    WatchService watcher = FileSystems.getDefault().newWatchService();

    // Anlegen des WatchKeys fuer den Prozess (falls er gestoppt wird, erfolgt die Komunikation mit diesem manager ueber das binaerfile)
    Path processDir = Paths.get(process.getRootdir());
    System.err.println("info: creating a watchkey for the process path " + process.getRootdir());
    WatchKey keyProcess = processDir.register(watcher, ENTRY_MODIFY);
    keys.put(keyProcess, processDir);

    // Anlegen der WatchKeys fuer jeden laufenden Step
    for (Step actStep : process.getStep()) {
        if (actStep.getStatus().equals("working")) {
            Path stepDir = Paths.get(actStep.getAbsdir());
            try {
                System.err.println("info: step " + actStep.getName()
                        + " is working -> creating a watchkey for its path " + actStep.getAbsdir());
                System.err.println("debug: creating...");
                WatchKey key = stepDir.register(watcher, ENTRY_CREATE);
                System.err.println("debug: creating...done. putting to the map");
                keys.put(key, stepDir);
                System.err.println("debug: creating...done. putting to the map...done");
            } catch (IOException e) {
                System.err.println(e);
            } catch (Exception e) {
                System.err.println(e);
            }

            java.io.File stepDirExitFile = new java.io.File(actStep.getAbsdir() + "/.exit");
            java.io.File stepDirStatusFile = new java.io.File(actStep.getAbsdir() + "/.status");

            // falls die datei bereits existiert, wird sofort erneut der Prozess weitergeschoben
            // dies ist dann der fall, wenn ein step gestartet wurde, und danach der manager neu gestartet wurde
            if (stepDirExitFile.exists()) {
                System.err.println("info: .exit file already exists -> shortcutting to pushing the process");

                // alle keys loeschen
                keys = null;

                // den prozess weiter pushen
                pushProcessAsFarAsPossible(process.getRootdir() + "/process.pmb", false);
            }
            // falls der step ein process ist, bibts dort kein .exit file sondern ein .status file
            else if (stepDirStatusFile.exists()) {
                System.err.println("info: .status file already exists.");
                try {
                    java.util.List<String> statusInhalt = Files.readAllLines(stepDirStatusFile.toPath(),
                            Charset.defaultCharset());
                    if (statusInhalt.size() > 0) {
                        String firstLine = statusInhalt.get(0);
                        System.err.println("info: status changed to: " + firstLine);

                        System.err.println("info: .status file contains status " + firstLine);
                        // wenn ein finaler status, dann soll manager aufgeweckt werden
                        if (firstLine.equals("error") || firstLine.equals("finished")) {
                            System.err.println("info: --> shortcutting to pushing process");
                            // alle keys loeschen
                            keys = null;

                            // den prozess weiter pushen
                            pushProcessAsFarAsPossible(process.getRootdir() + "/process.pmb", false);
                        }
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    System.err.println(
                            "IOException: trying to read file: " + stepDirStatusFile.getAbsolutePath());
                    e.printStackTrace();
                } catch (ExceptionInInitializerError e) {
                    System.err.println("ExceptionInInitializerError: trying to read file: "
                            + stepDirStatusFile.getAbsolutePath());
                    e.printStackTrace();
                }
            }

        }
    }

    process.log("info", "now into the watchloop");

    // warten auf ein Signal von einem WatchKey
    for (;;) {

        WatchKey key;
        try {
            key = watcher.take();
        } catch (InterruptedException e) {
            System.err.println(new Timestamp(System.currentTimeMillis())
                    + ": ---- watcher thread: interrupted! returning to alternativer Thread");
            return;
        }

        Path dir = keys.get(key);
        if (dir == null) {
            System.err.println("WatchKey not recognized!!");
            continue;
        }

        for (WatchEvent<?> event : key.pollEvents()) {
            //            System.err.println("debug: poll event " + event);

            WatchEvent.Kind kind = event.kind();

            WatchEvent<Path> ev = (WatchEvent<Path>) event;
            Path name = ev.context();
            // dieses logging fuehrt zur aenderung von stderr.txt und .log, was wiederum ein ENTRY_MODIFY ausloest etc. endlosschleife bis platte volllaeuft
            //            System.err.println("debug: poll context " + name);
            Path child = dir.resolve(name);
            //            System.err.println("debug: poll child " + child);

            if (kind == ENTRY_CREATE) {
                if (child.endsWith(".exit")) {
                    System.err.println("info: waking up, because file created: " + child.toString());

                    // alle keys loeschen
                    keys = null;

                    // den prozess weiter pushen
                    pushProcessAsFarAsPossible(process.getRootdir() + "/process.pmb", false);
                }
            }
            if ((kind == ENTRY_MODIFY) && (child.endsWith("process.pmb"))) {
                //               System.err.println("info: waking up, because process binary file has been modified: " + child.toString());

                // alle keys loeschen
                keys = null;

                // den prozess weiter pushen
                pushProcessAsFarAsPossible(process.getRootdir() + "/process.pmb", false);
            }
            if (kind == ENTRY_CREATE || kind == ENTRY_MODIFY) {
                if (child.endsWith(".status")) {
                    try {
                        java.util.List<String> statusInhalt = Files.readAllLines(child,
                                Charset.defaultCharset());
                        if (statusInhalt.size() > 0) {
                            String firstLine = statusInhalt.get(0);
                            System.err.println("info: status changed to: " + firstLine);

                            // wenn ein finaler status, dann soll manager aufgeweckt werden
                            if (firstLine.equals("error") || firstLine.equals("finished")) {
                                System.err.println("info: waking up, because status changed to: " + firstLine);
                                // alle keys loeschen
                                keys = null;

                                // den prozess weiter pushen
                                pushProcessAsFarAsPossible(process.getRootdir() + "/process.pmb", false);
                            }
                        }
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        System.err.println("IOException: trying to read file: " + child.toString());
                        e.printStackTrace();
                    } catch (ExceptionInInitializerError e) {
                        System.err.println(
                                "ExceptionInInitializerError: trying to read file: " + child.toString());
                        e.printStackTrace();
                    }

                }
            }

            // reset the triggered key
            key.reset();
        }
    }
}

From source file:com.bombardier.plugin.scheduling.TestScheduler.java

/**
 * Used to get the number of lines in a file ignoring lines that are empty
 * or contain only white spaces.//from   w ww . ja v  a 2 s. c  o  m
 * 
 * @param file
 *            the file to be read
 * @return the number of lines
 * @throws Exception
 * @since 1.0
 */
private int getNumOfLines(FilePath file) throws Exception {
    List<String> list = Files.readAllLines(Paths.get(file.absolutize().toURI()), StandardCharsets.UTF_8);
    // remove empty lines
    list.removeIf(new Predicate<String>() {
        @Override
        public boolean test(String arg0) {
            return !StringUtils.isNotBlank(arg0);
        }
    });
    return list.size();
}