【问题标题】:Read from FileChannel with java nio使用 java nio 从 FileChannel 读取
【发布时间】:2018-11-11 13:09:14
【问题描述】:

你能告诉我一个简单的例子,从一个名为 example.txt 的文件中读取并使用 java NIO 在我的 java 程序中将所有内容放入一个字符串中吗? p>

以下是我目前正在使用的:

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();
    }
}

【问题讨论】:

  • 直接使用 java-nio 有什么特别的原因吗?因为这是一种常见的操作,所以在大多数情况下,您最好使用实用程序类。
  • 这只是一个了解 java nio 工作原理的练习

标签: java string io nio java-io


【解决方案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();
}

如果按 char 写入 char 在性能方面是可以接受的,那么您可以不使用中间人缓冲区 ca。在这种情况下,您可以简单地sb.append(cb.get())

【讨论】:

  • 符合日食The method read(ByteBuffer) in the type ReadableByteChannel is not applicable for the arguments (CharBuffer)
猜你喜欢
  • 2011-03-21
  • 1970-01-01
  • 2020-09-02
  • 2013-03-14
  • 1970-01-01
  • 2010-12-08
  • 1970-01-01
  • 2011-01-03
  • 2018-12-25
相关资源
最近更新 更多