[英]Read from FileChannel with java nio
Can you show me a simple example to read from a file named example.txt and put all contents into a string in my java program using java NIO ? 您能给我展示一个简单的示例,以便从名为example.txt的文件读取并将所有内容放入使用Java NIO的 java程序中的字符串吗?
Following is what I'm using for the moment: 以下是我目前正在使用的内容:
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();
}
}
Try this: 尝试这个:
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();
}
You could do without the middle man buffer ca
if writing char by char is acceptable performance wise. 如果逐个字符地写入char是可以接受的性能明智的选择,则可以不使用中间缓冲区
ca
In which case you could simply sb.append(cb.get())
. 在这种情况下,您可以简单地
sb.append(cb.get())
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.