从原始资源文本文件中读取

时间:2014-10-29 15:33:08

标签: java android

我试图将.txt文件保存在Android Studio的res \ raw文件中并读取/解析该文件。我有一个文件" my_file.txt"在名为" raw"的文件夹中我在" res"目录(我没有创建)。

我认为我的主要问题是:创建File对象(与Scanner对象一起使用)时,我应该为我的文本文件传入哪条路径?

这是我的代码:

private void readFile(){
    Scanner scanner = null;
    try {
        scanner = new Scanner(new File("\\res\\raw\\my_file.txt"));  //I've also tried without the .txt extension
        Log.v("readFile->try","Trying to read file.");
    }catch(Exception e)
    {
        //Send error message.
    }
    if(scanner != null) {
        while (scanner.hasNext()) {
            String[] line = scanner.nextLine().split("\t");
            //Process string here
        }
    }
}

3 个答案:

答案 0 :(得分:5)

认为你正在寻找符合

的内容
InputStream is = ctx.getResources().openRawResource(res_id);

其中ctx是Context的实例

答案 1 :(得分:2)

我建议你把它放在assets文件夹下的src/main文件夹中。然后,您可以使用getAssets方法检索此文件

 InputStream in = (Activity)getContext().getAssets().open("my_file.txt")

如果文件夹不存在,请创建一个: - /

答案 2 :(得分:0)

或者您可以使用此功能

private String readFile()
{
String myData = "";
File myExternalFile = new File("assets/","log.txt");
try {
    FileInputStream fis = new FileInputStream(myExternalFile);
    DataInputStream in = new DataInputStream(fis);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));

    String strLine;
    while ((strLine = br.readLine()) != null) {
        myData = myData + strLine + "\n";
    }
    br.close();
    in.close();
    fis.close();
 } catch (IOException e) 
    {
         e.printStackTrace();
    }
   return myData;
}

就在路径Location中。

相关问题