逐行从文本文件中获取输入

时间:2018-03-05 21:28:50

标签: java input text-files

我有一个文本文件,其中的数据如下所述。

3
4
5
6

现在我想创建一个函数,其中我首先取值 3 ,然后创建另一个函数,其中我需要值 4

我有这个代码逐行读取文件。但我的问题是如何访问每行中的整数然后将其存储在任何变量中,以便我可以在我的函数中使用它?

  try {

        File f = new File("src/txt.txt");

        BufferedReader b = new BufferedReader(new FileReader(f));

        String readLine = "";

        System.out.println("Reading file using Buffered Reader");

        while ((readLine = b.readLine()) != null) {


            System.out.println(readLine);


        }

    } catch (IOException e) {
        e.printStackTrace();
    }

1 个答案:

答案 0 :(得分:0)

你可以尝试这样的事情:

public class Main {

    static List<Integer> integers = new ArrayList<>();
    public static void main(String[] args) {
        try(BufferedReader reader = new BufferedReader(new FileReader(Paths.get("filepath").toFile()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                try {
                    integers.add(Integer.valueOf(line));
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                    integers.add(0);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

通过此功能,您可以在列表中成功阅读所有可用于任何目的的数字。

相关问题