简体   繁体   English

使用java nio从FileChannel中读取

[英]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.

相关问题 使用 java nio FileChannel 读取 hadoop 上的文件 - Read files on hadoop with java nio FileChannel 从FileChannel(Java NIO)读取GZIP文件 - Reading a GZIP file from a FileChannel (Java NIO) Java NIO FileChannel - 从 Android TUN.network 接口读取空数据 - Java NIO FileChannel - Empty reads from Android TUN network interface Java NIO FileChannel与FileOutputstream的性能/实用性 - Java NIO FileChannel versus FileOutputstream performance / usefulness Java nio FileChannel 写入方法说明 - Java nio FileChannel write method clarfication Java-NIO:将FileChannel.read()与offset-address / NullPointer一起使用 - Java-NIO: Use FileChannel.read() with offset-address / NullPointer 如何使用 java.nio.channels.FileChannel 读取到 ByteBuffer 实现类似 BufferedReader#readLine() 的行为 - How to use java.nio.channels.FileChannel to read to ByteBuffer achieve similiar behavior like BufferedReader#readLine() Java NIO2:需要在FileChannel上进行说明 - Java NIO2: Need clarification on FileChannel 从包含文件(file:/// path / to / file)的java.net.URL到java.nio.FileChannel - From a java.net.URL containing a file (file:///path/to/file) to a java.nio.FileChannel 在 Java 中,使用 java.nio 库和 FileChannel,如何从文件加载 Properties 对象? - In Java, using the java.nio library and a FileChannel, how can I load a Properties object from a file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM