Java中从文件读取整数对并赋值给数组对应索引的实现方法
如何在Java中从文件读取整数对并填充数组?
嘿,这个需求我平时处理过不少,其实核心就是文件读取+整数解析+数组赋值这几个环节,我给你拆成步骤讲,再附上完整代码示例,你一看就懂~
核心思路
首先得明确两个关键点:
- 数组的长度得足够大,不然如果文件里出现一个超大的索引,直接赋值会抛出
ArrayIndexOutOfBoundsException - 要处理文件读取中的各种异常(比如文件找不到、行格式错误、非整数内容等)
方案一:先确定数组大小(适合索引范围可控的场景)
如果不确定文件里最大的索引是多少,我们可以先遍历一遍文件,找到最大的索引值,再初始化对应长度的数组,这样就不会出现越界问题了。
完整代码示例:
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class ArrayFromFile { public static void main(String[] args) { String filePath = "your-file-path.txt"; // 替换成你的文件路径 int maxIndex = -1; // 第一步:先遍历文件,找到最大的索引 try (BufferedReader br = new BufferedReader(new FileReader(filePath))) { String line; while ((line = br.readLine()) != null) { line = line.trim(); if (line.isEmpty()) continue; // 跳过空行 String[] parts = line.split("\\s+"); // 按任意空白字符分割 if (parts.length != 2) { System.err.println("无效的行格式:" + line); continue; } try { int index = Integer.parseInt(parts[0]); if (index > maxIndex) { maxIndex = index; } } catch (NumberFormatException e) { System.err.println("行中包含非整数:" + line); } } } catch (IOException e) { System.err.println("读取文件失败:" + e.getMessage()); return; } // 如果没有有效索引,直接返回 if (maxIndex == -1) { System.out.println("文件中没有有效的整数对"); return; } // 第二步:初始化数组并填充值 int[] resultArray = new int[maxIndex + 1]; // 索引从0开始,所以长度要+1 try (BufferedReader br = new BufferedReader(new FileReader(filePath))) { String line; while ((line = br.readLine()) != null) { line = line.trim(); if (line.isEmpty()) continue; String[] parts = line.split("\\s+"); if (parts.length != 2) continue; try { int index = Integer.parseInt(parts[0]); int value = Integer.parseInt(parts[1]); resultArray[index] = value; } catch (NumberFormatException e) { System.err.println("跳过无效行:" + line); } } } catch (IOException e) { System.err.println("再次读取文件失败:" + e.getMessage()); return; } // 测试输出数组(可选) System.out.println("填充后的数组:"); for (int i = 0; i < resultArray.length; i++) { if (resultArray[i] != 0) { // 只输出被赋值过的索引(默认值是0,如果你的值可能为0,这里要调整) System.out.printf("索引%d的值:%d%n", i, resultArray[i]); } } } }
方案二:用HashMap替代数组(适合索引范围极大的场景)
如果文件里的索引非常大(比如几十万甚至上百万),用数组会占用大量内存,这时候用HashMap<Integer, Integer>来存储索引和值的映射会更高效,不需要提前确定大小。
简化代码示例:
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class MapFromFile { public static void main(String[] args) { String filePath = "your-file-path.txt"; Map<Integer, Integer> indexValueMap = new HashMap<>(); try (BufferedReader br = new BufferedReader(new FileReader(filePath))) { String line; while ((line = br.readLine()) != null) { line = line.trim(); if (line.isEmpty()) continue; String[] parts = line.split("\\s+"); if (parts.length != 2) { System.err.println("无效行:" + line); continue; } try { int index = Integer.parseInt(parts[0]); int value = Integer.parseInt(parts[1]); indexValueMap.put(index, value); } catch (NumberFormatException e) { System.err.println("跳过非整数行:" + line); } } } catch (IOException e) { System.err.println("文件读取失败:" + e.getMessage()); return; } // 测试输出 System.out.println("索引-值映射:"); indexValueMap.forEach((index, value) -> System.out.printf("索引%d:%d%n", index, value)); } }
注意事项
- 一定要用
try-with-resources语法,它会自动关闭文件流,避免资源泄漏 - 要处理各种异常情况,比如文件不存在、行格式错误、非整数内容,不然程序容易崩溃
- 如果你的业务中允许索引对应的值为0,那方案一中的测试输出逻辑要调整,因为数组默认值就是0,没法区分是没赋值还是值本身就是0
内容的提问来源于stack exchange,提问作者Bip
相关产品推荐
相关产品推荐

