예제 #1
0
  public void testFind() throws IOException {
    PathBiPredicate pred = new PathBiPredicate((path, attrs) -> true);

    try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE, pred)) {
      Set<Path> result = s.collect(Collectors.toCollection(TreeSet::new));
      assertEquals(pred.visited(), all);
      assertEquals(result.toArray(new Path[0]), pred.visited());
    }

    pred = new PathBiPredicate((path, attrs) -> attrs.isSymbolicLink());
    try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE, pred)) {
      s.forEach(path -> assertTrue(Files.isSymbolicLink(path)));
      assertEquals(pred.visited(), all);
    }

    pred = new PathBiPredicate((path, attrs) -> path.getFileName().toString().startsWith("e"));
    try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE, pred)) {
      s.forEach(path -> assertEquals(path.getFileName().toString(), "empty"));
      assertEquals(pred.visited(), all);
    }

    pred =
        new PathBiPredicate(
            (path, attrs) ->
                path.getFileName().toString().startsWith("l") && attrs.isRegularFile());
    try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE, pred)) {
      s.forEach(path -> fail("Expect empty stream"));
      assertEquals(pred.visited(), all);
    }
  }
예제 #2
0
 @Test
 public void fileExistTest() throws IOException {
   long countDir =
       Files.find(Paths.get(rootPath), 35, (path, attributes) -> attributes.isDirectory()).count();
   assertEquals(30, countDir);
   long countFiles =
       Files.find(Paths.get(rootPath), 35, (path, attributes) -> attributes.isRegularFile())
           .count();
   assertEquals(499950, countFiles);
 }
예제 #3
0
  public void testClosedStream() throws IOException {
    try (Stream<Path> s = Files.list(testFolder)) {
      s.close();
      Object[] actual = s.sorted().toArray();
      fail("Operate on closed stream should throw IllegalStateException");
    } catch (IllegalStateException ex) {
      // expected
    }

    try (Stream<Path> s = Files.walk(testFolder)) {
      s.close();
      Object[] actual = s.sorted().toArray();
      fail("Operate on closed stream should throw IllegalStateException");
    } catch (IllegalStateException ex) {
      // expected
    }

    try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE, (p, attr) -> true)) {
      s.close();
      Object[] actual = s.sorted().toArray();
      fail("Operate on closed stream should throw IllegalStateException");
    } catch (IllegalStateException ex) {
      // expected
    }
  }
예제 #4
0
  public static void main(String[] args) throws IOException {
    try (Stream<Path> stream = Files.list(Paths.get(""))) {
      String joined =
          stream
              .map(String::valueOf)
              .filter(path -> !path.startsWith("."))
              .sorted()
              .collect(Collectors.joining("; "));
      System.out.println("List: " + joined);
    }

    Path start = Paths.get("");
    int maxDepth = 5;
    try (Stream<Path> stream =
        Files.find(start, maxDepth, (path, attr) -> String.valueOf(path).endsWith(".java"))) {
      String joined = stream.sorted().map(String::valueOf).collect(Collectors.joining("; "));
      System.out.println("Found: " + joined);
    }

    try (Stream<Path> stream = Files.walk(start, maxDepth)) {
      String joined =
          stream
              .map(String::valueOf)
              .filter(path -> path.endsWith(".java"))
              .sorted()
              .collect(Collectors.joining("; "));
      System.out.println("walk(): " + joined);
    }

    List<String> lines = Files.readAllLines(Paths.get("src/golf.sh"));
    lines.add("puts 'foobar'");
    Path path = Paths.get("src/golf-modified.sh");
    Files.write(path, lines);

    try (Stream<String> stream = Files.lines(path)) {
      stream.filter(line -> line.contains("puts")).map(String::trim).forEach(System.out::println);
    }

    System.out.println("a" == "a");
    System.out.println("a" != new String("a"));
    System.out.println(null != "a");
    System.out.println("a".equals("a"));

    try (BufferedReader reader = Files.newBufferedReader(path)) {
      while (reader.ready()) System.out.println(reader.readLine());
    }

    try (BufferedWriter writer = Files.newBufferedWriter(Paths.get("hello-world.sh"))) {
      writer.write("puts 'Hello world'");
    }

    try (BufferedReader reader = Files.newBufferedReader(path)) {
      long countPuts = reader.lines().filter(line -> line.contains("put")).count();
      System.out.println(countPuts);
    }
  }
  public static void main(String[] args) {
    // Methods in Comparator
    List<Person> people = new ArrayList<>();
    people.sort(
        Comparator.comparing(Person::getLastName)
            .thenComparing(Person::getFirstName)
            .thenComparing(
                Person::getEmailAddress, Comparator.nullsLast(String.CASE_INSENSITIVE_ORDER)));

    // Old way of initializing ThreadLocal:
    ThreadLocal<List<String>> oldThreadLocalString =
        new ThreadLocal<List<String>>() {
          @Override
          public List<String> initialValue() {
            return new ArrayList<>();
          }
        };
    System.out.println(oldThreadLocalString.get());

    // New way:
    ThreadLocal<List<String>> newThreadLocalString = ThreadLocal.withInitial(ArrayList::new);
    System.out.println(newThreadLocalString.get());

    // Java Optional
    Optional<Integer> optional = new ArrayList<Integer>().stream().min(Integer::compareTo);
    System.out.println(optional);

    // Files can now return streams
    try {
      Stream stream = Files.list(Paths.get("c:\\temp\\"));
      stream = Files.lines(Paths.get("c:\\temp\\"), Charset.forName("UTF_32"));
      stream = Files.find(Paths.get("c:\\"), 5, (T, U) -> (T == U));

    } catch (IOException e) {
      UncheckedIOException ex = new UncheckedIOException("cause", e);
      System.out.println(ex.getMessage());
    }

    // Rejoice, for we finally have string joins!
    String joinExample = String.join(",", "a", "b", "c", "4", "E", "6");
    System.out.println(joinExample);

    StringJoiner joiner = new StringJoiner("-");
    joiner.add("abbie");
    joiner.add("doobie");
    System.out.println(joiner.toString());
  }
예제 #6
0
 static void filesTest() {
   // Files.list
   try {
     try (Stream<Path> stream = Files.list(Paths.get("/opt"))) {
       String joined =
           stream
               .map(String::valueOf)
               .filter(path -> !path.startsWith("."))
               .sorted()
               .collect(Collectors.joining("; "));
       System.out.println("List path /opt : " + joined);
     }
   } catch (IOException e) {
     e.printStackTrace();
   }
   // Files.find
   Path start = Paths.get("/Users/alibaba/Downloads/2016113");
   int maxDepth = 5;
   try (Stream<Path> stream =
       Files.find(start, maxDepth, (path, attr) -> String.valueOf(path).endsWith(".js"))) {
     String joined = stream.sorted().map(String::valueOf).collect(Collectors.joining("; "));
     System.out.println("Files find : " + joined);
   } catch (IOException e) {
     e.printStackTrace();
   }
   // Files.walk
   try (Stream<Path> stream = Files.walk(start, maxDepth)) {
     String joined =
         stream
             .map(String::valueOf)
             .filter(path -> path.endsWith(".js"))
             .sorted()
             .collect(Collectors.joining("; "));
     System.out.println("Files walk : " + joined);
   } catch (IOException e) {
     e.printStackTrace();
   }
   // Files.readAllLines
   try {
     String p = "/Users/alibaba/linuxsir.txt";
     List<String> lines = Files.readAllLines(Paths.get(p));
     lines.add("print('foobar');");
     Files.write(Paths.get(p), lines);
     lines.remove(lines.size() - 1);
     System.out.println("readAllLines " + lines);
     Files.write(Paths.get(p), lines);
   } catch (IOException e) {
     e.printStackTrace();
   }
   // Files.lines
   try (Stream<String> stream = Files.lines(Paths.get("/Users/alibaba/linuxsir.txt"))) {
     stream.filter(line -> line.contains("w")).map(String::valueOf).forEach(System.out::println);
   } catch (IOException e) {
     e.printStackTrace();
   }
   // Files.newBufferedReader&Files.newBufferedWriter
   Path path = Paths.get("/Users/alibaba/linuxsir.txt");
   try (BufferedReader reader = Files.newBufferedReader(path)) {
     System.out.println(reader.readLine());
   } catch (IOException e) {
     e.printStackTrace();
   }
   path = Paths.get("/Users/alibaba/output.txt");
   try (BufferedWriter writer = Files.newBufferedWriter(path)) {
     writer.write("print('Hello World')");
   } catch (IOException e) {
     e.printStackTrace();
   }
 }