首页 > 解决方案 > Java如何逐行读取文件并更改行的特定部分

问题描述

我是java新手,老师给了我们一个项目作业。我必须实现逐行读取文件,以逗号分割行并将部分存储在多维数组中,更改行的特定部分(我想更改数量)。给定文件:

product1,type,amount
product2,type,amount
product3,type,amount
product4,type,amount
product5,type,amount

我尝试了此代码,但无法更改特定部分。

BufferedReader reader;
        int j=0;
        int i=0;
        try {
            reader = new BufferedReader(new FileReader("file.txt"));
            String line = reader.readLine();


            while (line != null) {
                j++;
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        String total_length[][]=new String[j][3];

            try {
            reader = new BufferedReader(new FileReader("file.txt"));
            String line = reader.readLine();


            while (line != null) {
                line = reader.readLine();
                String[] item = line.split(",");
                total_length[i][0]=item[0];
                total_length[i][1]=item[0];
                total_length[i][2]=item[0];
                i++;
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

非常感谢!

标签: javafile

解决方案


首先,您需要读取文件。有很多方法可以做到这一点,其中之一是:

BufferedReader s = new BufferedReader(new FileReader("filename"));

这允许您执行 s.readLine() 逐行读取它。您可以使用 while 循环将其读取到最后。请注意,如果到达文件末尾, readLine 将返回 null。然后,对于每一行,你想用昏迷来分割它们。您可以使用字符串的拆分方法:

line.split(",");

将它们放在一起,并为 IOException 使用 try-catch,您将得到:

    List<String[]> result = new ArrayList<>();
    try (BufferedReader s = new BufferedReader(new FileReader("filename"))) {
        String line;
        while ((line = s.readLine()) != null) {
            result.add(line.split(","));
        }
    } catch (IOException e) {
        // Handle IOExceptions here
    }

如果你最后真的需要一个二维数组,你可以这样做:

    String[][] array = new String[0][0];
    array = result.toArray(array);

然后您已经以您想要的格式读取了文件,您现在可以修改您解析的数据。


推荐阅读