Reference: http://jybzjf.iteye.com/blog/2262392
Java read code has a BOM file before there is a bug, and later fixed.
However, the addition of the files stream operation in JDK8 still does not seem to support BOM file reads.
Read the file row data using the Files.lines, using the following method:
Read all content
list<string> lines = Files.readalllines (Paths.get ("G://test.txt"), charsets.utf_8);
Read part of the content
long index = 0l; Read
int limit = ten from line 0; Reads 10 lines
of content Files.lines (Paths.get ("G://test.txt"), Charsets.utf_8)
. Skip (Index)
. Limit (limit)
. ForEach (line-> {
//processing each row of content
});
Can see JDK8 after using the files stream operation can only use a line of code, even without writing file input output stream, buffering can easily read and write files.
However, there is also a bug that reads and writes files encoded with a BOM.
The information in the opening reference link is the Java adaptation of the code with a BOM file read and write, where the main code with the BOM file is as follows:
Note: In Jdk8, the Unicodeinputstream class has some minor changes.
file F = new File ("D:" +file.separator+ "Order.txt");
FileInputStream in = new FileInputStream (f);
String DC = Charset.defaultcharset (). Name ();
Unicodeinputstream UIn = new Unicodeinputstream (IN,DC);
BufferedReader br = new BufferedReader (new InputStreamReader (UIn));
String line = Br.readline ();
Unicodeinputstream is the processing class with BOM files.
But the files.lines are already encapsulated, parameters can only pass the file path, and there is no interface for the file stream. How to deal with it.
Next we look at the Files.lines method source code.
public static stream<string> lines (path path, Charset cs) throws IOException {
BufferedReader br = Files.newbuff Eredreader (path, CS);
try {return
br.lines (). OnClose (Asuncheckedrunnable (BR));
} catch (error| RuntimeException e) {
try {
br.close ();
} catch (IOException ex) {
try {
e.addsuppressed (ex);
} catch (Throwable ignore) {}
}
throw e;
}
}
In fact, the source code is also the processing of bufferedreader, so we can use in our own codes:
Unicodeinputstream UIs = new Unicodeinputstream (Files.newinputstream (paths.get (Path)), true)//true indicates that BOM characters
are not read BufferedReader br = new BufferedReader (new InputStreamReader (UIs, CharSet));
Br.lines (). OnClose (Asuncheckedrunnable (BR))
. Skip (This.index)
. Limit (This.limit)
. ForEach (Line- > {
System.out.pinrtln (line);
});
Uis.close ();
Asuncheckedrunnable method directly from the source inside the copy out
private static Runnable asuncheckedrunnable (closeable c) {return
()-> {
try {
c.close ();
} catch (IOException e) {
throw new uncheckedioexception (e);}}
;
}
This allows you to read the encoded file with a BOM using the stream operation of files.