java 随机读写_Java基础之读文件——使用通道随机读写文件(RandomReadWrite)

这个Java程序演示了如何使用NIO的SeekableByteChannel进行随机读写文件。它从一个二进制文件中随机读取素数,并用特定值替换,确保不会选取已替换的值。
摘要由CSDN通过智能技术生成

1 import static java.nio.file.StandardOpenOption.*;2 import java.nio.file.*;3 importjava.nio.channels.SeekableByteChannel;4 importjava.io.IOException;5 importjava.nio.ByteBuffer;6 importjava.util.EnumSet;7

8 public classRandomReadWrite {9 public static voidmain(String[] args)10 {11 Path file = Paths.get(System.getProperty("user.home")).resolve("Beginning Java Struff").resolve("primes_backup.bin");12 if(!Files.exists(file)) {13 System.out.println(file + " does not exist. Terminating program.");14 System.exit(1);15 }16

17 final int PRIMESREQUIRED = 10;18 ByteBuffer buf = ByteBuffer.allocate(8);19

20 long[] primes = new long[PRIMESREQUIRED];21 int index = 0; //Position for a prime in the file

22 final long REPLACEMENT = 99999L; //Replacement for a selected prime

23

24 try (SeekableByteChannel channel =Files.newByteChannel(file, EnumSet.of(READ, WRITE))){25 final int PRIMECOUNT = (int)channel.size()/8;26 System.out.println("Prime count = "+PRIMECOUNT);27 for(int i = 0 ; i < PRIMESREQUIRED ; ++i) {28 index = 8*(int)(PRIMECOUNT*Math.random());29 channel.position(index).read(buf); //Read at a random position

30 buf.flip(); //Flip the buffer

31 primes[i] = buf.getLong(); //Extract the prime

32 buf.flip(); //Flip to ready for insertion

33 buf.putLong(REPLACEMENT); //Replacement into buffer

34 buf.flip(); //Flip ready to write

35 channel.position(index).write(buf); //Write the replacement to file

36 buf.clear(); //Reset ready for next read

37 }38

39 //Alternate loop code to avoid selecting REPLACEMENT values

40 /*for(int i = 0 ; i < PRIMESREQUIRED ; ++i)41 {42 while(true)43 {44 index = 8*(int)(PRIMECOUNT*Math.random());45 channel.position(index).read(buf); // Read at a random position46 buf.flip(); // Flip the buffer47 primes[i] = buf.getLong(); // Extract the prime48 if(primes[i] != REPLACEMENT) {49 break; // It's good so exit the inner loop50 } else {51 buf.clear(); // Clear ready to read another52 }53 }54 buf.flip(); // Flip to ready for insertion55 buf.putLong(REPLACEMENT); // Replacement into buffer56 buf.flip(); // Flip ready to write57 channel.position(index).write(buf); // Write the replacement to file58 buf.clear(); // Reset ready for next read59 }*/

60

61 int count = 0; //Count of primes written

62 for(longprime : primes) {63 System.out.printf("%12d", prime);64 if(++count%5 == 0) {65 System.out.println();66 }67 }68 } catch(IOException e) {69 e.printStackTrace();70 }71 }72 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值