如何将文本文件中的动物属性列表转换为Java二维数组?
把动物属性文本转成二维数组的解决方案
嘿,我来帮你搞定这个转换问题!你的现有代码只是把文件内容读出来打印,但没对每行的属性做分割和结构化处理,咱们来调整一下,把这些行转成可以操作的二维结构。
核心思路
咱们需要对每一行做这几件事:
- 把每行按
,(逗号加空格)分割成单个属性字符串 - 把每行的属性集合起来,最终形成一个“行集合”(也就是二维数组/列表)
- 用更安全的资源管理方式读取文件,避免手动关闭流的麻烦
改进后的代码(推荐用List<List<String>>,灵活适配不同长度的行)
因为你的行有的是6个属性,有的是7个,用List<List<String>>比固定长度的二维数组更灵活,后续增删改也方便:
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class FileReading { public static void main(String[] args) { // 用来存储所有动物的属性,外层List是行,内层List是每行的属性 List<List<String>> animalData = new ArrayList<>(); // 用try-with-resources自动关闭流,不用手动写finally try (BufferedReader br = new BufferedReader(new FileReader("Animals.txt"))) { String line; while ((line = br.readLine()) != null) { // 按", "分割每行的属性,注意如果有的行是逗号后无空格,可改用split("\\s*,\\s*")匹配任意空格 String[] attributes = line.split(", "); // 把数组转成List,加入到二维集合中 List<String> animalAttributes = new ArrayList<>(); for (String attr : attributes) { animalAttributes.add(attr); } // 或者用更简洁的方式:animalAttributes = Arrays.asList(attributes); animalData.add(animalAttributes); } } catch (IOException e) { e.printStackTrace(); } // 测试打印二维结构 System.out.println("转换后的二维集合:"); for (List<String> animal : animalData) { System.out.println(animal); } // 示例:修改第一个动物的价格 if (!animalData.isEmpty()) { animalData.get(0).set(2, "50.00"); System.out.println("\n修改后第一个动物的属性:"); System.out.println(animalData.get(0)); } } }
如果确实需要固定长度的二维数组
如果业务要求必须用String[][],可以先统计文件行数,再创建数组(注意要处理最大列数7):
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class FileReading { public static void main(String[] args) { List<String[]> tempList = new ArrayList<>(); int maxColumns = 7; // 你说最多7个属性 try (BufferedReader br = new BufferedReader(new FileReader("Animals.txt"))) { String line; while ((line = br.readLine()) != null) { String[] attributes = line.split(", "); // 如果行的属性不足7个,可以补空字符串或者null,根据需求调整 String[] paddedAttributes = new String[maxColumns]; System.arraycopy(attributes, 0, paddedAttributes, 0, attributes.length); tempList.add(paddedAttributes); } } catch (IOException e) { e.printStackTrace(); } // 转成二维数组 String[][] animalArray = tempList.toArray(new String[0][maxColumns]); // 测试打印 System.out.println("转换后的二维数组:"); for (String[] animal : animalArray) { for (String attr : animal) { System.out.print(attr + "\t"); } System.out.println(); } } }
小提示
- 如果你的文本文件里有的行分隔符是逗号后没有空格(比如
John,Dog,45.50),可以把split(", ")改成split("\\s*,\\s*"),这样能匹配逗号前后的任意空格,更鲁棒。 - 用try-with-resources的方式读取文件,JVM会自动帮你关闭流,避免忘记关闭导致的资源泄漏问题。
内容的提问来源于stack exchange,提问作者Alex Howard
相关产品推荐
相关产品推荐

