Java Code Examples for java.nio.file.Files#lines()

The following examples show how to use java.nio.file.Files#lines() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: word   File: TrieTest.java    License: Apache License 2.0 6 votes vote down vote up
public static void testTrigram2() throws Exception{
    GenericTrie<Integer> genericTrie = new GenericTrie<>();
    Map<String, Integer> map = new HashMap<>();
    Stream<String> lines = Files.lines(Paths.get("src/test/resources/trigram.txt"));
    lines.forEach(line -> {
        String[] attrs = line.split("\\s+");
        if(attrs!=null && attrs.length==2){
            map.put(attrs[0], Integer.parseInt(attrs[1]));
            genericTrie.put(attrs[0], map.get(attrs[0]));
        }
    });
    map.keySet().forEach(key->assertEquals(map.get(key).intValue(), genericTrie.get(key).intValue()));
    for(int i=0; i<1000; i++){
        map.keySet().forEach(key->genericTrie.get(key));
    }
}
 
Example 2
Source Project: ocraft-s2client   File: ExecutableParser.java    License: MIT License 6 votes vote down vote up
private static Path findExecutablePath() {
    Path executeInfoPath = resolveExecuteInfoPath().filter(Files::exists).orElseThrow(required(EXECUTE_INFO));
    try (Stream<String> lines = Files.lines(executeInfoPath)) {
        return lines.findFirst()
                .map(splitToKeyValue())
                .filter(correctProperty())
                .filter(notEmptyValue())
                .map(toPropertyValue())
                .map(Paths::get)
                .filter(Files::exists)
                .orElseThrow(required("executable path"));
    } catch (IOException e) {
        log.error("Finding executable path error.", e);
        throw new StarCraft2ControllerException(
                ControllerError.INVALID_EXECUTABLE, "Finding executable path error.", e);
    }
}
 
Example 3
Source Project: training   File: TransformStreams.java    License: MIT License 6 votes vote down vote up
/**
 * - Read lines from file as Strings. 
 * - Where do you close the opened file?
 * - Parse those to OrderLine using the function bellow
 * - Validate the created OrderLine. Throw ? :S
 */
public List<OrderLine> p10_readOrderFromFile(File file) throws IOException {
	// INITIAL(
	//Stream<String> lines = null; // ??
	////return lines
	////.map(line -> line.split(";")) // Stream<String[]>
	////.filter(cell -> "LINE".equals(cell[0]))
	////.map(this::parseOrderLine) // Stream<OrderLine>
	////.peek(this::validateOrderLine)
	////.collect(toList());
	//return null;
	// INITIAL)
	// SOLUTION(
	try (Stream<String> lines = Files.lines(file.toPath())) {
		return lines.skip(2) // skip the header
			.map(line -> line.split(";"))
			.filter(cell -> "LINE".equals(cell[0]))
			.map(this::parseOrderLine)
			.peek(this::validateOrderLine) // vezi exceptia
			.collect(toList());
	}
	// SOLUTION)
}
 
Example 4
@SuppressFBWarnings(value = "DMI_HARDCODED_ABSOLUTE_FILENAME")
public void authenticate(Vault vault, VaultConfig config) throws VaultException, VaultPluginException {
    if (isTokenTTLExpired()) {
        try (Stream<String> input =  Files.lines(Paths.get(SERVICE_ACCOUNT_TOKEN_PATH)) ) {
            this.jwt = input.collect(Collectors.joining());
        } catch (IOException e) {
            throw new VaultPluginException("could not get JWT from Service Account Token", e);
        }
        // authenticate
        currentAuthToken = vault.auth()
            .loginByJwt(mountPath, kubernetes.getRole(), this.jwt)
            .getAuthClientToken();
        config.token(currentAuthToken).build();
        LOGGER.log(Level.FINE, "Login to Vault using Kubernetes successful");
        getTTLExpiryOfCurrentToken(vault);
    } else {
        // make sure current auth token is set in config
        config.token(currentAuthToken).build();
    }
}
 
Example 5
protected void executeLanguages(JarFile componentJar, Map<String, Supplier<String>> jsonFiles) throws MojoExecutionException, MojoFailureException, IOException {
    List<String> languageNames = findLanguageNames(componentJar);
    if (!languageNames.isEmpty()) {
        getLog().info("Languages found: " + String.join(", ", languageNames));
        List<String> actual = new ArrayList<>();
        for (String languageName : languageNames) {
            String json = loadLanguageJson(jsonFiles, languageName);
            if (json != null) {
                json = json.replace("\"groupId\": \"" + getMainDepGroupId() + "\"", "\"groupId\": \"" + project.getGroupId() + "\"")
                           .replace("\"artifactId\": \"" + getMainDepArtifactId() + "\"", "\"artifactId\": \"" + project.getArtifactId() + "\"")
                           .replace("\"version\": \"" + getMainDepVersion() + "\"", "\"version\": \"" + project.getVersion() + "\"");
                writeIfChanged(json, new File(catalogDir,
                        "src/main/resources/org/apache/camel/springboot/catalog/languages/" + languageName + ".json"));
                actual.add(languageName);
            }
        }
        File languages = new File(catalogDir, "src/main/resources/org/apache/camel/springboot/catalog/languages.properties");
        Stream<String> existing = languages.isFile() ? Files.lines(languages.toPath()) : Stream.empty();
        String content = Stream.concat(existing, actual.stream())
                .sorted().distinct()
                .collect(Collectors.joining("\n"));
        writeIfChanged(content, languages);
    }
}
 
Example 6
public static String getMockData(String path) throws IOException {
  try (InputStream resourceAsStream = PostgresClientIT.class.getClassLoader().getResourceAsStream(path)) {
    if (resourceAsStream != null) {
      return IOUtils.toString(resourceAsStream, StandardCharsets.UTF_8);
    } else {
      StringBuilder sb = new StringBuilder();
      try (Stream<String> lines = Files.lines(Paths.get(path))) {
        lines.forEach(sb::append);
      }
      return sb.toString();
    }
  }
}
 
Example 7
Source Project: Chronicle-Map   File: ExitHookTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testExitHook() throws IOException, InterruptedException {
    if (!OS.isLinux() && !OS.isMacOSX())
        return; // This test runs only in Unix-like OSes
    File mapFile = folder.newFile();
    File preShutdownActionExecutionConfirmationFile = folder.newFile();
    // Create a process which opens the map, acquires the lock and "hangs" for 30 seconds
    Process process = startOtherProcess(mapFile, preShutdownActionExecutionConfirmationFile, false);
    // Let the other process actually reach the moment when it locks the map
    // (JVM startup and chronicle map creation are not instant)
    Thread.sleep(JVM_STARTUP_WAIT_TIME_MS);
    // Interrupt that process to trigger Chronicle Map's shutdown hooks
    interruptProcess(getPidOfProcess(process));
    process.waitFor();
    int actual = process.exitValue();
    if (actual != 0) // clean shutdown
        assertEquals(130, actual); // 130 is exit code for SIGINT (interruption).
    ChronicleMap<Integer, Integer> map = createMapBuilder().createPersistedTo(mapFile);
    try (ExternalMapQueryContext<Integer, Integer, ?> c = map.queryContext(KEY)) {
        // Test that we are able to lock the segment, i. e. the lock was released in other
        // process, thanks to default shutdown hook.
        c.writeLock().lock();
    }
    try (Stream<String> lines = Files.lines(preShutdownActionExecutionConfirmationFile.toPath())) {
        Iterator<String> lineIterator = lines.iterator();
        assertTrue(lineIterator.hasNext());
        String line = lineIterator.next();
        assertEquals(PRE_SHUTDOWN_ACTION_EXECUTED, line);
        assertFalse(lineIterator.hasNext());
    }
}
 
Example 8
Source Project: streamline   File: EventLogFileReader.java    License: Apache License 2.0 5 votes vote down vote up
public Stream<EventInformation> loadEventLogFileAsStream(File eventLogFile) throws IOException {
    Stream<String> lines = Files.lines(eventLogFile.toPath(), ENCODING_UTF_8);
    return lines.map(line -> {
        try {
            return (EventInformation) objectMapper.readValue(line, new TypeReference<EventInformation>() {});
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    });
}
 
Example 9
private String readFromFile(String filePath) {
    StringBuilder contentBuilder = new StringBuilder();

    try (Stream<String> stream = Files.lines( Paths.get(filePath), StandardCharsets.UTF_8)) {
        stream.forEach(s -> contentBuilder.append(s).append("\n"));
    } catch (IOException e) {
        e.printStackTrace();
    }

    return contentBuilder.toString();
}
 
Example 10
Source Project: aws-doc-sdk-examples   File: InvokeTest.java    License: Apache License 2.0 5 votes vote down vote up
private static String loadJsonFile(String path)
{
    StringBuilder stringBuilder = new StringBuilder();
    try (Stream<String> stream = Files.lines( Paths.get(path), StandardCharsets.UTF_8))
    {
        stream.forEach(s -> stringBuilder.append(s));
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
    return stringBuilder.toString();
}
 
Example 11
@Override
public void readOnce() {
    // get the event date, just in case we need it
    System.out.println("TailingReader.readOnce called.");
    stopReading();
    
    if (sourceFile == null || !sourceFile.exists() || !sourceFile.canRead() || !sourceFile.isFile()) {
        statusLabel.setText("Unable to open file: " + fileName.getValueSafe());
        return;
    }
    System.out.println("  Current file is: \"" + sourceFile.getAbsolutePath() + "\"");
    // Run this in a tailingThread....
    Task task;
    task = new Task<Void>() {
        @Override public Void call() {
            try {
                reading.acquire();
                try (Stream<String> s = Files.lines(sourceFile.toPath())) {
                    s.map(line -> line.trim()).filter(line -> !line.isEmpty()).forEach(line -> {
                        //System.out.println("readOnce read " + s);
                        process(line);
                    });
                    s.close();
                } catch (Exception ex){
                    ex.printStackTrace();
                }
                
            } catch (Exception ex){
                ex.printStackTrace();
            }
            reading.release();
            return null;
        }
    };
    new Thread(task).start();
    
}
 
Example 12
Source Project: cwlexec   File: DockerCommandBuilder.java    License: Apache License 2.0 5 votes vote down vote up
private static void mapEntries(File entryFile,
        Map<String, String> inputsMapping,
        String dockerOutdir,
        StringBuilder contentBuilder) {
    Stream<String> stream = null;
    try {
        stream = Files.lines(entryFile.toPath(), StandardCharsets.UTF_8);
        stream.forEach(s -> {
            if ((s.length() != 0) && (s.indexOf('/') != -1)) {
                String srcPath = s.substring(s.indexOf('/')).trim();
                String mappedPath = inputsMapping.get(srcPath);
                if (mappedPath == null) {
                    mappedPath = Paths.get(dockerOutdir).resolve(Paths.get(srcPath).getFileName()).toString();
                }
                String mapped = s.replaceAll(srcPath, mappedPath);
                logger.debug("entry: \"{}\" mapped to \"{}\"", s, mapped);
                contentBuilder.append(mapped).append(System.getProperty(LINE_SEPARATOR));
            } else {
                logger.debug("entry: \"{}\"", s);
                contentBuilder.append(s).append(System.getProperty(LINE_SEPARATOR));
            }
        });
    } catch (IOException e) {
        logger.error("Failed to read \"{}\": {}", entryFile.getAbsoluteFile(), e.getMessage());
    } finally {
        if (stream != null) {
            stream.close();
        }
    }
}
 
Example 13
Source Project: java8-tutorial   File: Files1.java    License: MIT License 5 votes vote down vote up
private static void testLines() throws IOException {
    try (Stream<String> stream = Files.lines(Paths.get("res/nashorn1.js"))) {
        stream
                .filter(line -> line.contains("print"))
                .map(String::trim)
                .forEach(System.out::println);
    }
}
 
Example 14
Source Project: CogniCrypt   File: Helper.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private String readFileLineByLine(final String filePath) {
	final StringBuilder contentBuilder = new StringBuilder();
	try (Stream<String> stream = Files.lines(Paths.get(filePath), StandardCharsets.UTF_8)) {
		stream.forEach(s -> contentBuilder.append(s).append("\n"));
	}
	catch (final IOException e) {
		e.printStackTrace();
	}
	return contentBuilder.toString();
}
 
Example 15
Source Project: ROUGE-2.0   File: ROUGECalculator.java    License: Apache License 2.0 5 votes vote down vote up
private List<String> getSystemSents(Path system) {
	/*
	 * try { BufferedReader r=new BufferedReader(new FileReader(system));
	 * List<String> sentList=new ArrayList<>(); String line="";
	 * 
	 * while((line=r.readLine())!=null){ line=cleanSent(line);
	 * sentList.add(line); }
	 */

	// read file into stream, try-with-resources
	List<String> sentList = new ArrayList<>();
	try (Stream<String> stream = Files.lines(system, StandardCharsets.ISO_8859_1)) {

		stream.forEach(line -> {
			line = cleanSent(line);
			sentList.add(line);
		});

	} catch (IOException e) {
		logger.error("Problem reading system sentences");
	}

	return sentList;
	/*
	 * } catch (IOException e) { e.printStackTrace(); return null; }
	 */
}
 
Example 16
Source Project: besu   File: AllowlistPersistorTest.java    License: Apache License 2.0 4 votes vote down vote up
private boolean hasKey(final ALLOWLIST_TYPE key) throws IOException {
  try (Stream<String> lines = Files.lines(tempFile.toPath())) {
    return lines.anyMatch(s -> s.startsWith(key.getTomlKey()));
  }
}
 
Example 17
Source Project: protools   File: ToolPath.java    License: Apache License 2.0 4 votes vote down vote up
public static Stream<String> readStream(Path path) throws IOException {
    return Files.lines(path);
}
 
Example 18
Source Project: toolbox   File: ARFFDataFolderReader.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void loadFromFile(String path) {

    this.pathFileData=path+"/data/";
    this.pathFileHeader=path+"/attributes.txt";
    this.pathFileName = path+"/name.txt";


    try {
        this.relationName = Files.lines(Paths.get(pathFileName)).collect(Collectors.toList()).get(0).split(" ")[1];

        Stream<String> headerLines =  Files.lines(Paths.get(pathFileHeader));

        List<String> attLines = headerLines
                .filter(w -> !w.isEmpty())
                .filter(w -> !w.startsWith("%"))
                .filter(line -> line.startsWith("@attribute"))
                .collect(Collectors.toList());


        List<Attribute> atts = null;
        try {
            atts = attLines.stream()
                    .map(line -> {
                        String[] parts = line.split(" |\t");
                        int index = Integer.parseInt(parts[2]);
                        StringBuilder builder = new StringBuilder();
                        for (int i = 0; i < parts.length; i++) {
                            if (i == 2)
                                continue;
                            builder.append(parts[i]);
                            builder.append("\t");
                        }
                        return ARFFDataReader.createAttributeFromLine(index, builder.toString());
                    })
                    .collect(Collectors.toList());

        }catch (Exception e) {
            atts = IntStream.range(0, attLines.size())
                    .mapToObj(i -> ARFFDataReader.createAttributeFromLine(i, attLines.get(i)))
                    .collect(Collectors.toList());
        }

        Collections.sort(atts, (a, b) -> a.getIndex() - b.getIndex());
        attributes = new Attributes(atts);
    }catch (Exception ex){
        throw new UndeclaredThrowableException(ex);
    }
}
 
Example 19
Source Project: TencentKona-8   File: Grep.java    License: GNU General Public License v2.0 3 votes vote down vote up
/**
 * Produces a stream of lines from a file. The result is a stream in order
 * to close it later. This code is not inlined for the reason of
 * Files.lines() throwing a checked IOException that must be caught.
 *
 * @param path - the file to read
 * @return stream of lines from the file
 */
private static Stream<String> path2Lines(Path path) {
    try {
        return Files.lines(path);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 20
Source Project: jdk8u-jdk   File: Grep.java    License: GNU General Public License v2.0 3 votes vote down vote up
/**
 * Produces a stream of lines from a file. The result is a stream in order
 * to close it later. This code is not inlined for the reason of
 * Files.lines() throwing a checked IOException that must be caught.
 *
 * @param path - the file to read
 * @return stream of lines from the file
 */
private static Stream<String> path2Lines(Path path) {
    try {
        return Files.lines(path);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}