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

The following are Jave code examples for showing how to use lines() of the java.nio.file.Files class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: r8   File: PrintUsageTest.java   Source Code and License Vote up 10 votes
PrintUsageInspector(Path printUsageFile) throws IOException {
  printedUsage = new HashMap<>();
  try (Stream<String> lines = Files.lines(printUsageFile)) {
    lines.forEach(line -> {
      if (line.startsWith("    ")) {
        if (line.contains("(") && line.contains(")")) {
          readMethod(line);
        } else {
          readField(line);
        }
      } else {
        readClazz(line);
      }
    });
  }
}
 
Example 2
Project: PointCloudCrust   File: PointCloudCrustImplTest.java   Source Code and License Vote up 6 votes
/**
 * Helper method for creating a large amount of points.
 *
 * @return Large amount of points.
 */
private List<Vector> generatePointCloud() throws URISyntaxException {
    List<Vector> pointCloud = new ArrayList<Vector>(2000);

    try (Stream<String> stream = Files.lines(Paths.get(
            PointCloudCrustImplTest.class.getResource(RES_POINTS).toURI()
    ))) {

        stream.forEach(it -> {
            String[] s = it.split("\\s+");
            pointCloud.add(new Vector(
                    Float.valueOf(s[8]),
                    Float.valueOf(s[9]),
                    Float.valueOf(s[10]),
                    s[0]
            ));

        });

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

    return pointCloud;
}
 
Example 3
Project: mapr-music   File: ArtistParser.java   Source Code and License Vote up 6 votes
private List<Artist> parseArtistLinks(List<Artist> artists) {
    Map<String, List<Artist>> artistMap = artists.stream()
            .filter(album -> !StringUtils.isEmpty(album.getPk()))
            .collect(Collectors.groupingBy(Artist::getPk));

    //read file into stream, try-with-resources
    try (Stream<String> stream = Files.lines(Paths.get(artistUrlsPath))) {
        stream.map(strRow -> strRow.split(TAB_SYMBOL))
                .forEach(row -> {
                    List<Artist> artistList = artistMap.get(row[2]);
                    if (artistList != null) {
                        artistList.forEach(artist -> artist.getLinks().add(new ArtistUrlLink(row[1], row[3])));
                    }
                });
    } catch (IOException e) {
        e.printStackTrace();
    }

    return artists;
}
 
Example 4
Project: moduletools   File: JITTraceReader.java   Source Code and License Vote up 6 votes
public static void main(String[] args) throws IOException {
  Path input = Paths.get(args[0]);
  Path output = Paths.get(args[1]);
  Map<String, Set<String>> indexMap = indexMap();
  try(Stream<String> lines = Files.lines(input)) {
    Stream<String> stream = lines
        .flatMap(tokens -> findClassAndMethodName(tokens).stream())
        .flatMap(name -> {
          Set<String> sigs = indexMap.get(name);
          //System.out.println("sigs " + sigs + " name " + name); 
          return (sigs == null)? Stream.of(name): sigs.stream();
        })
        .map(methodName -> "compileOnly " + methodName);
    Files.write(output, (Iterable<String>)stream.sorted().distinct()::iterator);
  }
}
 
Example 5
Project: hype   File: ManifestUtil.java   Source Code and License Vote up 5 votes
static RunManifest read(Path manifestPath) throws IOException {
  final Stream<String> lines = Files.lines(manifestPath);

  final RunManifestBuilder builder = new RunManifestBuilder();
  lines.forEachOrdered(line -> {
    if (line.trim().isEmpty()) {
      return;
    }

    final String[] split = line.trim().split(" ", 2);
    if (split.length != 2) {
      throw new IllegalArgumentException("Malformed manifest line '" + line + "'");
    }

    switch (split[0].charAt(0)) {
      case LAMBDA:
        builder.continuation(split[1]);
        break;

      case CLASSPATH_FILE:
        builder.addClassPathFile(split[1]);
        break;

      case REGULAR_FILE:
        builder.addFile(split[1]);
        break;

      default:
        LOG.warn("Unrecognized manifest entry '" + line + "'");
    }
  });

  return builder.build();
}
 
Example 6
Project: DeepMachineLearning   File: NetCaseConfiguration.java   Source Code and License Vote up 5 votes
private void loadTextFile(String filename, Consumer<String> processor) {
	try (Stream<String> stream = Files.lines(Paths.get(filename))) {
		stream.filter(line -> {return !line.startsWith("#") && 
				                      !line.trim().equals("");})
			  .forEach(processor);
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 7
Project: openjdk-jdk10   File: GenerateJLIClassesPlugin.java   Source Code and License Vote up 5 votes
private Stream<String> fileLines(File file) {
    try {
        return Files.lines(file.toPath());
    } catch (IOException io) {
        throw new PluginException("Couldn't read file");
    }
}
 
Example 8
Project: worldheatmap   File: Main.java   Source Code and License Vote up 5 votes
private List<Point2D> readCitiesFromFile() throws IOException {
    List<Point2D>  cities     = new ArrayList<>(8092);
    String         citiesFile = (Main.class.getResource("cities.txt").toExternalForm()).replace("file:", "");
    Stream<String> lines      = Files.lines(Paths.get(citiesFile));
    lines.forEach(line -> {
        String city[] = line.split(",");
        double[] xy = World.latLonToXY(Double.parseDouble(city[1]), Double.parseDouble(city[2]));
        cities.add(new Point2D(xy[0], xy[1]));
    });
    lines.close();
    return cities;
}
 
Example 9
Project: jdk8u-jdk   File: StreamTest.java   Source Code and License Vote up 5 votes
public void testConstructException() {
    try (Stream<String> s = Files.lines(testFolder.resolve("notExist"), Charset.forName("UTF-8"))) {
        s.forEach(l -> fail("File is not even exist!"));
    } catch (IOException ioe) {
        assertTrue(ioe instanceof NoSuchFileException);
    }
}
 
Example 10
Project: yuvi   File: VarBitMetricStoreBenchmark.java   Source Code and License Vote up 5 votes
public void load() throws IOException {
  // Get metric name and put it in a map and assign it a number.
  // Add ts and value to metric store with that number.
  try (Stream<String> lines = Files.lines(filePath, Charset.defaultCharset())) {
    lines.forEachOrdered(line -> {
      if (line == null || line.isEmpty()) { // Ignore empty lines
        return;
      }
      try {
        String[] metricParts = line.split(" ");
        if (metricParts.length > 1 && metricParts[0].equals("put")) {
          String metricName = metricParts[1].trim();
          List<String> rawTags = Arrays.asList(metricParts).subList(4, metricParts.length);
          Metric metric = new Metric(metricName, rawTags);
          long ts = Long.parseLong(metricParts[2].trim());
          double value = Double.parseDouble(metricParts[3].trim());

          // System.out.println(metric.fullMetricName);

          int id = -1;
          if (metricidHashMap.containsKey(metric.fullMetricName)) {
            id = metricidHashMap.get(metric.fullMetricName);
          } else {
            metricCounter[0] = metricCounter[0] + 1;
            metricidHashMap.put(metric.fullMetricName, metricCounter[0]);
            id = metricCounter[0];
          }

          store.addPoint(id, ts, value);
        }
      } catch (Exception e) {
        // System.out.println("Error ingesting line " + line + " with exception " + e.getMessage());
      }
    });
  }
  metricidHashMap.clear();
  // System.out.println("Metric counter size: " + metricCounter[0]);
}
 
Example 11
Project: openjdk-jdk10   File: ToolBasicTest.java   Source Code and License Vote up 5 votes
public void elideStartUpFromSave() throws IOException {
    Compiler compiler = new Compiler();
    Path path = compiler.getPath("myfile");
    test(
            (a) -> assertCommandOutputContains(a, "123", "==> 123"),
            (a) -> assertCommand(a, "/save " + path.toString(), "")
    );
    try (Stream<String> lines = Files.lines(path)) {
        assertEquals(lines.count(), 1, "Expected only one saved line");
    }
}
 
Example 12
Project: What-Happened-to-Station-7   File: Entity.java   Source Code and License Vote up 5 votes
/**
 * Chooses a random name for the entity from a file.
 * 
 * @param names The file containing the potential name choices
 * @param numOfNames The number of names in the file
 */
public void setName(File names, int numOfNames)
{
	Stream<String> lines = null;
	try
	{
		lines = Files.lines(names.toPath());
	}
	catch (IOException e)
	{
		e.printStackTrace();
	}
	name = lines.skip((int) (Math.random() * numOfNames)).findFirst().get();
}
 
Example 13
Project: email-service   File: SenderService.java   Source Code and License Vote up 5 votes
private Stream<String> load(String filename) {
    try {
        return Files.lines(Paths.get(
            new PathMatchingResourcePatternResolver()
                .getResource(filename)
                .getURI()
        ));
    } catch (final IOException ex) {
        throw new RuntimeException("Could not find required file '" +
                                       filename + "' on classpath.");
    }
}
 
Example 14
Project: mapr-music   File: ArtistParser.java   Source Code and License Vote up 5 votes
private List<Artist> parseUrls(List<Artist> artists) {


        Map<String, List<Artist>> urlArtistMap = new HashMap<>();
        artists.stream()
                .filter(artist -> !artist.getLinks().isEmpty())
                .forEach(artist -> {
                    artist.getLinks().forEach(artistUrlLink -> {
                        if (!urlArtistMap.containsKey(artistUrlLink.getUrlId())) {
                            urlArtistMap.put(artistUrlLink.getUrlId(), new ArrayList<>());
                        }
                        urlArtistMap.get(artistUrlLink.getUrlId()).add(artist);
                    });
                });

        //read file into stream, try-with-resources
        try (Stream<String> stream = Files.lines(Paths.get(urlsPath))) {
            stream.map(strRow -> strRow.split(TAB_SYMBOL))
                    .forEach(row -> {
                        List<Artist> artistsWithSuchUrlList = urlArtistMap.get(row[0]);
                        if (artistsWithSuchUrlList != null) {

                            String pictureUrl = (row[2].contains("commons.wikimedia")) ? getActualWikiImageURL(row[2]) : row[2];

                            artistsWithSuchUrlList.forEach(artist -> {

                                if (artist.getProfileImageUrl() == null || artist.getProfileImageUrl().isEmpty()) {
                                    artist.setProfileImageUrl(pictureUrl);
                                } else {
                                    artist.addImageUrl(pictureUrl);
                                }
                            });
                        }
                    });
        } catch (IOException e) {
            e.printStackTrace();
        }

        return artists;
    }
 
Example 15
Project: mpd-2017-i41d   File: App.java   Source Code and License Vote up 5 votes
public static void main(String[] args) throws URISyntaxException, IOException {
    Path p = Paths.get(ClassLoader.getSystemResource(SRC).toURI());
    Stream<String> lines = Files.lines(p);
    int[] temperatures = parseTemperature(lines).toArray();
    // out.println(streamMax(lines));
    out.println(intStreamMax(stream(temperatures)));
    for (int i = 0; i < 10; i++) {
        // out.println(streamAverage1(stream(temperatures)));
        out.println(streamAverage2(stream(temperatures)));
        // out.println(streamAverage3(stream(temperatures)));
    }
}
 
Example 16
Project: openjdk-jdk10   File: ElementStructureTest.java   Source Code and License Vote up 5 votes
Predicate<String> constructAcceptIgnoreList(String fromFiles) throws IOException {
    StringBuilder acceptPattern = new StringBuilder();
    StringBuilder rejectPattern = new StringBuilder();
    for (String file : fromFiles.split(File.pathSeparator)) {
        try (Stream<String> lines = Files.lines(Paths.get(file))) {
            lines.forEach(line -> {
                if (line.isEmpty())
                    return;
                StringBuilder targetPattern;
                switch (line.charAt(0)) {
                    case '+':
                        targetPattern = acceptPattern;
                        break;
                    case '-':
                        targetPattern = rejectPattern;
                        break;
                    default:
                        return ;
                }
                line = line.substring(1);
                if (line.endsWith("/")) {
                    line += "[^/]*";
                } else {
                    line += "|" + line + "$[^/]*";
                }
                line = line.replace("/", ".");
                if (targetPattern.length() != 0)
                    targetPattern.append("|");
                targetPattern.append(line);
            });
        }
    }
    Pattern accept = Pattern.compile(acceptPattern.toString());
    Pattern reject = Pattern.compile(rejectPattern.toString());

    return clazzName -> accept.matcher(clazzName).matches() && !reject.matcher(clazzName).matches();
}
 
Example 17
Project: openjdk-jdk10   File: StreamLinesTest.java   Source Code and License Vote up 5 votes
@Test(dataProvider = "lines")
public void test(String description,
                 IntFunction<String> lineGenerator, IntFunction<LineSeparator> separatorGenerator,
                 int lines, Charset cs) throws IOException {
    Path p = generateTempFileWithLines(lineGenerator, separatorGenerator, lines, cs, false);

    Supplier<Stream<String>> ss = () -> {
        try {
            return Files.lines(p, cs);
        }
        catch (IOException e) {
            throw new RuntimeException(e);
        }
    };

    // Test without a separator at the end
    List<String> expected = readAllLines(p, cs);
    withData(TestData.Factory.ofSupplier("Lines with no separator at end", ss))
            .stream(s -> s)
            .expectedResult(expected)
            .exercise();

    // Test with a separator at the end
    writeLineSeparator(p, separatorGenerator, lines, cs);
    expected = readAllLines(p, cs);
    withData(TestData.Factory.ofSupplier("Lines with separator at end", ss))
            .stream(s -> s)
            .expectedResult(expected)
            .exercise();
}
 
Example 18
Project: Higher-Cloud-Computing-Project   File: LabeledDatasetLoader.java   Source Code and License Vote up 4 votes
/**
 * Datafile should keep class labels in the first column.
 *
 * @param pathToFile Path to file.
 * @param separator Element to tokenize row on separate tokens.
 * @param isDistributed Generates distributed dataset if true.
 * @param isFallOnBadData Fall on incorrect data if true.
 * @return Labeled Dataset parsed from file.
 */
public static LabeledDataset loadFromTxtFile(Path pathToFile, String separator, boolean isDistributed,
    boolean isFallOnBadData) throws IOException {
    Stream<String> stream = Files.lines(pathToFile);
    List<String> list = new ArrayList<>();
    stream.forEach(list::add);

    final int rowSize = list.size();

    List<Double> labels = new ArrayList<>();
    List<Vector> vectors = new ArrayList<>();

    if (rowSize > 0) {

        final int colSize = getColumnSize(separator, list) - 1;

        if (colSize > 0) {

            for (int i = 0; i < rowSize; i++) {
                Double clsLb;

                String[] rowData = list.get(i).split(separator);

                try {
                    clsLb = Double.parseDouble(rowData[0]);
                    Vector vec = parseFeatures(pathToFile, isDistributed, isFallOnBadData, colSize, i, rowData);
                    labels.add(clsLb);
                    vectors.add(vec);
                }
                catch (NumberFormatException e) {
                    if (isFallOnBadData)
                        throw new FileParsingException(rowData[0], i, pathToFile);
                }
            }

            LabeledVector[] data = new LabeledVector[vectors.size()];
            for (int i = 0; i < vectors.size(); i++)
                data[i] = new LabeledVector(vectors.get(i), labels.get(i));

            return new LabeledDataset(data, colSize);
        }
        else
            throw new NoDataException("File should contain first row with data");
    }
    else
        throw new EmptyFileException(pathToFile.toString());
}
 
Example 19
Project: Apache-Spark-2x-for-Java-Developers   File: CreateStreamExample.java   Source Code and License Vote up 4 votes
public static void main(String[] args) throws IOException {
	
	//Creating Streams using user/programmatically specified elements  
	 Stream<String> Userstream = Stream.of("Creating","Streams","from","Specific","elements");
	 Userstream.forEach(p -> System.out.println(p));
     
	 
	 //Creating Streams using array of objects
        Stream<String> ArrayStream = Stream.of( new String[]{"Stream","from","an","array","of","objects"} );
        ArrayStream.forEach(p -> System.out.println(p)); 
    
       
        //Creating Streams from an array
        String[] StringArray=new String[]{"We","can","convert","an","array","to","a","Stream","using","Arrays","as","well"};
        Stream<String> StringStream=Arrays.stream(StringArray);
        StringStream.forEach(p -> System.out.println(p));
        
        //Creating Streams from Collection
        List<Double> myCollection = new ArrayList<>();
        for(int i=0; i<10; i++){
       	 myCollection.add(Math.random());
        }
               //sequential stream
        Stream<Double> sequentialStream = myCollection.stream();
        sequentialStream.forEach(p -> System.out.println(p));
        		
                //parallel stream
        Stream<Double> parallelStream = myCollection.parallelStream();
        parallelStream.forEach(p -> System.out.println(p));
        
        
        //Stream from Hashmap
        Map<String, Integer> mapData = new HashMap<>();
        mapData.put("This", 1900);
        mapData.put("is", 2000);
        mapData.put("HashMap", 2100);
        
        mapData.entrySet()
       		.stream()
       		.forEach(p -> System.out.println(p));
        
        mapData.keySet()
               .stream()
               .forEach(p-> System.out.println(p));
        
        //primitive streams 
        IntStream.range(1, 4)
        .forEach(p -> System.out.println(p));
        
        LongStream.rangeClosed(1, 4)
        .forEach(p -> System.out.println(p));
        
        DoubleStream.of(1.0,2.0,3.0,4.0)
        .forEach(p -> System.out.println(p));
        
        //Infinite Streams using generate()
        Stream <Double> sequentialDoubleStream = Stream.generate(Math :: random); 

        Stream<Integer> sequentialIntegerStream = Stream.generate(new AtomicInteger () :: getAndIncrement); 

        //Infinite Streams using iterate()
        Stream <Integer> sequentialIntegerStream1 = Stream.iterate (Integer.MIN_VALUE, i -> i++); 

        Stream <BigInteger> sequentialBigIntegerStream = Stream.iterate(BigInteger.ZERO, i -> i.add (BigInteger.TEN)); 
        
        //Streams from File
        Stream<String> streamOfStrings = Files.lines(Paths.get("Apology_by_Plato.txt"));
        Stream<String> streamWithCharset = Files.lines(Paths.get("Apology_by_Plato.txt"), Charset.forName("UTF-8"));

      
}
 
Example 20
Project: jdk8u-jdk   File: Grep.java   Source Code and License Vote up 3 votes
/**
 * 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);
    }
}