有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用java nio从FileChannel读取的字符串

你能给我一个简单的例子,从一个名为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) 个答案

  1. # 1 楼答案

    试试这个:

    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。在这种情况下,您可以简单地sb.append(cb.get())