控制台程序,本例读取Java基础之写文件部分(PrimesToFile2)写入的Primes.txt。

方法二:设置一个任意容量的、大小合适的字节缓冲区并且使用来自文件的字节进行填充。然后整理出缓冲区中所有的内容。这种方式的问题是:缓冲区的内容可能会在读取文件的一个数据项时半途而断。这样一来,就必须做一些工作对此进行检测并且找出下一步要做的工作,但是这比第一种方式更加有效,因为这极大减少了用于读取整个文件所需的读操作数目。

本例的关键是缓冲区类提供的compact()方法,即压缩缓冲区。

 import java.nio.file.*;
import java.nio.channels.ReadableByteChannel;
import java.io.IOException;
import java.nio.ByteBuffer; public class ReadPrimesMixedData2 { public static void main(String[] args) {
Path file = Paths.get(System.getProperty("user.home")).resolve("Beginning Java Struff").resolve("primes.txt");
if(!Files.exists(file)) {
System.out.println(file + " does not exist. Terminating program.");
System.exit(1);
} try(ReadableByteChannel inCh = Files.newByteChannel(file)) {
ByteBuffer buf = ByteBuffer.allocateDirect(256);
buf.position(buf.limit()); // Set the position for the loop operation
int strLength = 0; // Stores the string length
byte[] strChars = null; // Array to hold the bytes for the string while(true) {
if(buf.remaining() < 8) { // Verify enough bytes for string length
if(inCh.read(buf.compact()) == -1)
break; // EOF reached
buf.flip();
}
strLength = (int)buf.getDouble(); // Get the string length // Verify enough bytes for complete string
if(buf.remaining() < 2*strLength) {
if(inCh.read(buf.compact()) == -1) {
System.err.println("EOF found reading the prime string.");
break; // EOF reached
}
buf.flip();
}
strChars = new byte[2*strLength]; // Array for string bytes
buf.get(strChars); // Get the bytes if(buf.remaining() < 8) { // Verify enough bytes for prime value
if(inCh.read(buf.compact()) == -1) {
System.err.println("EOF found reading the binary prime value.");
break; // EOF reached
}
buf.flip();
} System.out.printf("String length: %3s String: %-12s Binary Value: %3d%n",
strLength, ByteBuffer.wrap(strChars).asCharBuffer(),buf.getLong());
} System.out.println("\nEOF reached."); } catch(IOException e) {
e.printStackTrace();
}
}
}

Java基础之读文件——使用通道读取混合数据2(ReadPrimesMixedData2)的更多相关文章

  1. Java基础之读文件——使用通道读取混合数据1(ReadPrimesMixedData)

    控制台程序,本例读取Java基础之写文件部分(PrimesToFile2)写入的Primes.txt. 方法一:可以在第一个读操作中读取字符串的长度,然后再将字符串和二进制素数值读入到文本中.这种方式 ...

  2. Java基础之读文件——使用输入流读取二进制文件(StreamInputFromFile)

    控制台程序,读取Java基础之读文件部分(StreamOutputToFile)写入的50个fibonacci数字. import java.nio.file.*; import java.nio.* ...

  3. Java基础之读文件——使用通道读二进制数据(ReadPrimes)

    控制台程序,本例读取Java基础之写文件部分(PrimesToFile)写入的primes.bin. import java.nio.file.*; import java.nio.*; import ...

  4. Java基础之读文件——使用缓冲读取器读取文件(ReaderInputFromFile)

    控制台程序,本例读取Java基础之写文件部分(WriterOutputToFile)写入的Saying.txt. import java.io.*; import java.nio.file.*; i ...

  5. Java基础之读文件——使用通道随机读取文件(RandomFileRead)

    import java.nio.file.*; import java.nio.channels.FileChannel; import java.io.IOException; import jav ...

  6. Java基础之读文件——使用通道随机读写文件(RandomReadWrite)

    控制台程序,使用通道随机读写primes_backup.bin文件. import static java.nio.file.StandardOpenOption.*; import java.nio ...

  7. Java基础之读文件——使用通道复制文件(FileBackup)

    控制台程序,除了使用Files类中使用copy()方法将文件复制外,还可以使用FileChannel对象复制文件,连接到输入文件的FileChannel对象能直接将数据传输到连接到输出文件的FileC ...

  8. Java基础之读文件——从文件中读取文本(ReadAString)

    控制台程序,使用通道从缓冲区获取数据,读取Java基础之写文件(BufferStateTrace)写入的charData.txt import java.nio.file.*; import java ...

  9. Java基础之写文件——创建通道并且写文件(TryChannel)

    控制台程序,创建一个文件并且使用通道将一些文本写入到这个文件中. import static java.nio.file.StandardOpenOption.*; import java.nio.c ...

随机推荐

  1. WPF 最大化最小化窗口

    public static void FullOrMin(this Window window)        {            //如果是全屏,则最小化            if (win ...

  2. PHP5.4安装xhprof扩展[不要去pecl下载]

    HP5.3或之前版本可以去pecl(http://pecl.php.net)下载xhprof扩展安装. 但pecl上的版本不支持PHP5.4 可以到github上的xhprof库中下载:https:/ ...

  3. SMS模型格网转换为MIKE21的格网源代码

    program main !sms网格转换成mike21网格 DIMENSION X(),Y(),H(),NDNN(,),ncbd() dimension NBS(),NOBD(,),NSED(,), ...

  4. 【转】Warning: mysql_connect(): mysqlnd cannot connect to MySQL 4.1+ using the old insecure authenticat

    Warning: mysql_connect(): mysqlnd cannot connect to MySQL 4.1+ using the old insecure authenticat 当m ...

  5. FW docker使用问题总结,解决国内不能访问gcr.io的问题

    docker使用问题总结 解决国内不能访问gcr.io的问题 国内可以通过https://dashboard.daocloud.io来下载. 比如?gcr.io/google_containers/p ...

  6. postgressql安装

    参考文章 FreeBSD10.0下ports安装postgresql9.4-server: http://download.csdn.net/detail/machen_smiling/8425613 ...

  7. Android源码剖析之Framework层进阶版(Wms窗口管理)

    本文来自http://blog.csdn.net/liuxian13183/ ,引用必须注明出处! 上一篇我们主要讲了Ams,篇幅有限,本篇再讲讲Wms,即WindowManagerService,管 ...

  8. 【Android开发学习笔记】【随笔】UI线程

    概念 UI线程 是Android中的主线程,涉及到UI方面的一些操作都需要在ui线程中进行操作 在非ui线程中想操作ui,就会报错 android.view.ViewRoot$CalledFromWr ...

  9. 在Windows上一键编译各种版本的Protobuf

    所需工具 : cmake  for  windows 和  git for windows 原理:protobuf 是google的一个开源项目,其源代码在github上可以下载到,并且源码都采用cm ...

  10. C++用数组实现的静态队列

    #ifndef _STATIC_QUEUE_H_ #define _STATIC_QUEUE_H_ // 静态queue模板,用数组实现的队列,在初始化的时候需要指定长度 template<cl ...