files - Reading & Writing Files

// files/ListOfLines.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

import java.nio.file.*;
import java.util.*;

public class ListOfLines {
  public static void main(String[] args) throws Exception {
    Files.readAllLines(Paths.get("../streams/Cheese.dat")) // final class Paths since 1.7
        .stream()
        .filter(line -> !line.startsWith("//"))
        .map(line -> line.substring(0, line.length() / 2))
        .forEach(System.out::println);
  }
}
/* Output:
Not much of a cheese
Finest in the
And what leads you
Well, it's
It's certainly uncon
*/

get

public static Path get(String first,
                       String... more)

Converts a path string, or a sequence of strings that when joined form a path string, to a Path. If more does not specify any elements then the value of the first parameter is the path string to convert. If more specifies one or more elements then each non-empty string, including first, is considered to be a sequence of name elements (see Path) and is joined to form a path string. The details as to how the Strings are joined is provider specific but typically they will be joined using the name-separator as the separator. For example, if the name separator is "/" and getPath("/foo","bar","gus") is invoked, then the path string "/foo/bar/gus" is converted to a Path. A Path representing an empty path is returned if first is the empty string and more does not contain any non-empty strings.

The Path is obtained by invoking the getPath method of the default FileSystem.

Note that while this method is very convenient, using it will imply an assumed reference to the default FileSystem and limit the utility of the calling code. Hence it should not be used in library code intended for flexible reuse. A more flexible alternative is to use an existing Path instance as an anchor, such as:

     Path dir = ...
     Path path = dir.resolve("file");
 

Parameters:

first - the path string or initial part of the path string

more - additional strings to be joined to form the path string

Returns:

the resulting Path

Throws:

InvalidPathException - if the path string cannot be converted to a Path

See Also:

FileSystem.getPath(java.lang.String, java.lang.String...)

// files/Writing.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

import java.nio.file.*;
import java.util.*;

public class Writing {
  static Random rand = new Random(47);
  static final int SIZE = 1000;

  public static void main(String[] args) throws Exception {
    // Write bytes to a file:
    byte[] bytes = new byte[SIZE];
    rand.nextBytes(bytes);
    Files.write(Paths.get("bytes.dat"), bytes);
    System.out.println("bytes.dat: " + Files.size(Paths.get("bytes.dat")));

    // Write an iterable to a file:
    List<String> lines = Files.readAllLines(Paths.get("../streams/Cheese.dat"));
    Files.write(Paths.get("Cheese.txt"), lines);
    System.out.println("Cheese.txt: " + Files.size(Paths.get("Cheese.txt")));
  }
}
/* My Output:
bytes.dat: 1000
Cheese.txt: 193
*/

We use Random to create a thousand random byte s; you can see the resulting file size is 1000. A List is written to a file here, but anything Iterable will work. What if file size is an issue? Perhaps:

  1. The file is so big you might run out of memory if you read the whole thing at once.
  2. You only need to work partway through the file to get the results you want, so reading the whole file wastes time.

Files.lines() conveniently turns a file into a Stream of lines: 

read

// files/ReadLineStream.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

import java.nio.file.*;

public class ReadLineStream {
  public static void main(String[] args) throws Exception {
    Files.lines(Paths.get("PathInfo.java")).skip(13).findFirst().ifPresent(System.out::println);// skip 13 lines
  }
}
/* My Output:
  }
*/

read and write

// files/StreamInAndOut.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

import java.io.*;
import java.nio.file.*;
import java.util.stream.*;

public class StreamInAndOut {
  public static void main(String[] args) {
    try (Stream<String> input = Files.lines(Paths.get("StreamInAndOut.java"));
        PrintWriter output = new PrintWriter("StreamInAndOut.txt")) {
      input.map(String::toUpperCase).forEachOrdered(output::println);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
}

references:

1. On Java 8 - Bruce Eckel

2. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/files/ListOfLines.java

3. https://docs.oracle.com/javase/8/docs/api/java/nio/file/Paths.html#get-java.lang.String-java.lang.String...-

4.  https://github.com/wangbingfeng/OnJava8-Examples/blob/master/files/Writing.java

5. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/files/ReadLineStream.java

6. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/files/StreamInAndOut.java

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章