I wrote this article because I thought I needed something to read and write files to create a new language. It's very versatile, so please apply it to something.
EAM is an abbreviation of ** Execute Around Method **, which means to allocate or free memory before and after a method. Especially when using external resources (such as IO) the garbage collector (GC) is not enough and you need to close the resource (such as FileWriter's close ()). It's hard to understand in words, so let's take a look at the implementation.
Functional programming with Java -Java8 lambda expression and Stream-
It is a quote from
`The Stream class added in Java 8 implements AutoCloseable. (...) As a result, AutoCloseable has been changed to a looser "resources may be closed" agreement instead of the previous strict "resources must be closed". (...) Using ARM This code is very concise and attractive, but developers should remember to use it. Ignoring this elegant syntax doesn't pay attention to your code ... but if you're looking for a way to release resources in a timely manner and avoid developer errors in a feud, ARM's We have to go further. ``
EAM.java
import java.util.*;
import java.io.*;
public class EAM{
private final FileReader fr;
private EAM(final String s) throws IOException{
fr = new FileReader(s);
}
public static void use(final String s,final Use<EAM,IOException> u) throws IOException{
final EAM eam = new EAM(s);
try{
u.accept(eam);
}finally{
eam.close();
}
}
private void close() throws IOException{
System.out.println("close()");
fr.close();
}
public void read(char[] c) throws IOException{
fr.read(c);
}
}
It is implemented only for Reader, but it is easy to implement Writer.
Use.java
@FunctionalInterface
public interface Use<T,X extends Throwable>{
void accept(T t) throws X;
}
The constructor is made private in case the resource is opened outside use () even though I am trying to manage the external resource. This allows only use () to be called externally. --Description of EAM.java
Main.java
import java.io.*;
import java.util.*;
public class Main{
public static void main(String[] args) throws IOException{
char[] c = new char[100];
EAM.use("eam.txt",eam -> eam.read(c));
for(char aChar:c) System.out.print(aChar);
}
}
Create eam.txt and type in the string, or specify another file. Could the character string in the file be read? If you have any questions, please ask.