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) throws IOException 

Source Link

Document

Read all lines from a file.

Usage

From source file:it.polimi.diceH2020.SPACE4CloudWS.ml.MLPredictor.java

private String readJsonFile(String file) throws IOException {
    InputStream inputStream = getClass().getResourceAsStream(file);
    if (inputStream != null) {
        return IOUtils.toString(inputStream, StandardCharsets.UTF_8.name());
    }/*  ww w .j ava2 s . c  o m*/
    inputStream = getClass().getResourceAsStream("/" + file);
    if (inputStream != null) {
        return IOUtils.toString(inputStream, StandardCharsets.UTF_8.name());
    }
    return String.join("\n", Files.readAllLines(Paths.get(file)));
}

From source file:com.rptools.io.TableFileParser.java

/**
 * Parse file found at path {@param file} into an RPTable object. See {@link
 * RPTable} for expected table file format.
 *
 * Json files are read directly as a proto3 RPTable message. Text files must
 * be parsed, have their json equivalent written, then deleted. This is to
 * ease adding future tables by pasting their text content instead of trying
 * to convert them to json by hand./*from w ww . ja  v  a2  s .  c  o m*/
 *
 * @param file Input table text/json file.
 * @return {@link RPTable.Builder} created from contents of input file.
 */
public RPTable.Builder parseFile(Path file) {
    roll = 1;
    try {
        List<String> lines = Files.readAllLines(file);
        RPTable.Builder builder = RPTable.newBuilder();
        // We want to keep json files around, and convert text files to json, then delete them.
        if (file.getFileName().toString().endsWith(EXT_JSON)) {
            JsonFormat.parser().merge(JOINER.join(lines), builder);
            return builder;
        }
        setTableName(file, builder);

        String headerRow = lines.remove(0);
        List<String> headers = SPLITTER.splitToList(headerRow);
        builder.addAllColumns(headers);

        lines.forEach(line -> parseLine(builder, headers, line));
        // only return a table for .txt files if the json file did not also
        // already exist to be read separately
        if (updateResourceFiles(file, builder)) {
            return builder;
        }
        log.debug("Not renewing json/text file");
        return null;
    } catch (IOException e) {
        log.error(String.format(PARSE_ERROR, file.toString(), e.toString()), e);
        return null;
    }
}

From source file:org.springframework.cloud.stream.app.plugin.utils.SpringCloudStreamPluginUtils.java

public static void addExtraTestConfig(String generatedAppHome, String clazzInfo) throws IOException {
    Collection<File> files = FileUtils.listFiles(new File(generatedAppHome, "src/test/java"), null, true);
    Optional<File> first = files.stream().filter(f -> f.getName().endsWith("ApplicationTests.java"))
            .findFirst();/*from w  ww.jav  a  2s. co  m*/

    if (first.isPresent()) {
        StringBuilder sb = new StringBuilder();
        File f1 = first.get();
        Files.readAllLines(f1.toPath()).forEach(l -> {
            if (l.startsWith("@SpringApplicationConfiguration")) {
                sb.append("@SpringApplicationConfiguration(").append(clazzInfo).append(")");
            } else {
                sb.append(l);
            }
            sb.append("\n");
        });
        Files.write(f1.toPath(), sb.toString().getBytes());
    }
}

From source file:bit.changepurse.wdk.util.CheckedExceptionMethods.java

public static List<String> readAllLines(Path path) {
    try {//from  ww w.j av  a 2s.c  om
        return Files.readAllLines(path);
    } catch (IOException e) {
        throw new UncheckedException(e);
    }
}

From source file:org.typetalk.data.Suggestions.java

private void readSuggestions() {
    try {//from ww w. j  a  v  a 2s.  c  o  m
        suggestions = Files.readAllLines(suggestionsFile);
    } catch (IOException e) {
        log.error("Unable to read suggestions file", e);
    }
}

From source file:org.wurtele.ifttt.watchers.WorkTimesWatcher.java

private void processFile(Path input) {
    logger.info("Updating " + output);

    try (Workbook wb = new XSSFWorkbook();
            OutputStream out = Files.newOutputStream(output, StandardOpenOption.CREATE,
                    StandardOpenOption.TRUNCATE_EXISTING)) {
        Sheet sheet = wb.createSheet("Time Sheet");
        List<WorkDay> days = new ArrayList<>();
        DateFormat df = new SimpleDateFormat("MMMM dd, yyyy 'at' hh:mma");
        for (String line : Files.readAllLines(input)) {
            String[] data = line.split(";");
            LocationType type = LocationType.valueOf(data[0].toUpperCase());
            Date time = df.parse(data[1]);
            Date day = DateUtils.truncate(time, Calendar.DATE);
            WorkDay wd = new WorkDay(day);
            if (days.contains(wd))
                wd = days.get(days.indexOf(wd));
            else//from   ww w  . j  a  v  a2s.c o m
                days.add(wd);
            wd.getTimes().add(new WorkTime(time, type));
        }

        CreationHelper helper = wb.getCreationHelper();
        Font bold = wb.createFont();
        bold.setBoldweight(Font.BOLDWEIGHT_BOLD);

        CellStyle dateStyle = wb.createCellStyle();
        dateStyle.setDataFormat(helper.createDataFormat().getFormat("MMMM d, yyyy"));
        CellStyle timeStyle = wb.createCellStyle();
        timeStyle.setDataFormat(helper.createDataFormat().getFormat("h:mm AM/PM"));
        CellStyle headerStyle = wb.createCellStyle();
        headerStyle.setAlignment(CellStyle.ALIGN_CENTER);
        headerStyle.setFont(bold);
        CellStyle totalStyle = wb.createCellStyle();
        totalStyle.setAlignment(CellStyle.ALIGN_RIGHT);

        Row header = sheet.createRow(0);
        header.createCell(0).setCellValue("DATE");
        header.getCell(0).setCellStyle(headerStyle);

        Collections.sort(days);
        for (int r = 0; r < days.size(); r++) {
            WorkDay day = days.get(r);
            Row row = sheet.createRow(r + 1);
            row.createCell(0).setCellValue(day.getDate());
            row.getCell(0).setCellStyle(dateStyle);
            Collections.sort(day.getTimes());
            for (int c = 0; c < day.getTimes().size(); c++) {
                WorkTime time = day.getTimes().get(c);
                if (sheet.getRow(0).getCell(c + 1) != null
                        && !sheet.getRow(0).getCell(c + 1).getStringCellValue().equals(time.getType().name())) {
                    throw new Exception("Invalid data");
                } else if (sheet.getRow(0).getCell(c + 1) == null) {
                    sheet.getRow(0).createCell(c + 1).setCellValue(time.getType().name());
                    sheet.getRow(0).getCell(c + 1).setCellStyle(headerStyle);
                }
                row.createCell(c + 1).setCellValue(time.getTime());
                row.getCell(c + 1).setCellStyle(timeStyle);
            }
        }

        int totalCol = header.getLastCellNum();
        header.createCell(totalCol).setCellValue("TOTAL");
        header.getCell(totalCol).setCellStyle(headerStyle);

        for (int r = 0; r < days.size(); r++) {
            sheet.getRow(r + 1).createCell(totalCol).setCellValue(days.get(r).getTotal());
            sheet.getRow(r + 1).getCell(totalCol).setCellStyle(totalStyle);
        }

        for (int c = 0; c <= totalCol; c++) {
            sheet.autoSizeColumn(c);
        }

        wb.write(out);
    } catch (Exception e) {
        logger.error("Failed to update " + output, e);
    }
}

From source file:org.elasticsearch.xpack.security.authc.esnative.tool.SetupPasswordToolIT.java

@SuppressWarnings("unchecked")
public void testSetupPasswordToolAutoSetup() throws Exception {
    final String testConfigDir = System.getProperty("tests.config.dir");
    logger.info("--> CONF: {}", testConfigDir);
    final Path configPath = PathUtils.get(testConfigDir);
    setSystemPropsForTool(configPath);//from  w  w w .j a  v a 2 s .co  m

    Response nodesResponse = client().performRequest("GET", "/_nodes/http");
    Map<String, Object> nodesMap = entityAsMap(nodesResponse);

    Map<String, Object> nodes = (Map<String, Object>) nodesMap.get("nodes");
    Map<String, Object> firstNode = (Map<String, Object>) nodes.entrySet().iterator().next().getValue();
    Map<String, Object> firstNodeHttp = (Map<String, Object>) firstNode.get("http");
    String nodePublishAddress = (String) firstNodeHttp.get("publish_address");
    final int lastColonIndex = nodePublishAddress.lastIndexOf(':');
    InetAddress actualPublishAddress = InetAddresses.forString(nodePublishAddress.substring(0, lastColonIndex));
    InetAddress expectedPublishAddress = new NetworkService(Collections.emptyList())
            .resolvePublishHostAddresses(Strings.EMPTY_ARRAY);
    final int port = Integer.valueOf(nodePublishAddress.substring(lastColonIndex + 1));

    List<String> lines = Files.readAllLines(configPath.resolve("elasticsearch.yml"));
    lines = lines.stream()
            .filter(s -> s.startsWith("http.port") == false && s.startsWith("http.publish_port") == false)
            .collect(Collectors.toList());
    lines.add(randomFrom("http.port", "http.publish_port") + ": " + port);
    if (expectedPublishAddress.equals(actualPublishAddress) == false) {
        lines.add("http.publish_address: " + InetAddresses.toAddrString(actualPublishAddress));
    }
    Files.write(configPath.resolve("elasticsearch.yml"), lines, StandardCharsets.UTF_8,
            StandardOpenOption.TRUNCATE_EXISTING);

    MockTerminal mockTerminal = new MockTerminal();
    SetupPasswordTool tool = new SetupPasswordTool();
    final int status;
    if (randomBoolean()) {
        mockTerminal.addTextInput("y"); // answer yes to continue prompt
        status = tool.main(new String[] { "auto" }, mockTerminal);
    } else {
        status = tool.main(new String[] { "auto", "--batch" }, mockTerminal);
    }
    assertEquals(0, status);
    String output = mockTerminal.getOutput();
    logger.info("CLI TOOL OUTPUT:\n{}", output);
    String[] outputLines = output.split("\\n");
    Map<String, String> userPasswordMap = new HashMap<>();
    Arrays.asList(outputLines).forEach(line -> {
        if (line.startsWith("PASSWORD ")) {
            String[] pieces = line.split(" ");
            String user = pieces[1];
            String password = pieces[pieces.length - 1];
            logger.info("user [{}] password [{}]", user, password);
            userPasswordMap.put(user, password);
        }
    });

    assertEquals(4, userPasswordMap.size());
    userPasswordMap.entrySet().forEach(entry -> {
        final String basicHeader = "Basic " + Base64.getEncoder()
                .encodeToString((entry.getKey() + ":" + entry.getValue()).getBytes(StandardCharsets.UTF_8));
        try {
            Response authenticateResponse = client().performRequest("GET", "/_xpack/security/_authenticate",
                    new BasicHeader("Authorization", basicHeader));
            assertEquals(200, authenticateResponse.getStatusLine().getStatusCode());
            Map<String, Object> userInfoMap = entityAsMap(authenticateResponse);
            assertEquals(entry.getKey(), userInfoMap.get("username"));
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    });
}

From source file:ai.susi.mind.SusiAwareness.java

/**
 * produce awareness by reading a memory dump up to a given attention time
 * @param memorydump file where the memory is stored
 * @param attentionTime the maximum number of cognitions within the required awareness
 * @return awareness for the give time// ww  w . j  a  v  a2  s  . c  o m
 * @throws IOException
 */
public static SusiAwareness readMemory(final File memorydump, int attentionTime) throws IOException {
    List<String> lines = Files.readAllLines(memorydump.toPath());
    SusiAwareness awareness = new SusiAwareness();
    for (int i = lines.size() - 1; i >= 0; i--) {
        String line = lines.get(i);
        if (line.length() == 0)
            continue;
        SusiCognition si = new SusiCognition(new JSONObject(line));
        awareness.aware.add(si);
        if (attentionTime != Integer.MAX_VALUE && awareness.getTime() >= attentionTime)
            break;
    }
    return awareness;
}

From source file:com.simiacryptus.util.lang.CodeUtil.java

/**
 * Gets heapCopy text.//from  www  . j  a  v a 2  s .c o  m
 *
 * @param callingFrame the calling frame
 * @return the heapCopy text
 * @throws IOException the io exception
 */
public static String getInnerText(@javax.annotation.Nonnull final StackTraceElement callingFrame)
        throws IOException {
    try {
        @javax.annotation.Nonnull
        final File file = com.simiacryptus.util.lang.CodeUtil.findFile(callingFrame);
        assert null != file;
        final int start = callingFrame.getLineNumber() - 1;
        final List<String> allLines = Files.readAllLines(file.toPath());
        final String txt = allLines.get(start);
        @javax.annotation.Nonnull
        final String indent = com.simiacryptus.util.lang.CodeUtil.getIndent(txt);
        @javax.annotation.Nonnull
        final ArrayList<String> lines = new ArrayList<>();
        for (int i = start + 1; i < allLines.size()
                && (com.simiacryptus.util.lang.CodeUtil.getIndent(allLines.get(i)).length() > indent.length()
                        || allLines.get(i).trim().isEmpty()); i++) {
            final String line = allLines.get(i);
            lines.add(line.substring(Math.min(indent.length(), line.length())));
        }
        return lines.stream().collect(Collectors.joining("\n"));
    } catch (@javax.annotation.Nonnull final Throwable e) {
        return "";
    }
}

From source file:io.apiman.common.es.util.ApimanEmbeddedElastic.java

private void deleteProcessId() throws IOException {
    if (Files.exists(pidPath)) {
        List<String> pidLines = Files.readAllLines(pidPath).stream()
                .filter(storedPid -> !storedPid.equalsIgnoreCase(String.valueOf(pid))) // Compare PID (long) with PID from file (String)
                .collect(Collectors.toList());
        // Write back with successfully terminated PID removed.
        Files.write(pidPath, pidLines, Charset.defaultCharset(), StandardOpenOption.CREATE,
                StandardOpenOption.TRUNCATE_EXISTING);
    } else {//from w  w  w  .j  a v a2s .c om
        System.err.println("No pid file. Did someone delete it while the program was running?");
    }
}