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.nuxeo.launcher.TestNuxeoLauncher.java

@Test
public void testClidOption()
        throws ConfigurationException, ParseException, IOException, PackageException, InvalidCLID {
    Path instanceClid = Paths.get(TEST_INSTANCE_CLID);
    if (!Files.exists(instanceClid)) {
        throw new AssumptionViolatedException("No test CLID available");
    }/*from   ww  w .j av a 2  s  .c  om*/
    String[] args = new String[] { "--clid", instanceClid.toString(), "showconf" };
    final NuxeoLauncher launcher = NuxeoLauncher.createLauncher(args);
    InstanceInfo info = launcher.getInfo();
    assertNotNull("Failed to get instance info", info);
    List<String> clidLines = Files.readAllLines(instanceClid, Charsets.UTF_8);
    LogicalInstanceIdentifier expectedClid = new LogicalInstanceIdentifier(
            clidLines.get(0) + LogicalInstanceIdentifier.ID_SEP + clidLines.get(1), "expected clid");
    assertEquals("Not the right instance.clid file: ", expectedClid.getCLID(), info.clid);
}

From source file:no.imr.stox.functions.utils.RUtils.java

public static Boolean installRstox(String ftpPath, String rFolder) {
    try {// w w w.j  ava  2s .  co  m
        String triggerFile = getTmpDir() + "installRstox.R";
        try (PrintWriter pw = new PrintWriter(triggerFile)) {
            //pw.println("Sys.setenv(JAVA_HOME = \"\")");
            if (ftpPath.startsWith("ftp.")) {
                ftpPath = "ftp://" + ftpPath;
            }
            ftpPath = ftpPath + "/" + "README";
            pw.println("source(\"" + ftpPath + "\")");
            //pw.println("install.packages(pkgFile, repos=NULL, type=\"source\", lib=.libPaths()[1])");
        } catch (Throwable ex) {
            ex.printStackTrace();
        }
        callR(rFolder, triggerFile, true);
        if (!new File(triggerFile + "out").exists()) {
            return false;
        }
        List<String> lines = Files.readAllLines(Paths.get(triggerFile + "out"), Charset.forName("UTF-8"));
        lines = lines.stream().filter(s -> s.contains("DONE")).collect(Collectors.toList());
        return !lines.isEmpty();
    } catch (IOException ex) {
        Logger.getLogger(RUtils.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:org.apache.ranger.patch.PatchPersmissionModel_J10003.java

private List<String> readUserNamesFromFile(String aFileName) throws IOException {
    List<String> userNames = new ArrayList<String>();
    if (!StringUtils.isEmpty(aFileName)) {
        Path path = Paths.get(aFileName);
        if (Files.exists(path) && Files.isRegularFile(path)) {
            List<String> fileContents = Files.readAllLines(path, ENCODING);
            if (fileContents != null && fileContents.size() > 0) {
                for (String line : fileContents) {
                    if (!StringUtils.isEmpty(line) && !userNames.contains(line)) {
                        try {
                            userNames.add(line.trim());
                        } catch (Exception ex) {
                        }/*from  w  w w  .j av a2 s .  c o  m*/
                    }
                }
            }
        }
    }
    return userNames;
}

From source file:org.jboss.as.test.integration.logging.formatters.JsonFormatterTestCase.java

@Test
public void testFormattedException() throws Exception {
    configure(Collections.emptyMap(), Collections.emptyMap(), false);

    // Change the exception-output-type
    executeOperation(/* w ww  .ja  v a 2 s  . co m*/
            Operations.createWriteAttributeOperation(FORMATTER_ADDRESS, "exception-output-type", "formatted"));

    final String msg = "Logging test: JsonFormatterTestCase.testNoExceptions";
    int statusCode = getResponse(msg,
            Collections.singletonMap(LoggingServiceActivator.LOG_EXCEPTION_KEY, "true"));
    Assert.assertTrue("Invalid response statusCode: " + statusCode, statusCode == HttpStatus.SC_OK);

    final List<String> expectedKeys = createDefaultKeys();
    expectedKeys.add("stackTrace");

    for (String s : Files.readAllLines(logFile, StandardCharsets.UTF_8)) {
        if (s.trim().isEmpty())
            continue;
        try (JsonReader reader = Json.createReader(new StringReader(s))) {
            final JsonObject json = reader.readObject();

            validateDefault(json, expectedKeys, msg);
            validateStackTrace(json, true, false);
        }
    }
}

From source file:com.spotify.docker.BuildMojoTest.java

public void testBuildWithGeneratedDockerfile() throws Exception {
    final File pom = getTestFile("src/test/resources/pom-build-generated-dockerfile.xml");
    assertNotNull("Null pom.xml", pom);
    assertTrue("pom.xml does not exist", pom.exists());

    final BuildMojo mojo = setupMojo(pom);
    final DockerClient docker = mock(DockerClient.class);
    mojo.execute(docker);/* w  ww .  j  a va  2s  .co  m*/

    verify(docker).build(eq(Paths.get("target/docker")), eq("busybox"), any(AnsiProgressHandler.class));
    assertFilesCopied();
    assertEquals("wrong dockerfile contents", GENERATED_DOCKERFILE,
            Files.readAllLines(Paths.get("target/docker/Dockerfile"), UTF_8));
}

From source file:nl.mvdr.umvc3replayanalyser.ocr.TesseractOCREngine.java

/**
 * Reads the nonempty line from the given text file.
 * /*w  ww . j a  v  a 2 s .c om*/
 * @param textFile
 *            text file to be read
 * @return contents of the nonempty line in the file
 * @throws IOException
 *             if reading the file fails due to an I/O error
 * @throws OCRException
 *             if the file is empty or contains multiple nonempty lines
 */
private String readLineFromFile(File textFile) throws IOException, OCRException {
    if (log.isDebugEnabled()) {
        log.debug("Reading from file: " + textFile);
    }
    String result;
    List<String> lines = Files.readAllLines(textFile.toPath(), Charset.defaultCharset());
    result = "";
    for (String line : lines) {
        if ("".equals(result)) {
            result = line;
        } else if (!"".equals(line)) {
            // We've already read a nonempty line, now we've found another one.
            throw new OCRException("Image contains more than one line of text: " + lines);
        } // else: empty line, skip it
    }
    if ("".equals(result)) {
        throw new OCRException("No text found.");
    }
    return result;
}

From source file:io.fabric8.docker.client.impl.BuildImage.java

@Override
public OutputHandle fromFolder(String path) {
    try {// w w  w. j a va 2s  .c o  m
        final Path root = Paths.get(path);
        final Path dockerIgnore = root.resolve(DOCKER_IGNORE);
        final List<String> ignorePatterns = new ArrayList<>();
        if (dockerIgnore.toFile().exists()) {
            for (String p : Files.readAllLines(dockerIgnore, UTF_8)) {
                ignorePatterns.add(path.endsWith(File.separator) ? path + p : path + File.separator + p);
            }
        }

        final DockerIgnorePathMatcher dockerIgnorePathMatcher = new DockerIgnorePathMatcher(ignorePatterns);

        File tempFile = Files.createTempFile(Paths.get(DEFAULT_TEMP_DIR), DOCKER_PREFIX, BZIP2_SUFFIX).toFile();

        try (FileOutputStream fout = new FileOutputStream(tempFile);
                BufferedOutputStream bout = new BufferedOutputStream(fout);
                BZip2CompressorOutputStream bzout = new BZip2CompressorOutputStream(bout);
                final TarArchiveOutputStream tout = new TarArchiveOutputStream(bzout)) {
            Files.walkFileTree(root, new SimpleFileVisitor<Path>() {

                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                        throws IOException {
                    if (dockerIgnorePathMatcher.matches(dir)) {
                        return FileVisitResult.SKIP_SUBTREE;
                    }
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    if (dockerIgnorePathMatcher.matches(file)) {
                        return FileVisitResult.SKIP_SUBTREE;
                    }

                    final Path relativePath = root.relativize(file);
                    final TarArchiveEntry entry = new TarArchiveEntry(file.toFile());
                    entry.setName(relativePath.toString());
                    entry.setMode(TarArchiveEntry.DEFAULT_FILE_MODE);
                    entry.setSize(attrs.size());
                    tout.putArchiveEntry(entry);
                    Files.copy(file, tout);
                    tout.closeArchiveEntry();
                    return FileVisitResult.CONTINUE;
                }
            });
            fout.flush();
        }
        return fromTar(tempFile.getAbsolutePath());

    } catch (IOException e) {
        throw DockerClientException.launderThrowable(e);
    }
}

From source file:org.mycore.frontend.cli.MCRCommandLineInterface.java

/**
 * Show contents of a local text file, including line numbers.
 * /* w w w . j a v  a2s  .  c o  m*/
 * @param fname
 *            the filename
 */
public static void show(String fname) throws Exception {
    AtomicInteger ln = new AtomicInteger();
    System.out.println();
    Files.readAllLines(Paths.get(fname), Charset.defaultCharset())
            .forEach(l -> System.out.printf(Locale.ROOT, "%04d: %s", ln.incrementAndGet(), l));
    System.out.println();
}

From source file:net.cyllene.hackerrank.downloader.HackerrankDownloader.java

/**
 * Gets a secret key from configuration file in user.home.
 * The secret key is a _hackerrank_session variable stored in cookies by server.
 * To simplify things, no login logic is present in this program, it means
 * you should login somewhere else and then provide this value in the config.
 *
 * @return String representing a _hackerrank_session id, about 430 characters long.
 *//*w  ww  . j  ava  2s.c  om*/
private static String getSecretFromConfig() {
    final String confPathStr = System.getProperty("user.home") + File.separator
            + DownloaderSettings.KEYFILE_NAME;
    final Path confPath = Paths.get(confPathStr);
    String result = null;
    try {
        result = Files.readAllLines(confPath, StandardCharsets.US_ASCII).get(0);
    } catch (IOException e) {
        System.err.println("Fatal Error: Unable to open configuration file " + confPathStr
                + System.lineSeparator() + "File might be missing, empty or inaccessible by user."
                + System.lineSeparator() + "It must contain a single ASCII line, a value of \""
                + DownloaderSettings.SECRET_COOKIE_ID + "\" cookie variable," + System.lineSeparator()
                + "which length is about 430 symbols.");
        System.exit(1);
    }

    return result;
}

From source file:com.spotify.docker.BuildMojoTest.java

public void testBuildGeneratedDockerFile_CopiesEntireDirectory() throws Exception {
    final File pom = getTestFile("src/test/resources/pom-build-copy-entire-directory.xml");

    final BuildMojo mojo = setupMojo(pom);
    final DockerClient docker = mock(DockerClient.class);
    mojo.execute(docker);/*from   w  w w.  j a v  a 2s. com*/

    verify(docker).build(eq(Paths.get("target/docker")), eq("test-copied-directory"),
            any(AnsiProgressHandler.class));

    List<String> expectedDockerFileContents = ImmutableList.of("FROM busybox", "ADD /data /data",
            "ENTRYPOINT echo");

    assertEquals("wrong dockerfile contents", expectedDockerFileContents,
            Files.readAllLines(Paths.get("target/docker/Dockerfile"), UTF_8));

    assertFileExists("target/docker/data/file.txt");
    assertFileExists("target/docker/data/nested/file2");
}