[英]Read from FileChannel with java nio
您能给我展示一个简单的示例,以便从名为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();
}
}
尝试这个:
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();
}
如果逐个字符地写入char是可以接受的性能明智的选择,则可以不使用中间缓冲区ca
在这种情况下,您可以简单地sb.append(cb.get())
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.