strings - Inspired by Unix’s grep

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/wangbingfengf98/article/details/91487534

readAllLines

public static List<String> readAllLines(Path path)
                                 throws IOException

Read all lines from a file. Bytes from the file are decoded into characters using the UTF-8 charset.

This method works as if invoking it were equivalent to evaluating the expression:

Files.readAllLines(path, StandardCharsets.UTF_8)

Parameters:

path - the path to the file

Returns:

the lines from the file as a List; whether the List is modifiable or not is implementation dependent and therefore not specified

Throws:

IOException - if an I/O error occurs reading from the file or a malformed or unmappable byte sequence is read

SecurityException - In the case of the default provider, and a security manager is installed, the checkRead method is invoked to check read access to the file.

Since:

1.8

   /**
     * Read all lines from a file. This method ensures that the file is
     * closed when all bytes have been read or an I/O error, or other runtime
     * exception, is thrown. Bytes from the file are decoded into characters
     * using the specified charset.
     *
     * <p> This method recognizes the following as line terminators:
     * <ul>
     *   <li> <code>&#92;u000D</code> followed by <code>&#92;u000A</code>,
     *     CARRIAGE RETURN followed by LINE FEED </li>
     *   <li> <code>&#92;u000A</code>, LINE FEED </li>
     *   <li> <code>&#92;u000D</code>, CARRIAGE RETURN </li>
     * </ul>
     * <p> Additional Unicode line terminators may be recognized in future
     * releases.
     *
     * <p> Note that this method is intended for simple cases where it is
     * convenient to read all lines in a single operation. It is not intended
     * for reading in large files.
     *
     * @param   path
     *          the path to the file
     * @param   cs
     *          the charset to use for decoding
     *
     * @return  the lines from the file as a {@code List}; whether the {@code
     *          List} is modifiable or not is implementation dependent and
     *          therefore not specified
     *
     * @throws  IOException
     *          if an I/O error occurs reading from the file or a malformed or
     *          unmappable byte sequence is read
     * @throws  SecurityException
     *          In the case of the default provider, and a security manager is
     *          installed, the {@link SecurityManager#checkRead(String) checkRead}
     *          method is invoked to check read access to the file.
     *
     * @see #newBufferedReader
     */
    public static List<String> readAllLines(Path path, Charset cs) throws IOException {
        try (BufferedReader reader = newBufferedReader(path, cs)) {
            List<String> result = new ArrayList<>();
            for (;;) {
                String line = reader.readLine();
                if (line == null)
                    break;
                result.add(line);
            }
            return result;
        }
    }

The following example shows one way to apply regular expressions to search for matches in a file. Inspired by Unix’s grep , JGrep.java takes two arguments: a file name and the regular expression to match. The output shows each line where a match occurs and the match position(s) within the line.

// strings/JGrep.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.
// A very simple version of the "grep" program
// {java JGrep
// WhitherStringBuilder.java 'return|for|String'}

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

public class JGrep {
  public static void main(String[] args) throws Exception {
    if (args.length < 2) {
      System.out.println("Usage: java JGrep file regex");
      System.exit(0);
    }
    Pattern p = Pattern.compile(args[1]);
    // Iterate through the lines of the input file:
    int index = 0;
    Matcher m = p.matcher("");
    for (String line : Files.readAllLines(Paths.get(args[0]))) {
      m.reset(line);
      while (m.find()) {
        System.out.println("line:" + line);
        System.out.println(index++ + ": " + m.group() + ": " + m.start());// m.start() index is zero-based.
      }
    }
  }
}
/* My Output:
line:// strings/WhitherStringBuilder.java
0: String: 18
line:// We make no guarantees that this code is fit for any purpose.
1: for: 47
line:// Visit http://OnJava8.com for more book information.
2: for: 28
line:// Visit http://OnJava8.com for more book information.
3: for: 44
line:public class WhitherStringBuilder {
4: String: 20
line:  public String implicit(String[] fields) {
5: String: 9
line:  public String implicit(String[] fields) {

6: String: 25
line:    String result = "";
7: String: 4
line:    for (String field : fields) {
8: for: 4
line:    for (String field : fields) {
9: String: 9
line:    return result;
10: return: 4
line:  public String explicit(String[] fields) {
11: String: 9
line:  public String explicit(String[] fields) {
12: String: 25
line:    StringBuilder result = new StringBuilder();
13: String: 4
line:    StringBuilder result = new StringBuilder();
14: String: 31
line:    for (String field : fields) {
15: for: 4
line:    for (String field : fields) {
16: String: 9
line:    return result.toString();
17: return: 4
line:    return result.toString();
18: String: 20
*/

references:

1. On Java 8 - Bruce Eckel

2. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/strings/JGrep.java

3. https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#readAllLines-java.nio.file.Path-

4. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/strings/WhitherStringBuilder.java

5. http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/nio/file/Files.java

猜你喜欢

转载自blog.csdn.net/wangbingfengf98/article/details/91487534