Java基础之读文件——使用通道随机读取文件(RandomFileRead)
2013-11-04 23:12
621 查看
import java.nio.file.*; import java.nio.channels.FileChannel; import java.io.IOException; import java.nio.ByteBuffer; public class RandomFileRead { public static void main(String[] args) { Path file = Paths.get(System.getProperty("user.home")).resolve("Beginning Java Struff").resolve("primes.bin"); if(!Files.exists(file)) { System.out.println(file + " does not exist. Terminating program."); System.exit(1); } final int PRIMESREQUIRED = 10; final int LONG_BYTES = 8; // Number of bytes for type long ByteBuffer buf = ByteBuffer.allocate(LONG_BYTES*PRIMESREQUIRED); long[] primes = new long[PRIMESREQUIRED]; int index = 0; // Position for a prime in the file try (FileChannel inCh = (FileChannel)(Files.newByteChannel(file))){ // Count of primes in the file final int PRIMECOUNT = (int)inCh.size()/LONG_BYTES; // Read the number of random primes required for(int i = 0 ; i < PRIMESREQUIRED ; ++i) { index = LONG_BYTES*(int)(PRIMECOUNT*Math.random()); inCh.read(buf, index); // Read the value // inCh.position(index).read(buf); // Read the value buf.flip(); primes[i] = buf.getLong(); // Save it in the array buf.clear(); } // Output the selection of random primes 5 to a line in field width of 12 int count = 0; // Count of primes written for(long prime : primes) { System.out.printf("%12d", prime); if(++count%5 == 0) { System.out.println(); } } } catch(IOException e) { e.printStackTrace(); } } }
控制塔程序,本例从primes.bin文件中随机选择一些值进行提取。
相关文章推荐
- Java基础之读文件——使用通道随机读写文件(RandomReadWrite)
- 【幻化万千戏红尘】qianfengDay20-java基础学习:数据流、随机读取文件流RandomAccessFile
- java当中randomAccessFile文件随机读取对象的简单使用
- Java基础之读文件——使用通道读取混合数据1(ReadPrimesMixedData)
- Java基础之读文件——使用输入流读取二进制文件(StreamInputFromFile)
- Java基础之读文件——使用通道读取混合数据2(ReadPrimesMixedData2)
- Java按行读取正在被动态写入的大文件实例--使用RandomAccessFile(1)
- Java RandomAccessFile随机读取文件
- Java基础之读文件——使用缓冲读取器读取文件(ReaderInputFromFile)
- java:RandomAccessFile随机读取文件内容
- java中RandomAccessFile随机文件读写,文件追加和部分读取
- Java的RandomAccessFile随机文件读写的简单使用
- Java IO操作——简单了解RandomAccessFile随机读写文件操作类的使用
- RandomAccessFile读取超大文件 随机读一行
- JAVA基础 day23 IO流的其他类 (对象的序列化 管道流 RandomAccessFile类(随机读取文件) DateStream(操作基本数据类型的流) 操作数组的流 )字符编码问题
- Java基础之写文件——使用带缓冲的Writer写文件(WriterOutputToFile)
- Java源码——读取顺序存取文件中的数据(read text file and display each record)
- 使用FileReader对象的readAsDataURL方法来读取图像文件
- JAVA基础初探(十三)IO简介、字节流与字符流区别、带缓冲的字节/字符流读取数据、FileReader/FileWriter便捷类、Apache IO库使用说明
- AutoCAD .Net 使用 Database.ReadDwgFile 读取dwg文件而不显示文档窗口