An implementation of file conversion in Java (surround execution mode & behavior parameterization & functional interface | Lambda expression)

File to string method --- (surround execution mode & behavior parameterization & functional interface|Lambda expression)

Well, of course, if it is convenient, we can use it directly,

org.apache.commons.io.FileUtils;

String readFileToString(final File file, final String encoding)

Learn here as a way of thinking 

First we talk about a few concepts:

  • Surround execution mode:

    • Simply put, for OI, JDBC and other similar resources, they need to be closed after they are used up. A common mode of resource processing is to open a resource, do some processing, and then close the resource. This setting is similar to the cleanup phase, and will The business logic surrounding the execution processing . This is the surround execution mode .
  • Behavior parameterization:

    • An idea of ​​functional programming is to wrap the code as a parameter passing behavior, that is, to wrap the code logic as a parameter and pass it to the method.
  • Lambda expression:

    • Lambda expressions are understood as a way to concisely express an anonymous function that can be passed . It has no name, but it has a function body, a parameter list, and a return type. An exception type can be thrown. The packaging code logic is the use of Lambda expressions as parameters .
  • Functional interface:

    • Essentially, it is an ordinary interface with only one abstract method , which can be implicitly converted into a Lambda expression , and it needs to be defined with annotations (@FunctionalInterface ) . Default methods and static methods do not need to be abstract methods and can be defined in functional interfaces .
    • If the functional interface additionally define more abstract methods , then these abstract method signature public Object methods must be the same as the interface ultimately determine the class that implements the ultimate parent class is Object. Therefore, functional interfaces can define public methods of Object.
    • @FunctionalInterfacepublic
      interface ObjectMethodFunctionalInterface {
      void count(int i);
      String toString(); //same to Object.toString
      int hashCode(); //same to Object.hashCode
      boolean equals(Object obj); //same to Object.equals
      }
  • About more java8 learning ,

    • "Java8 Actual Combat" personally feels that this book is good. You can also take a look at my blog, "java8 actual combat" reading notes , there are PDF resources for this book

Let's first look at a simple surround execution mode:

1) The first step; when the logic code needs to be changed, the code needs to be rewritten, so the behavior parameterization is thought of

public static String processFile()throws IOException {
        try(BufferedReader bufferedReader =
                new BufferedReader(new FileReader("data.txt"))){
           // return  bufferedReader.readLine();
            return  bufferedReader.readLine()+bufferedReader.readLine();
        }


2) The second step is to use a functional interface to pass a behavior

@FunctionalInterface
    public  interface BufferReaderProcessFile{
        // 方法签名为 BufferReader -> String
        String peocess(BufferedReader bufferedReader)throws IOException;
    }


3) The third step is to perform an action. Any BufferReader -> String Lambda expression can be passed in as a parameter. As long as it conforms to the signature of the peocess method.

 public static String processFiles(BufferReaderProcessFile bufferReaderProcessFile)throws IOException {
        try(BufferedReader bufferedReader =
                    new BufferedReader(new FileReader("data.txt"))){
             return bufferReaderProcessFile.peocess(bufferedReader) ;

 

 4) The fourth step, pass the Lambda

String string = processFiles((BufferedReader bs) ->bs.readLine());

Convert file to string

My thinking, I am not very familiar with java IO, if you have a good method, please leave a message and learn from each other :

  1. FileInputStream fileInputStream = new FileInputStream(file))
  2. InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream))
  3. BufferedReader bufferedReader = new BufferedReader(inputStreamReader))
  4. String str = bufferedReader.readLine()
  5. Byte stream-"character stream-"character buffer stream is about to convert byte stream to character stream and then wrap it with advanced stream.

So my idea is to avoid too many IO stream closures and exception captures in the logic, and concentrate on processing the read logic, combining the following two technologies:

  • try(){}[automatically close the stream, 1.7 support]
  • Lambda features to achieve [behavior parameterization, 1.8]

step:

Definition of functional interface transfer behavior:

package com.liruilong.demotext.service.utils.interfaceutils;

import java.io.BufferedReader;
import java.io.IOException;

/**
 * @Description : 函数接口,描述BufferedReader ->String的转化方式
 * @Author: Liruilong
 * @Date: 2020/3/17 15:44
 */
@FunctionalInterface
public interface InputStreamPeocess {
    /**
     * @Author Liruilong
     * @Description 方法签名 BufferedReader ->String
     * @Date 15:47 2020/3/17
     * @Param [inputStream]
     * @return com.liruilong.demotext.service.utils.InputStream
     **/

    String peocess(BufferedReader bufferedReader) throws IOException;
}

To perform an action, any BufferReader -> String Lambda expression can be passed in as a parameter. As long as it conforms to the signature of the peocess method.

 /**
     * @return java.lang.String
     * @Author Liruilong
     * @Description 环绕处理
     * @Date 17:14 2020/3/17
     * @Param [inputStreamPeocess, file]
     **/

    public static String fileToBufferedReader(InputStreamPeocess inputStreamPeocess, File file) {
        try (FileInputStream fileInputStream = new FileInputStream(file)) {
            try (InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream)) {
                try (BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
                    return inputStreamPeocess.peocess(bufferedReader);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            return null;
        }
    }

Execute Lambda

/**
     * @return java.lang.String
     * @Author Liruilong
     * @Description 文件转字符串
     * @Date 17:22 2020/3/17
     * @Param [file]
     **/

    public static String readJsonToString(File file) {
        return string = fileToBufferedReader((bufferedReader) -> {
            String str = null;
            StringBuilder stringBuilder = new StringBuilder();
            while ((str = bufferedReader.readLine()) != null) {
                stringBuilder.append(str);
            }
            return stringBuilder.toString();
        }, file);
    }

Such benefits:

  • We only need to care about the specific reading logic, and we don’t need to care about other things.
  • It can be used for text processing, filtering the read string and other operations.

I hope my friends can criticize and advise on the shortcomings. Come on with life..

Guess you like

Origin blog.csdn.net/sanhewuyang/article/details/105449221