繁体   English   中英

我如何简单地读取我创建的 .txt 文件并计算其行数

[英]How do I simply read a .txt file that I created and count its lines

我对 Android Studio 很陌生,但我有两个问题。

因此,目前我正在使用一种方法从 .txt 文件中获取行并将其转换为 ArrayList。 我正在使用 FileReader 和 LineNumberReader。 当我运行该程序时,即使此代码在 Eclipse 上工作,也会激活捕获。

我的问题: 1. 我目前将 .txt 文件存储在资产的原始文件夹中。 这是放置它的正确位置吗? 2.我使用的位置是“\\res\\raw\\city.txt”,是不是我调用的文件有误?

这是我的代码(在 Android Studio 中)以获得更多上下文:

    //Method to take a file and convert into an ArrayList
    private ArrayList<String> txtArray(String fileLoc) throws IOException {
        int n = 22;

        File file = new File(fileLoc);

        //Counts how many lines are in the system
        try {
            FileReader fr = new FileReader(fileLoc);
            LineNumberReader lr = new LineNumberReader(fr);

            lr.skip(Long.MAX_VALUE);
            n = lr.getLineNumber();

            Toast errorToast3 = Toast.makeText(getActivity(), "the Number of lines is " + n, Toast.LENGTH_SHORT);
            errorToast3.show();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Toast errorToast5 = Toast.makeText(getActivity(), "Fuk " + n, Toast.LENGTH_SHORT);
            errorToast5.show();
        }

        Toast errorToast3 = Toast.makeText(getActivity(), "Still ok here " + n, Toast.LENGTH_SHORT);
        errorToast3.show();

        //Takes lines from the text file and converts into Array List
        Scanner kb = new Scanner(new File(fileLoc));

        Toast errorToast7 = Toast.makeText(getActivity(), "Pls work " + n, Toast.LENGTH_SHORT);
        errorToast7.show();

        ArrayList<String> test = new ArrayList<String>();
        for (int i = 0; i < n; i++) {
            test.add(kb.nextLine());
            //kb.next();
        }

        return test;

谢谢你的帮助!

  1. 您可能需要内部存储
  2. 路径似乎错误,因为它使用了错误的斜杠并且还使用了绝对路径(以/开头)。 试试res/raw/city.txt

您也可以查看Files.lines().collect(Collectors.toList())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM