Example usage for java.nio.file Files lines

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

Introduction

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

Prototype

public static Stream<String> lines(Path path) throws IOException 

Source Link

Document

Read all lines from a file as a Stream .

Usage

From source file:de.bund.bfr.knime.gis.GisUtils.java

public static CoordinateReferenceSystem getCoordinateSystem(String shpFile)
        throws InvalidPathException, MalformedURLException, IOException, FactoryException, NoSuchFileException {
    try (Stream<String> stream = Files
            .lines(KnimeUtils.getFile(FilenameUtils.removeExtension(shpFile) + ".prj").toPath())) {
        return CRS.parseWKT(stream.collect(Collectors.joining()));
    }//from   w  ww .  jav a2 s. c  om
}

From source file:org.perfcake.examples.weaver.Weaver.java

/**
 * Initializes the configuration.//  w  w  w . ja  va  2s  .c  o m
 *
 * @throws IOException
 *       When it was not possible to parse the configuration.
 */
public void init() throws IOException {
    int maxThreads = Files.lines(Paths.get(config)).collect(Collectors.summingInt(this::parseWorker));
    if (threads > maxThreads || threads == 0) {
        if (threads > maxThreads) {
            log.warn("Maximum possible threads is " + maxThreads + ", while you requested " + threads
                    + ". Using " + maxThreads + ".");
        }
        threads = maxThreads;
    }

    if (shuffle) {
        log.info("Shuffling workers...");

        final List<Worker> workersList = workers.stream().collect(Collectors.toList());
        Collections.shuffle(workersList);
        workers.clear();
        workersList.forEach(workers::offer);
    }

    log.info("Creating executor with " + threads + " threads.");

    executor = new ThreadPoolExecutor(threads, threads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(),
            new ThreadFactoryBuilder().setDaemon(true).setNameFormat("worker-thread-%d").build());
}

From source file:es.upv.grycap.coreutils.logging.test.LogManagerTest.java

private void assertThatLogfileContains(final String msg) throws IOException {
    assertThat("Log file contains expected message",
            Files.lines(Paths.get(TESTLOG_FILENAME)).anyMatch(line -> line.contains(msg)));
}

From source file:com.intelligentz.appointmentz.controllers.addSession.java

@SuppressWarnings("Since15")
@Override/*from   w  w  w .j a  v  a 2 s  .c om*/
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    try {
        String room_id = null;
        String doctor_id = null;
        String start_time = null;
        String date_picked = null;
        ArrayList<SessonCustomer> sessonCustomers = new ArrayList<>();
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // maximum size that will be stored in memory
        factory.setSizeThreshold(maxMemSize);
        // Location to save data that is larger than maxMemSize.
        factory.setRepository(new File(filePath + "temp"));

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        // maximum file size to be uploaded.
        upload.setSizeMax(maxFileSize);

        // Parse the request to get file items.
        List fileItems = upload.parseRequest(req);

        // Process the uploaded file items
        Iterator i = fileItems.iterator();

        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                String fileName = fi.getName();
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();
                // Write the file
                if (fileName.lastIndexOf("\\") >= 0) {
                    filePath = filePath + fileName.substring(fileName.lastIndexOf("\\"));
                    file = new File(filePath);
                } else {
                    filePath = filePath + fileName.substring(fileName.lastIndexOf("\\") + 1);
                    file = new File(filePath);
                }
                fi.write(file);
                Files.lines(Paths.get(filePath)).forEach((line) -> {
                    String[] cust = line.split(",");
                    sessonCustomers.add(new SessonCustomer(cust[0].trim(), Integer.parseInt(cust[1].trim())));
                });
            } else {
                if (fi.getFieldName().equals("room_id"))
                    room_id = fi.getString();
                else if (fi.getFieldName().equals("doctor_id"))
                    doctor_id = fi.getString();
                else if (fi.getFieldName().equals("start_time"))
                    start_time = fi.getString();
                else if (fi.getFieldName().equals("date_picked"))
                    date_picked = fi.getString();
            }
        }

        con = new connectToDB();
        if (con.connect()) {
            Connection connection = con.getConnection();
            Class.forName("com.mysql.jdbc.Driver");
            Statement stmt = connection.createStatement();
            String SQL, SQL1, SQL2;
            SQL1 = "insert into db_bro.session ( doctor_id, room_id, date, start_time) VALUES (?,?,?,?)";
            PreparedStatement preparedStmt = connection.prepareStatement(SQL1);
            preparedStmt.setString(1, doctor_id);
            preparedStmt.setString(2, room_id);
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH:mm");
            try {
                java.util.Date d = formatter.parse(date_picked + "-" + start_time);
                Date d_sql = new Date(d.getTime());
                java.util.Date N = new java.util.Date();
                if (N.compareTo(d) > 0) {
                    res.sendRedirect("./error.jsp?error=Invalid Date!");
                }
                //String [] T = start_time.split(":");
                //Time t = Time.valueOf(start_time);
                //Time t = new Time(Integer.parseInt(T[0]),Integer.parseInt(T[1]),0);

                //java.sql.Time t_sql = new java.sql.Date(d.getTime());
                preparedStmt.setString(4, start_time + ":00");
                preparedStmt.setDate(3, d_sql);
            } catch (ParseException e) {
                displayMessage(res, "Invalid Date!" + e.getLocalizedMessage());
            }

            // execute the preparedstatement
            preparedStmt.execute();

            SQL = "select * from db_bro.session ORDER BY session_id DESC limit 1";
            ResultSet rs = stmt.executeQuery(SQL);

            boolean check = false;
            while (rs.next()) {
                String db_doctor_id = rs.getString("doctor_id");
                String db_date_picked = rs.getString("date");
                String db_start_time = rs.getString("start_time");
                String db_room_id = rs.getString("room_id");

                if ((doctor_id == null ? db_doctor_id == null : doctor_id.equals(db_doctor_id))
                        && (start_time == null ? db_start_time == null
                                : (start_time + ":00").equals(db_start_time))
                        && (room_id == null ? db_room_id == null : room_id.equals(db_room_id))
                        && (date_picked == null ? db_date_picked == null
                                : date_picked.equals(db_date_picked))) {
                    check = true;
                    //displayMessage(res,"Authentication Success!");
                    SQL2 = "insert into db_bro.session_customers ( session_id, mobile, appointment_num) VALUES (?,?,?)";
                    for (SessonCustomer sessonCustomer : sessonCustomers) {
                        preparedStmt = connection.prepareStatement(SQL2);
                        preparedStmt.setString(1, rs.getString("session_id"));
                        preparedStmt.setString(2, sessonCustomer.getMobile());
                        preparedStmt.setInt(3, sessonCustomer.getAppointment_num());
                        preparedStmt.execute();
                    }
                    try {
                        connection.close();
                    } catch (SQLException e) {
                        displayMessage(res, "SQLException");
                    }

                    res.sendRedirect("./home");

                }
            }
            if (!check) {

                try {
                    connection.close();
                } catch (SQLException e) {
                    displayMessage(res, "SQLException");
                }
                displayMessage(res, "SQL query Failed!");
            }
        } else {
            con.showErrormessage(res);
        }

        /*res.setContentType("text/html");//setting the content type
        PrintWriter pw=res.getWriter();//get the stream to write the data
                
        //writing html in the stream
        pw.println("<html><body>");
        pw.println("Welcome to servlet: "+username);
        pw.println("</body></html>");
                
        pw.close();//closing the stream
        */
    } catch (Exception ex) {
        Logger.getLogger(authenticate.class.getName()).log(Level.SEVERE, null, ex);
        displayMessage(res, "Error!" + ex.getLocalizedMessage());
    }
}

From source file:org.xlrnet.tibaija.FileSystemCodeProvider.java

@NotNull
private String loadFileContent(@NotNull Path filepath) throws IOException {
    checkArgument(!Files.isDirectory(filepath), "Path must be a file");

    return Files.lines(filepath).collect(Collectors.joining("\n"));
}

From source file:org.cryptomator.cli.Args.java

public String getVaultPassword(String vaultName) {
    if (vaultPasswords.getProperty(vaultName) == null) {
        Path vaultPasswordPath = Paths.get(vaultPasswordFiles.getProperty(vaultName));
        if (Files.isReadable(vaultPasswordPath) && Files.isRegularFile(vaultPasswordPath)) {
            try (Stream<String> lines = Files.lines(vaultPasswordPath)) {
                return lines.findFirst().get().toString();
            } catch (IOException e) {
                return null;
            }/*from   www.j av  a  2 s  .c o m*/
        }
        return null;
    }
    return vaultPasswords.getProperty(vaultName);
}

From source file:com.att.aro.core.settings.impl.JvmSettings.java

@SuppressFBWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE")
@Override/*  w  w  w. java  2  s .  co m*/
public String setAttribute(String name, String value) {
    if (!StringUtils.equals("Xmx", name)) {
        throw new IllegalArgumentException("Not a valid property:" + name);
    }
    if (!NumberUtils.isNumber(value)) {
        throw new IllegalArgumentException(
                value + " is not a valid value for memory; Please enter an integer value.");
    }
    validateSize(Long.valueOf(value));
    Path path = Paths.get(CONFIG_FILE_PATH);
    List<String> values = Collections.emptyList();
    if (!path.toFile().exists()) {
        createConfig(CONFIG_FILE_PATH, Collections.singletonList("-Xmx" + value + "m"));
        return value;
    } else {
        try (Stream<String> lines = Files.lines(path)) {
            values = lines.filter((line) -> !StringUtils.contains(line, name)).collect(Collectors.toList());
            values.add(0, "-Xmx" + value + "m");
            FileUtils.deleteQuietly(path.toFile());
        } catch (IOException e) {
            String message = "Counldn't read vm options file";
            LOGGER.error(message, e);
            throw new ARORuntimeException(message, e);
        }
        createConfig(CONFIG_FILE_PATH, values);
    }
    return value;
}

From source file:de.citec.sc.templates.PageRankTemplate.java

private void loadPageRanks() {

    pageRankMap = new ConcurrentHashMap<>(19500000);
    //            String path = "dbpediaFiles/pageranks.ttl";
    String path = "pagerank.csv";

    System.out.print("Loading pagerank scores to memory ...");

    try (Stream<String> stream = Files.lines(Paths.get(path))) {
        stream.parallel().forEach(item -> {

            String line = item.toString();

            String[] data = line.split("\t");
            String uri = data[1];
            Double v = Double.parseDouble(data[2]);
            if (!(uri.contains("Category:") || uri.contains("(disambiguation)"))) {

                uri = StringEscapeUtils.unescapeJava(uri);

                try {
                    uri = URLDecoder.decode(uri, "UTF-8");
                } catch (Exception e) {
                }/*from  www. ja v a2s  .  c  om*/

                pageRankMap.put(uri, v);

            }

        });

    } catch (IOException e) {
        e.printStackTrace();
    }

    System.out.println("  DONE");

    System.out.println(pageRankMap.get("Germany"));
    System.out.println(pageRankMap.get("History_of_Germany"));
    System.out.println(pageRankMap.get("German_language"));

    int z = 1;
}

From source file:com.schnobosoft.semeval.cortical.SemEvalTextSimilarity.java

/**
 * Read an input file of tab-separated texts. Ignoring empty lines.
 *
 * @param inputFile the input {@link File}
 * @return an array {@link CompareModels}, each holding two {@link Text}s which have been read from the file.
 * @throws IOException//from   ww w. jav  a2s  .  com
 */
private static CompareModels[] readInput(File inputFile) throws IOException {
    LOG.info("Reading input file " + inputFile);
    assert inputFile.getName().startsWith(INPUT_FILE_PREFIX);
    List<CompareModels> lines = Files.lines(inputFile.toPath()).filter((s) -> !s.isEmpty())
            .map(line -> line.split("\t")).map(line -> new CompareModels(new Text(line[0]), new Text(line[1])))
            .collect(Collectors.toList());
    return lines.toArray(new CompareModels[lines.size()]);
}

From source file:org.openhab.binding.onewiregpio.handler.OneWireGPIOHandler.java

private BigDecimal readSensorTemperature(String gpioFile) {
    try (Stream<String> stream = Files.lines(Paths.get(gpioFile))) {
        Optional<String> temperatureLine = stream
                .filter(s -> s.contains(OneWireGPIOBindingConstants.FILE_TEMP_MARKER)).findFirst();
        if (temperatureLine.isPresent()) {
            String line = temperatureLine.get();
            String tempString = line.substring(line.indexOf(OneWireGPIOBindingConstants.FILE_TEMP_MARKER)
                    + OneWireGPIOBindingConstants.FILE_TEMP_MARKER.length());
            Integer intTemp = Integer.parseInt(tempString);
            if (getThing().getStatus() != ThingStatus.ONLINE) {
                updateStatus(ThingStatus.ONLINE);
            }/*ww w. j  a  v a  2 s  . co m*/
            return BigDecimal.valueOf(intTemp).movePointLeft(3);
        } else {
            logger.debug(
                    "GPIO file didn't contain line with 't=' where temperature value should be available. Check if configuration points to the proper file");
            return null;
        }
    } catch (IOException | InvalidPathException e) {
        logger.debug("error reading GPIO bus file. File path is: {}.  Check if path is proper.", gpioFile, e);
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
                "Error reading GPIO bus file.");
        return null;
    }

}