-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathTempNioReadFile.java
executable file
·36 lines (33 loc) · 1.06 KB
/
TempNioReadFile.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
public class TempNioReadFile {
public static void main(String[] args){
readFromFile("c:\\temp.xml");
}
private static boolean readFromFile(String pathToFile){
boolean returnValue=false;
try{
FileInputStream fis=new FileInputStream(pathToFile);
FileChannel channel=fis.getChannel();
ByteBuffer buffer=ByteBuffer.allocate(50);
CharsetEncoder encoder=Charset.defaultCharset().newEncoder();
CharsetDecoder decoder=Charset.defaultCharset().newDecoder();
while(channel.read(buffer)>0){
buffer.flip();
CharBuffer charBuffer=decoder.decode(buffer);
System.out.println(charBuffer.toString());
buffer.clear();
}
returnValue=true;
}catch(Exception ex){
System.out.println("readFromFile: "+ex.getMessage());
returnValue=false;
}
return returnValue;
}
}