我正在尝试自学如何将原始资源文本文件读入多维数组,到目前为止还没有太多运气。这是原始文本文件:
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) 我得到 p>
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/