使用 java nio 从 FileChannel 读取
Read from FileChannel with java nio
你能给我一个简单的例子来读取一个名为 example.txt 的文件,然后使用 java 程序将所有内容放入一个字符串中 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();
}
如果一个字符一个字符地写入一个字符在性能方面是可以接受的,那么您可以不用中间人缓冲区 ca
。在这种情况下,您可以简单地 sb.append(cb.get())
.
你能给我一个简单的例子来读取一个名为 example.txt 的文件,然后使用 java 程序将所有内容放入一个字符串中 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();
}
如果一个字符一个字符地写入一个字符在性能方面是可以接受的,那么您可以不用中间人缓冲区 ca
。在这种情况下,您可以简单地 sb.append(cb.get())
.