你能告訴我一個簡單的例子,從名為example.txt的文件中讀取并使用java NIO將所有內容放入我的 java 程序中的字符串中嗎?以下是我目前使用的:FileChannel inChannel = FileChannel.open(Paths.get(file),StandardOpenOption.READ);CharBuffer buf=ByteBuffer.allocate(1024).asCharBuffer();while(inChannel.read(buf)!=-1) { buf.flip(); while(buf.hasRemaining()) { //append to a String buf.clear(); }}
1 回答

Helenr
TA貢獻1780條經驗 獲得超4個贊
試試這個:
public static String readFile(File f, int bufSize) {
ReadableByteChannel rbc = FileChannel.open(Paths.get(f),StandardOpenOption.READ);
char[] ca = new char[bufSize];
ByteBuffer bb = ByteBuffer.allocate(bufSize);
StringBuilder sb = new StringBuilder();
while(rbc.read(bb) > -1) {
CharBuffer cb = bb.asCharBuffer();
cb.flip();
cb.get(ca);
sb.append(ca);
cb.clear();
}
return sb.toString();
}
ca如果按 char 寫入 char 在性能方面是可以接受的,那么您可以不使用中間人緩沖區。在這種情況下,您可以簡單地sb.append(cb.get()).
添加回答
舉報
0/150
提交
取消