byteBuffer
package com.example;
//import java.nio.ByteBuffer; //導入依賴的package包/類
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SeekableByteChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
//String file="C:\\Work\\Java\\data\\19027835361399637";
Path file = Paths.get("C:\\Work\\Java\\data\\19027835361399637");
//Path file = Paths.get(System.getProperty("user.home") + "/test/myfile.txt");
try (SeekableByteChannel sbc = Files.newByteChannel(file)) { // |\longremark{newByteChannel默認返回隻讀的Channel}|
ByteBuffer buf = ByteBuffer.allocate(200); // |\longremark{allocate創建一個指定字節的ByteBuffer,本例中,sbc這個Channel每次讀取10個字節}|
String encoding = System.getProperty("file.encoding"); // |\longremark{獲得當前係統文件編碼方式,以便讀取文件字節後解碼}|
while (sbc.read(buf) > 0) { // |\longremark{從通道讀數據到緩衝區}|
buf.flip(); // |\longremark{切換緩衝區為讀模式}|
System.out.print(Charset.forName(encoding).decode(buf));
buf.clear(); // |\longremark{清空緩衝區,準備寫入下一輪數據}|
}
} catch (IOException x) {
System.out.println("caught exception: " + x);
}
}
}
留言
張貼留言