如何通过java获取txt的列内容

String pathname = "F:\\Calibration.txt";

try (FileReader reader = new FileReader(pathname);

    BufferedReader br = new BufferedReader(reader)) {

        String line;

        while ((line = br.readLine()) != null) {

            String[] split = line.split(",");

            System.out.println(split[0]);

        }

此代码可以获取第一列的内容

,但列不固定。

我想 - 按列数自动获取每列的数据

不使用像这样的修复数字 split[fixNumber]


27311,28841,30577,31583,0

26401,28046,30234,31255,50

25495,27263,29891,30926,100

24594,26494,29548,30597,150

23696,25737,29206,30269,200

这是 Calibration.txt 的内容


预期输出:


27311 26401 25495 24594 23696

colmun 不固定,我不想使用 split[0] 或 (split[1] split[2]...)


这是我的新代码:


  List<String> list = new ArrayList();

  String pathname = "F:\\Calibration.txt";

  try (FileReader reader = new FileReader(pathname);

    BufferedReader br = new BufferedReader(reader)) 

{

        String line;

        while ((line = br.readLine()) != null) {

            list.add(line);

       }


       for(int i = 0; i < list.size(); i++) {

           System.out.println(i);

                for(String a : list){

                    String[] regex = a.split(",");

                    System.err.println(regex[i]);


                }

            }


慕田峪7331174
浏览 128回答 1
1回答

HUH函数

假设您已经阅读了文件并将所有行存储在ArrayList您完成的文件中。&nbsp;List<String> list = new ArrayList();&nbsp; String pathname = "F:\\Calibration.txt";&nbsp; try (FileReader reader = new FileReader(pathname);&nbsp; &nbsp; BufferedReader br = new BufferedReader(reader))&nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; String line;&nbsp; &nbsp; &nbsp; &nbsp; while ((line = br.readLine()) != null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; list.add(line);&nbsp; &nbsp; &nbsp; &nbsp;}&nbsp;}如果你的第一行是27311,28841,30577,31583,0然后在这一行中,第 1 列(或索引 0)的值为 27311,第 2 列 =28841,第 3 列 =30577 等等..如果你想要第 nth(或 n-1 索引)行的第 ith(或 i-1 索引)列,你需要执行以下操作:String row = list.get(n-1); //row nString[] columns = row.split(",");//this gives you the columns//Now access any columnString col1 = columns[0];String colI = columns[i-1];现在,根据您的预期输出,您需要所有行的第一列。因此,您需要迭代列表,拆分它们并获取第一列。//iterate the listfor(String line : list){&nbsp; &nbsp; String[] columns = line.split(",");&nbsp; &nbsp; String col0 = columns[0];&nbsp; &nbsp; System.out.println("column 1 : "+col0);}如果您只想要每一行的第一列,另一种方法是使用正则表达式删除其他列和逗号。//iterate the listfor(String line : list){&nbsp; &nbsp; String col0 = line.replaceFirst("\\s*,.*", "");&nbsp; &nbsp; System.out.println("column 1 : "+col0);}要打印所有列,您还需要遍历列数组,如下所示。//iterate the list&nbsp; &nbsp; for(String line : list){&nbsp; &nbsp; &nbsp; &nbsp; String[] columns = line.split(",");&nbsp; &nbsp; &nbsp; &nbsp; for(int i =0; i<columns.length; i++)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println("column "+ i +": "+columns[i]);&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java