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

本文介绍了一个使用Java控制台程序读取文件内容的实例,包括如何通过读取文件长度和数据分块来解析二进制素数值,并将其与字符串结合输出。重点展示了文件操作的基本步骤和注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

方法一:可以在第一个读操作中读取字符串的长度,然后再将字符串和二进制素数值读入到文本中。这种方式的唯一不足是:这不是一种有效读取文件的方式,因为有很多的读操作,其中的每个都读取非常少量的数据。

 

 1 import java.nio.file.*;
 2 import java.nio.channels.FileChannel;
 3 import java.io.IOException;
 4 import java.nio.ByteBuffer;
 5 
 6 public class ReadPrimesMixedData {
 7   public static void main(String[] args) {
 8     Path file = Paths.get(System.getProperty("user.home")).resolve("Beginning Java Struff").resolve("primes.txt");
 9     if(!Files.exists(file)) {
10       System.out.println(file + " does not exist. Terminating program.");
11       System.exit(1);;
12     }
13 
14     try (FileChannel inCh = (FileChannel)Files.newByteChannel(file)){
15       ByteBuffer lengthBuf = ByteBuffer.allocate(8);
16       int strLength = 0;                                               // Stores the string length
17 
18       ByteBuffer[] buffers = {
19                            null,                                       // Byte buffer to hold string
20                            ByteBuffer.allocate(8)                      // Byte buffer to hold prime
21                              };
22 
23       while(true) {
24         if(inCh.read(lengthBuf) == -1)                                 // Read the string length,
25           break;                                                       // if its EOF exit the loop
26 
27         lengthBuf.flip();
28 
29         // Extract the length and convert to int
30         strLength = (int)lengthBuf.getDouble();
31 
32         // Now create the buffer for the string
33         buffers[0] = ByteBuffer.allocate(2*strLength);
34 
35         if(inCh.read(buffers) == -1) {                                 // Read the string & binary prime value
36           // Should not get here!
37           System.err.println("EOF found reading the prime string.");
38           break;                                                       // Exit loop on EOF
39         }
40 
41         System.out.printf(
42                 "String length: %3s  String: %-12s  Binary Value: %3d%n",
43                 strLength,
44                 ((ByteBuffer)(buffers[0].flip())).asCharBuffer().toString(),
45                 ((ByteBuffer)buffers[1].flip()).getLong());
46 
47         // Clear the buffers for the next read
48         lengthBuf.clear();
49         buffers[1].clear();
50       }
51       System.out.println("\nEOF reached.");
52     } catch(IOException e) {
53       e.printStackTrace();
54     }
55   }
56 }

 

 

转载于:https://www.cnblogs.com/mannixiang/p/3387145.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值