如何从同时包含字符与整数的字节数组对应的文件中读取目标整数
问题根源
你当前的存储逻辑没有区分字符类型和整数类型的元信息,所有内容都被统一转为byte值写入文件:比如你代码里的'D'和68对应的byte值完全相同,读取时自然无法区分这个字节原本是字符还是你要提取的整数。同时你现有代码错误将Scanner绑定了系统输入而非文件输入,也是无法正确读取的原因之一。
解决方法
方案1:给存储内容增加类型标识(二进制存储)
每个存储单元前加1个标识字节:0代表后续1字节是字符,1代表后续1字节是整数,写入时打标,读取时根据标识判断是否要输出为整数。
示例代码:
import java.util.*; import java.io.*; class ReadInt { // 标识常量 private static final byte TYPE_CHAR = 0; private static final byte TYPE_INT = 1; public static void main(String[] args) throws IOException { // 写入阶段:给每个元素加类型标识 FileOutputStream fout = new FileOutputStream("Integer.txt"); // 按[标识+内容]的结构写入 writeWithType(fout, TYPE_CHAR, (byte)'h'); writeWithType(fout, TYPE_CHAR, (byte)'e'); writeWithType(fout, TYPE_CHAR, (byte)'l'); writeWithType(fout, TYPE_INT, (byte)68); writeWithType(fout, TYPE_CHAR, (byte)'l'); writeWithType(fout, TYPE_CHAR, (byte)'o'); writeWithType(fout, TYPE_INT, (byte)1); writeWithType(fout, TYPE_INT, (byte)2); fout.close(); // 读取阶段:按标识筛选整数 FileInputStream fin = new FileInputStream("Integer.txt"); int type, content; while ((type = fin.read()) != -1) { content = fin.read(); if (type == TYPE_INT) { System.out.print(content + " "); } } fin.close(); // 输出结果:68 1 2 } private static void writeWithType(FileOutputStream fout, byte type, byte content) throws IOException { fout.write(type); fout.write(content); } }
方案2:改为文本结构化存储(可读性更高)
直接把所有内容按类型:值的格式写入文本文件,读取时分割字符串判断类型即可,不需要处理二进制字节。
示例代码:
import java.util.*; import java.io.*; class ReadInt { public static void main(String[] args) throws IOException { // 写入文本 PrintWriter pw = new PrintWriter(new FileWriter("Integer.txt")); pw.println("char:h"); pw.println("char:e"); pw.println("char:l"); pw.println("int:68"); pw.println("char:l"); pw.println("char:o"); pw.println("int:1"); pw.println("int:2"); pw.close(); // 读取筛选整数 BufferedReader br = new BufferedReader(new FileReader("Integer.txt")); String line; while ((line = br.readLine()) != null) { String[] parts = line.split(":"); if ("int".equals(parts[0])) { System.out.print(parts[1] + " "); } } br.close(); } }
内容的提问来源于stack exchange,提问作者Shubham J
相关产品推荐
相关产品推荐

