讀取文字檔案內容(Java FileChannel)
阿新 • • 發佈:2019-01-12
import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; /** * 讀取文字檔案內容(Java FileChannel)。 * @author Bright Lee */ public class FileChannelTest { public static void main(String[] args) { RandomAccessFile file = null; try { file = new RandomAccessFile("C:\\JavaNIO\\test.txt", "rw"); FileChannel channel = file.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); while (true) { int count = channel.read(buffer); if (count <= -1) { break; } buffer.flip(); while (buffer.hasRemaining()) { char ch = (char) buffer.get(); System.out.print(ch); } buffer.compact(); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (file != null) { file.close(); } } catch (IOException e) { e.printStackTrace(); } } } }
執行結果:
Hello world! Java file NIO