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:com.diffplug.gradle.pde.PdeInstallation.java

/** Installs the bootstrap installation. */
private void install() throws Exception {
    System.out.print("Installing pde " + release + "... ");
    P2Model.DirectorApp directorApp = p2model().directorApp(getRootFolder(), "goomph-pde-bootstrap-" + release);
    // share the install for quickness
    directorApp.bundlepool(GoomphCacheLocations.bundlePool());
    // create a native launcher
    directorApp.platform(SwtPlatform.getRunning());
    directorApp.runUsingBootstrapper();/*from  w  w  w  .ja  v  a  2 s  .  c o  m*/
    // parse out the pde.build version
    File bundleInfo = new File(getContentsEclipse(),
            "configuration/org.eclipse.equinox.simpleconfigurator/bundles.info");
    Preconditions.checkArgument(bundleInfo.isFile(), "Needed to find the pde.build folder: %s", bundleInfo);
    String pdeBuildLine = Files.readAllLines(bundleInfo.toPath()).stream()
            .filter(line -> line.startsWith("org.eclipse.pde.build,")).findFirst().get();
    String pdeBuildVersion = pdeBuildLine.split(",")[1];
    // find the plugins folder
    pdeBuildFolder = new File(GoomphCacheLocations.bundlePool(),
            "plugins/org.eclipse.pde.build_" + pdeBuildVersion);
    FileMisc.writeToken(getRootFolder(), TOKEN, pdeBuildFolder.getAbsolutePath());
    System.out.println("Success.");
}

From source file:org.matonto.etl.rest.impl.DelimitedRestImplTest.java

@Test
public void updateDelimitedReplacesContentTest() throws Exception {
    String fileName = UUID.randomUUID().toString() + ".csv";
    copyResourceToTemp("test.csv", fileName);
    List<String> expectedLines = getCsvResourceLines("test_updated.csv");

    FormDataMultiPart fd = getFileFormData("test_updated.csv");
    Response response = target().path("delimited-files/" + fileName).request()
            .put(Entity.entity(fd, MediaType.MULTIPART_FORM_DATA));
    assertEquals(response.getStatus(), 200);
    assertEquals(response.readEntity(String.class), fileName);
    List<String> resultLines = Files.readAllLines(Paths.get(DelimitedRestImpl.TEMP_DIR + "/" + fileName));
    assertEquals(resultLines.size(), expectedLines.size());
    for (int i = 0; i < resultLines.size(); i++) {
        assertEquals(resultLines.get(i), expectedLines.get(i));
    }/*from  w w w .  j  a v  a 2 s  .c  o m*/
}

From source file:com.facebook.buck.util.unarchive.UntarTest.java

/**
 * Assert that a symlink exists inside of the temp directory with given contents and that links to
 * the right file/*from   w w w . j  a  v  a 2 s .c om*/
 */
private void assertOutputSymlinkExists(Path symlinkPath, Path expectedLinkedToPath, String expectedContents)
        throws IOException {
    Path fullPath = tmpFolder.getRoot().resolve(symlinkPath);
    if (Platform.detect() != Platform.WINDOWS) {
        Assert.assertTrue(String.format("Expected %s to be a symlink", fullPath),
                Files.isSymbolicLink(fullPath));
        Path linkedToPath = Files.readSymbolicLink(fullPath);
        Assert.assertEquals(String.format("Expected symlink at %s to point to %s, not %s", symlinkPath,
                expectedLinkedToPath, linkedToPath), expectedLinkedToPath, linkedToPath);
    }

    Path realExpectedLinkedToPath = filesystem.getRootPath()
            .resolve(symlinkPath.getParent().resolve(expectedLinkedToPath).normalize());
    Assert.assertTrue(
            String.format("Expected link %s to be the same file as %s", fullPath, realExpectedLinkedToPath),
            Files.isSameFile(fullPath, realExpectedLinkedToPath));

    String contents = Joiner.on('\n').join(Files.readAllLines(fullPath));
    Assert.assertEquals(expectedContents, contents);
}

From source file:org.apdplat.superword.tools.WordClassifierForYouDao.java

public static synchronized void save(Map<String, List<String>> data) {
    LOGGER.info("??");
    data.keySet().forEach(key -> {/*from w w w .j av a2 s.c  o  m*/
        try {
            String path = "src/main/resources/word_" + key + ".txt";
            LOGGER.info("??" + path);
            List<String> existWords = Files.readAllLines(Paths.get(path));
            Set<String> allWords = new HashSet<>();
            existWords.forEach(line -> {
                String[] attr = line.split("\\s+");
                if (attr != null) {
                    String w = "";
                    if (attr.length == 1) {
                        w = attr[0];
                    }
                    if (attr.length == 2) {
                        w = attr[1];
                    }
                    allWords.add(w);
                }
            });
            if (data.get(key) != null) {
                allWords.addAll(data.get(key));
            }
            AtomicInteger i = new AtomicInteger();
            List<String> list = allWords.stream().sorted().map(word -> i.incrementAndGet() + "\t" + word)
                    .collect(Collectors.toList());
            Files.write(Paths.get(path), list);
            if (data.get(key) != null) {
                data.get(key).clear();
            }
            existWords.clear();
            allWords.clear();
            list.clear();
        } catch (Exception e) {
            LOGGER.error("??", e);
        }
    });
    data.clear();
    try {
        if (!NOT_FOUND_WORDS.isEmpty()) {
            String path = "src/main/resources/word_not_found.txt";
            LOGGER.info("??" + path);
            AtomicInteger i = new AtomicInteger();
            //NOT_FOUND_WORDS
            List<String> list = NOT_FOUND_WORDS.stream().sorted().map(word -> i.incrementAndGet() + "\t" + word)
                    .collect(Collectors.toList());
            Files.write(Paths.get(path), list);
            list.clear();
        }
        //?HTML
        if (!ORIGIN_HTML.isEmpty()) {
            String path = "src/main/resources/origin_html_" + System.currentTimeMillis() + ".txt";
            LOGGER.info("??" + path);
            Files.write(Paths.get(path), ORIGIN_HTML);
            ORIGIN_HTML.clear();
        }
    } catch (Exception e) {
        LOGGER.error("??", e);
    }
}

From source file:com.evolveum.midpoint.model.intest.manual.CsvBackingStore.java

protected String dumpCsv() throws IOException {
    return StringUtils.join(Files.readAllLines(Paths.get(CSV_TARGET_FILE.getPath())), "\n");
}

From source file:rgu.jclos.foldbuilder.FoldBuilder.java

/**
 * Generates K folds and writes them to disk
 * @param inputFile The CSV file from which the data comes from.
 * @param outputDirectory The directory in which the folds will be written.
 * @param separator The separating character in the CSV file.
 * @param indexLabel The index of the labels in the CSV file. Used for stratification of the folds.
 * @param k The number of folds to generates.
 * @param speak Whether to print some status messages along the way.
 * @return A pair containing a list of folds with ids of documents, and a dictionary that allows the user to retrieve aformentioned documents using the ids, in order to save space.
 * @throws IOException If something stops the program from reading or writing the files.
 *//*from   ww w . j  a  v  a 2  s . c  o  m*/
public static Pair<List<Set<String>>, Map<String, Instance>> getFolds(String inputFile, String outputDirectory,
        String separator, int indexLabel, int k, boolean speak) throws IOException {
    Random rng = new Random();
    Map<String, Instance> dictionary = new HashMap<>();
    Map<String, Integer> classes = new HashMap<>();
    Map<String, List<String>> reversedDictionary = new HashMap<>();
    int id = 0;
    for (String line : Files.readAllLines(new File(inputFile).toPath())) {
        Instance inst = new Instance();
        String[] elements = line.split(separator);
        inst.content = line;
        inst.label = elements[indexLabel];
        String iid = "inst" + id;
        dictionary.put(iid, inst);
        classes.put(inst.label, classes.getOrDefault(inst.label, 0) + 1);
        if (reversedDictionary.containsKey(inst.label)) {
            reversedDictionary.get(inst.label).add(iid);
        } else {
            List<String> ids = new ArrayList<>();
            ids.add(iid);
            reversedDictionary.put(inst.label, ids);
        }
        id++;
    }

    int numberOfInstances = id;
    int sizeOfEachFold = (int) Math.floor(numberOfInstances / k);
    Map<String, Double> classRatios = new HashMap<>();
    for (Map.Entry<String, Integer> classFrequency : classes.entrySet()) {
        classRatios.put(classFrequency.getKey(),
                (double) classFrequency.getValue() / (double) numberOfInstances);
    }

    List<Set<String>> folds = new ArrayList<>();
    for (int i = 0; i < k; i++) {
        Set<String> fold = new HashSet<>();
        for (Map.Entry<String, List<String>> c : reversedDictionary.entrySet()) {
            int currentSize = fold.size();
            int numberRequired = (int) Math.floor(classRatios.get(c.getKey()) * sizeOfEachFold);
            while (fold.size() < currentSize + numberRequired && c.getValue().size() > 0) {
                int nextPick = rng.nextInt(c.getValue().size());
                fold.add(c.getValue().get(nextPick));
                c.getValue().remove(nextPick);
            }
        }
        folds.add(fold);
        if (speak)
            System.out.println("Finished computing fold " + (i + 1) + " of size " + fold.size());
    }

    if (speak)
        System.out.println("Writing folds on disk");

    return Pair.of(folds, dictionary);
}

From source file:edu.usu.sdl.openstorefront.usecase.AttributeImport.java

private AttributeTypeView loadJCFSLArch() {
    AttributeTypeView attributeTypeView = new AttributeTypeView();
    Set<String> codeSet = new HashSet();

    CSVParser parser = new CSVParser();
    Path path = Paths.get(FileSystemManager.getDir(FileSystemManager.IMPORT_DIR) + "/jcfsl.csv");
    try {/*from  ww  w .  j  a v  a2  s. c  o m*/
        List<String> lines = Files.readAllLines(path);
        //read type
        try {
            String data[] = parser.parseLine(lines.get(1));

            attributeTypeView.setAttributeType(data[0].trim());
            attributeTypeView.setDescription(data[1].trim());
            attributeTypeView.setArchitectureFlg(Convert.toBoolean(data[2].trim()));
            attributeTypeView.setVisibleFlg(Convert.toBoolean(data[3].trim()));
            attributeTypeView.setImportantFlg(Convert.toBoolean(data[4].trim()));
            attributeTypeView.setRequiredFlg(Convert.toBoolean(data[5].trim()));
            attributeTypeView.setAllowMultipleFlg(Convert.toBoolean(data[6].trim()));

            for (int i = 2; i < lines.size(); i++) {
                if (StringUtils.isNotBlank(lines.get(i))) {
                    data = parser.parseLine(lines.get(i));
                    AttributeCodeView attributeCodeView = new AttributeCodeView();
                    String code[] = data[0].split(" ");

                    if (code.length > 0) {
                        String codeKey = code[0].toUpperCase().trim();
                        if (codeSet.contains(codeKey) == false) {
                            if (StringUtils.isNotBlank(codeKey)) {
                                attributeCodeView.setCode(codeKey);
                                attributeCodeView.setLabel(data[0].trim());
                                attributeTypeView.getCodes().add(attributeCodeView);
                                codeSet.add(codeKey);
                            }
                        }
                    }
                }
            }

        } catch (IOException ex) {
            log.log(Level.SEVERE, null, ex);
        }

    } catch (IOException ex) {

        log.log(Level.SEVERE, null, ex);
    }

    return attributeTypeView;
}

From source file:com.wx3.galacdecks.Bootstrap.java

private void importRules(GameDatastore datastore, String path) throws IOException {
    Files.walk(Paths.get(path)).forEach(filePath -> {
        if (Files.isRegularFile(filePath)) {
            try {
                if (FilenameUtils.getExtension(filePath.getFileName().toString()).toLowerCase().equals("js")) {
                    String id = FilenameUtils.removeExtension(filePath.getFileName().toString());
                    List<String> lines = Files.readAllLines(filePath);
                    if (lines.size() < 3) {
                        throw new RuntimeException(
                                "Script file should have at least 3 lines: description, trigger, and code.");
                    }//from ww  w.  jav  a 2 s .co  m
                    String description = lines.get(0).substring(2).trim();

                    String trigger = lines.get(1).substring(11).trim();
                    // Check that this actually is a valid trigger event:
                    try {
                        if (!trigger.equals(GameRules.BUFF_PHASE)) {
                            Class.forName(eventPackage + "." + trigger);
                        }

                    } catch (ClassNotFoundException e) {
                        throw new RuntimeException("No such GameEvent: " + trigger);
                    }
                    String script = String.join("\n", lines);
                    EntityRule rule = EntityRule.createRule(trigger, script, id, description);
                    datastore.createRule(rule);
                    ruleCache.put(id, rule);
                    logger.info("Imported rule " + id);
                }
            } catch (Exception e) {
                throw new RuntimeException("Failed to parse " + filePath + ": " + e.getMessage());
            }
        }
    });
}

From source file:fi.johannes.kata.ocr.utils.files.CFileOperations.java

/**
 * 1.8 readAllLines//  w ww . java 2 s .c  o  m
 *
 * @param path
 * @return
 * @throws IOException
 */
public static List<String> readLines(String path) throws IOException {
    return Files.readAllLines(Paths.get(path));
}

From source file:fi.johannes.kata.ocr.utils.files.CFileOperations.java

/**
 * 1.8 readAllLines/*from   ww w. j  a  v  a 2s  . co m*/
 *
 * @param path
 * @return
 * @throws IOException
 */
public static List<String> readLines(Path path) throws IOException {
    return Files.readAllLines(path);
}