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.testeditor.fixture.swt.SwtBotFixture.java

/**
 * Waits until a previous launch is terminated.
 * //from  ww  w . j av a2s .  c  o  m
 * @throws InterruptedException
 *             while waiting.
 * 
 */
protected void waitUntilPreviousLaunchIsFinished() throws InterruptedException {
    LOGGER.info("Already a process running? " + runningApp);
    int count = 0;
    while (runningApp) {
        Thread.sleep(100);
        count++;
        if (count > 100) {
            LOGGER.error(">>>>>>> Old process blocks AUT start for 10 seconds. Giving up for test: " + testName
                    + ".");
            try {
                List<String> allLines = Files.readAllLines(
                        new File(new File(getWorkspacePath(), ".metadata"), ".log").toPath(),
                        Charset.forName("UTF-8"));
                LOGGER.error("AUT .log content:");
                for (String string : allLines) {
                    LOGGER.error(string);
                }
            } catch (Exception e) {
                LOGGER.error("Error reading .log of AUT.", e);
            } finally {
                stopApplication();
            }
        }
    }
}

From source file:open.dolphin.client.MainWindowController.java

@FXML
protected void fileChoose() {
    FileChooser fc = new FileChooser();
    fc.setTitle("select file");
    fc.setInitialDirectory(new File(System.getProperty("user.home")));
    fc.getExtensionFilters().add(new ExtensionFilter("????", "*.*"));

    File f = fc.showOpenDialog(null);
    if (f != null) {
        try {//  ww w.  jav a 2s.com
            Path path = f.toPath();
            choiceFile.setText(path.getFileName().toString());
            for (String s : Files.readAllLines(path, Charset.forName("SJIS"))) {
                System.out.println(s);
            }
        } catch (IOException ex) {
            Logger.getLogger(MainWindowController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:org.codice.ddf.platform.migratable.impl.PlatformMigratableTest.java

private boolean verifyImported(Path p) throws IOException {
    List<String> lines = Files.readAllLines(p, StandardCharsets.UTF_8);
    String tag = lines.get(0).split("&")[1];
    return StringUtils.equals(tag, String.format(DDF_EXPORTED_TAG_TEMPLATE, DDF_EXPORTED_HOME));
}

From source file:org.jenkinsci.plugins.gitclient.GitClientTest.java

@Test
public void testModifiedTrackedFilesReset() throws Exception {
    ObjectId commitA = commitOneFile("First commit");

    /* Modify every plain file in the root of the repository */
    String randomUUID = UUID.randomUUID().toString();
    String randomString = "Added after initial file checkin " + randomUUID + "\n";
    File lastModifiedFile = null;
    for (File file : repoRoot.listFiles()) {
        if (file.isFile()) {
            try (PrintWriter writer = new PrintWriter(
                    new OutputStreamWriter(Files.newOutputStream(file.toPath()), "UTF-8"), true)) {
                writer.print(randomString);
            }/*from   w w  w .j av  a  2 s.c o m*/
            lastModifiedFile = file;
        }
    }
    assertTrue("No files modified " + repoRoot, lastModifiedFile != null);

    /* Checkout a new branch - verify no files retain modification */
    gitClient.checkout().branch("master-" + randomUUID).ref(commitA.getName()).execute();

    lastModifiedFile = null;
    for (File file : repoRoot.listFiles()) {
        if (file.isFile()) {
            List<String> lines = Files.readAllLines(file.toPath(), Charset.forName("UTF-8"));
            for (String line : lines) {
                if (line.contains(randomString)) {
                    lastModifiedFile = file;
                }
            }
        }
    }
    assertNull("Checkout did not revert change in " + lastModifiedFile, lastModifiedFile);
}

From source file:org.madsonic.service.MediaFileService.java

private String checkForCommentFile(File file) {

    File commentFile = new File(file.getPath(), "comment.txt");
    if (commentFile.exists()) {
        LOG.info("## CommentFile found: " + commentFile);
        Path path = Paths.get(commentFile.getPath());
        List<String> lines = null;
        String listString = "";

        try {/* w w  w  .ja v a 2  s  .co  m*/
            lines = Files.readAllLines(path, StandardCharsets.UTF_8);
        } catch (IOException e) {
            LOG.warn("## error reading commentfile: " + commentFile);
            //            e.printStackTrace();
        }

        if (lines == null) {
            try {
                lines = Files.readAllLines(path, StandardCharsets.ISO_8859_1);
            } catch (IOException e) {
                LOG.warn("## error reading commentfile: " + commentFile);
                //                  e.printStackTrace();
            }
        }

        for (String s : lines) {
            s = s.replace("", "'");
            listString += s + " \\\\";
        }

        return listString;
    }
    return null;
}

From source file:org.testeditor.fixture.swt.SwtBotFixture.java

/**
 * Opens a file in the workspace and returns the source as a List.
 * //  w  w  w  .j  a  va2s .c  om
 * @param directory
 *            start path parameter
 * @param testFilePath
 *            comma separated path to file path
 * @return a list of all source lines
 * @throws IOException
 *             if file not exist
 */
private List<String> sourceList(String directory, String testFilePath) throws IOException {
    String[] folder = testFilePath.split(",");
    directory += File.separator + folder[0] + File.separator + "FitNesseRoot"; // Project
    // name
    // and
    // FitNsesseRoot
    for (String string : folder) {
        directory += File.separator + string;
    }
    directory += File.separator + "content.txt";
    File dirFile = new File(directory);
    Path path = dirFile.toPath();
    LOGGER.warn("PATH " + path.toString() + "  " + path.toFile().exists() + "---" + Charset.defaultCharset());
    List<String> lines = Files.readAllLines(path, Charset.defaultCharset());
    return lines;
}

From source file:paq_bancos.pre_libro_bancos.java

public void seleccionarArchivo(FileUploadEvent event) {
    if (tex_separa.getValue() == null || tex_separa.getValue().toString().isEmpty()) {
        utilitario.agregarMensajeError("Ingrese el separador de columnas del archivo", "");
        return;//from  ww w.  ja  v  a2 s  .co m
    }
    try {
        final File tempFile = File.createTempFile("archivoConcilia", "csv");
        tempFile.deleteOnExit();
        try (FileOutputStream out = new FileOutputStream(tempFile)) {
            IOUtils.copy(event.getFile().getInputstream(), out);
        }
        List<String> lines = Files.readAllLines(tempFile.toPath(), StandardCharsets.UTF_8);
        int intFila = 0;
        //Columnas            
        String strColumnas = "";
        List listaColumnas = new ArrayList();
        if (lines.isEmpty() == false) {
            String[] array = lines.get(0).split("" + tex_separa.getValue() + "\"");
            for (String array1 : array) {

                if (strColumnas.isEmpty() == false) {
                    strColumnas += ",";
                }
                if (array1.replace("\"", "").equalsIgnoreCase("FECHA")) {
                    strColumnas += "'' FECHA_MOVIMIENTO";
                    Object fila[] = { "FECHA_MOVIMIENTO", "FECHA_MOVIMIENTO" };
                    listaColumnas.add(fila);
                } else {
                    strColumnas += "'' " + array1.replace("\"", "");
                    Object fila[] = { array1.replace("\"", ""), array1.replace("\"", "") };
                    listaColumnas.add(fila);
                }

            }
        }
        com_colDocumento.setCombo(listaColumnas);
        com_colValor.setCombo(listaColumnas);
        UIComponent padre = tab_tabla1.getParent();
        padre.getChildren().remove(tab_tabla1);
        tab_tabla1 = new Tabla();
        tab_tabla1.setId("tab_tabla1");
        tab_tabla1.setSql("SELECT 0 as ENCONTRO, " + strColumnas + " from sis_empresa WHERE IDE_EMPR=1");
        tab_tabla1.setLectura(true);
        tab_tabla1.setRows(10);
        for (Columna col : tab_tabla1.getColumnas()) {
            col.setFiltroContenido();
            col.setLongitud(30);
            col.setAncho(30);
        }
        tab_tabla1.getColumna("ENCONTRO").setVisible(false);
        tab_tabla1.setValueExpression("rowStyleClass",
                "fila.campos[0] eq 'false' ? 'text-red' : fila.campos[1] eq 'true'  ? 'text-green' : null");

        tab_tabla1.dibujar();
        tab_tabla1.setLectura(false);
        padre.getChildren().add(tab_tabla1);
        //Filas
        for (String line : lines) {
            if (intFila == 0) {
                intFila++;
                continue;
            }
            tab_tabla1.insertar();
            String[] array = line.split(",\"");
            int intColumna = 1;
            for (String array1 : array) {
                tab_tabla1.setValor(tab_tabla1.getColumnas()[intColumna].getNombre(), array1.replace("\"", ""));
                intColumna++;
            }
            intFila++;
        }
        upl_importa.setNombreReal(event.getFile().getFileName());
        utilitario.addUpdate("gri_valida,grid");
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.dell.asm.asmcore.asmmanager.app.rest.ServiceTemplateService.java

/**
 * Get default template customized with uploaded config file
 * @param configPath/* w  w  w.  jav  a 2s . c  o m*/
 * @return
 * @throws WebApplicationException
 */
@Override
public ServiceTemplate getUploadedConfigTemplate(String configPath) throws IOException {

    try {
        String configXml = "";
        List<String> lines = Files.readAllLines(Paths.get(configPath), Charset.defaultCharset());
        for (String line : lines)
            configXml += line;
        ServiceTemplate svcTmpl = getDefaultTemplate();
        processSystemConfiguration(svcTmpl, configXml, null, null);
        return svcTmpl;
    } catch (IOException e) {
        LOGGER.error("Could not read imported configuration profile file at " + configPath, e);
        throw new LocalizedWebApplicationException(Response.Status.INTERNAL_SERVER_ERROR,
                AsmManagerMessages.internalError());
    } catch (WSManException e) {
        LOGGER.error("Could not process imported configuration profile", e);
        throw new LocalizedWebApplicationException(Response.Status.INTERNAL_SERVER_ERROR,
                AsmManagerMessages.internalError());
    } finally {
        Files.deleteIfExists(Paths.get(configPath));
    }
}

From source file:com.splicemachine.derby.impl.load.HdfsImportIT.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(" + "'%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  w w  w .j  a  v  a2s  .  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:com.github.podd.example.ExamplePoddClient.java

public Map<Path, String> uploadToStorage(final List<Path> bagsToUpload, final String sshServerFingerprint,
        final String sshHost, final int portNo, final String username, final Path pathToPublicKey,
        final Path localRootPath, final Path remoteRootPath, final PasswordFinder keyExtractor)
        throws PoddClientException, NoSuchAlgorithmException, IOException {
    final Map<Path, String> results = new ConcurrentHashMap<>();

    final ConcurrentMap<Path, ConcurrentMap<PoddDigestUtils.Algorithm, String>> digests = PoddDigestUtils
            .getDigests(bagsToUpload);//w w w  .  j  av a  2  s  .c om

    try (SSHClient sshClient = new SSHClient(ExamplePoddClient.DEFAULT_CONFIG);) {
        sshClient.useCompression();
        sshClient.addHostKeyVerifier(sshServerFingerprint);
        sshClient.connect(sshHost, portNo);
        if (!Files.exists(pathToPublicKey)) {
            throw new PoddClientException("Could not find public key: " + pathToPublicKey);
        }
        if (!SecurityUtils.isBouncyCastleRegistered()) {
            throw new PoddClientException("Bouncy castle needed");
        }
        final FileKeyProvider rsa = new PKCS8KeyFile();
        rsa.init(pathToPublicKey.toFile(), keyExtractor);
        sshClient.authPublickey(username, rsa);
        // Session session = sshClient.startSession();
        try (SFTPClient sftp = sshClient.newSFTPClient();) {
            for (final Path nextBag : bagsToUpload) {
                // Check to make sure that the bag was under the local root path
                final Path localPath = nextBag.toAbsolutePath();
                if (!localPath.startsWith(localRootPath)) {
                    this.log.error(
                            "Local bag path was not a direct descendant of the local root path: {} {} {}",
                            localRootPath, nextBag, localPath);
                    throw new PoddClientException(
                            "Local bag path was not a direct descendant of the local root path: " + localPath
                                    + " " + localRootPath);
                }

                // Take the local root path out to get the subpath to use on the remote
                final Path remoteSubPath = localPath.subpath(localRootPath.getNameCount(),
                        nextBag.getNameCount() - 1);

                this.log.info("Remote sub path: {}", remoteSubPath);

                final Path remoteDirPath = remoteRootPath.resolve(remoteSubPath);
                this.log.info("Remote dir path: {}", remoteDirPath);

                final Path remoteBagPath = remoteDirPath.resolve(nextBag.getFileName());

                this.log.info("Remote bag path: {}", remoteBagPath);

                boolean fileFound = false;
                boolean sizeCorrect = false;
                try {
                    // check details of a remote bag
                    final FileAttributes attribs = sftp.lstat(remoteBagPath.toAbsolutePath().toString());
                    final long localSize = Files.size(nextBag);
                    final long remoteSize = attribs.getSize();

                    if (localSize <= 0) {
                        this.log.error("Local bag was empty: {}", nextBag);
                        sizeCorrect = false;
                        fileFound = false;
                    } else if (remoteSize <= 0) {
                        this.log.warn("Remote bag was empty: {} {}", nextBag, attribs);
                        sizeCorrect = false;
                        fileFound = false;
                    } else if (localSize == remoteSize) {
                        this.log.info("Found file on remote already with same size as local: {} {}", nextBag,
                                remoteBagPath);
                        sizeCorrect = true;
                        fileFound = true;
                    } else {
                        sizeCorrect = false;
                        fileFound = true;
                        // We always assume that a non-zero local file is correct
                        // The bags contain time-stamps that will be modified when they are
                        // regenerated, likely changing the file-size, and hopefully changing
                        // the digest checksums
                        // throw new PoddClientException(
                        // "Could not automatically compare file sizes (need manual intervention to delete one) : "
                        // + nextBag + " " + remoteBagPath + " localSize=" + localSize
                        // + " remoteSize=" + remoteSize);
                    }
                } catch (final IOException e) {
                    // lstat() throws an IOException if the file does not exist
                    // Ignore
                    sizeCorrect = false;
                    fileFound = false;
                }

                final ConcurrentMap<Algorithm, String> bagDigests = digests.get(nextBag);
                if (bagDigests.isEmpty()) {
                    this.log.error("No bag digests were generated for bag: {}", nextBag);
                }
                for (final Entry<Algorithm, String> entry : bagDigests.entrySet()) {
                    final Path localDigestPath = localPath
                            .resolveSibling(localPath.getFileName() + entry.getKey().getExtension());
                    // Create the local digest file
                    Files.copy(
                            new ReaderInputStream(new StringReader(entry.getValue()), StandardCharsets.UTF_8),
                            localDigestPath);
                    final Path remoteDigestPath = remoteBagPath
                            .resolveSibling(remoteBagPath.getFileName() + entry.getKey().getExtension());
                    boolean nextDigestFileFound = false;
                    boolean nextDigestCorrect = false;
                    try {
                        final Path tempFile = Files.createTempFile("podd-digest-",
                                entry.getKey().getExtension());
                        final SFTPFileTransfer sftpFileTransfer = new SFTPFileTransfer(sftp.getSFTPEngine());
                        sftpFileTransfer.download(remoteBagPath.toAbsolutePath().toString(),
                                tempFile.toAbsolutePath().toString());
                        nextDigestFileFound = true;

                        final List<String> allLines = Files.readAllLines(tempFile, StandardCharsets.UTF_8);
                        if (allLines.isEmpty()) {
                            nextDigestCorrect = false;
                        } else if (allLines.size() > 1) {
                            nextDigestCorrect = false;
                        }
                        // Check if the digests match exactly
                        else if (allLines.get(0).equals(entry.getValue())) {
                            nextDigestCorrect = true;
                        } else {
                            nextDigestCorrect = false;
                        }
                    } catch (final IOException e) {
                        nextDigestFileFound = false;
                        nextDigestCorrect = false;
                    }
                    if (nextDigestFileFound && nextDigestCorrect) {
                        this.log.info(
                                "Not copying digest to remote as it exists and contains the same content as the local digest");
                    } else if (nextDigestFileFound && !nextDigestCorrect) {
                        this.log.error("Found remote digest but content was not correct: {} {}",
                                localDigestPath, remoteDigestPath);
                        sftp.rm(remoteDigestPath.toString());
                        this.log.info("Copying digest to remote: {}", remoteDigestPath);
                        sftp.put(new FileSystemFile(localDigestPath.toString()), remoteDigestPath.toString());
                    } else if (!nextDigestFileFound) {
                        this.log.info("About to make directories on remote: {}", remoteDirPath);
                        sftp.mkdirs(remoteDirPath.toString());
                        this.log.info("Copying digest to remote: {}", remoteDigestPath);
                        sftp.put(new FileSystemFile(localDigestPath.toString()), remoteDigestPath.toString());
                    }
                }

                if (fileFound && sizeCorrect) {
                    this.log.info("Not copying bag to remote as it exists and is the same size as local bag");
                } else if (fileFound && !sizeCorrect) {
                    this.log.error("Found remote bag but size was not correct: {} {}", nextBag, remoteBagPath);
                    sftp.rm(remoteBagPath.toString());
                    this.log.info("Copying bag to remote: {}", remoteBagPath);
                    sftp.put(new FileSystemFile(localPath.toString()), remoteBagPath.toString());
                } else if (!fileFound) {
                    this.log.info("About to make directories on remote: {}", remoteDirPath);
                    sftp.mkdirs(remoteDirPath.toString());
                    this.log.info("Copying bag to remote: {}", remoteBagPath);
                    sftp.put(new FileSystemFile(localPath.toString()), remoteBagPath.toString());
                }

            }
        }
    } catch (final IOException e) {
        throw new PoddClientException("Could not copy a bag to the remote location", e);
    }

    return results;
}