java - 如何使用 FileReader 引用我的原始 txt 文件?

标签 java android arrays multidimensional-array java.util.scanner

我正在尝试自学如何将原始资源文本文件读入多维数组,到目前为止还没有太多运气。这是原始文本文件:

ken todd
stuart brian
bob stewart
orange apple

green red

我的代码如下所示。

   public void LoadFromFile (){

        //  int fileId = (getResources().getIdentifier("text_file",
         //        "raw", getPackageName()));
        Scanner scan = new Scanner(new FileReader(R.raw.text_file);
        // initialises the scanner to read the text_file

        String[][] entries = new String[6][2];
        // creates a 2d array with 6 rows and 2 columns.

        int i = 0;
        while (scan.hasNextLine()) {
            entries[i] = scan.nextLine().split("\\s+");
            i++;
        }
        //loops through the file and splits on a space

        for (int row = 0; row < entries.length; row++) {
            for (int col = 0; col < entries[0].length; col++) {
                if (entries[row][col] != null) {
                    System.out.print(entries[row][col] + " ");
                }
            }
            if (entries[row][0] != null) {
                System.out.print("\n");
            }
        }
        //prints the contents of the array that are not "null"
    }

我在扫描仪线路上遇到错误。特别是 FileReader(R.raw.text_file) 我得到

Cannot resolve constructor 'FileReader(int)'

显然,FileReader 正在寻找一个 int,我尝试通过将文件 ID 放入一个 int 变量中,然后在 FileReader 中使用该 int 变量来实现此目的,但这也不起作用。

int fileId = (getResources().getIdentifier("text_file", 
        "raw", getPackageName()));
Scanner scan = new Scanner(new FileReader(fileId);

它给了我同样的错误

Cannot resolve constructor 'FileReader(int)'

我在这里做错了什么?有人知道如何将文件放入数组中吗?

干杯

空气修复

最佳答案

您可以使用 openRawResource(int) 读取原始资源。这将为您提供一个 InputStream,您可以用 InputStreamReader 包装它。 ,然后用 BufferedReader 包裹起来。然后您可以使用 readLine()在 BufferedReader 上获取行。

关于java - 如何使用 FileReader 引用我的原始 txt 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36439102/

相关文章:

javascript - 使用数组值创建嵌套对象

java - Swing: Action 监听器的作用

java - 有没有办法使用 ACTION_SEND 在 google plus 上发布多张图片

android - 无法在 Android 谷歌浏览器浏览器中通过谷歌键盘输入

android - Android 6 中 Qt 5.6 QSsqlSocket 的问题

java - 在二维数组中找到到角点的最短路径

java - 找不到任何可执行的 java 二进制文件

java - 运算符 && 不能应用于 boolean,char

AndroidHttpClient 关闭后无法 getEntity().getContent()

c - 如何在 C 中定义和使用位数组?