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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26634463/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 10:17:19  来源:igfitidea点击:

Reading from a raw resource text file

javaandroid

提问by John

I'm trying to keep a .txt file in my res\raw file in Android Studio and read/parse the file. I have a file "my_file.txt" in a folder called "raw" that I created in the "res" directory (that I didn't create).

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

Here's what I think my main issue is: When creating the File object (to use with the Scanner object), what path should I pass in for my text file?

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

Here's my code:

这是我的代码:

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
        }
    }
}

回答by Woodi_333

Think you are looking for something along the lines of

认为你正在寻找类似的东西

InputStream is = ctx.getResources().openRawResource(res_id);

Where ctx is a instance of Context

其中 ctx 是 Context 的一个实例

回答by Panther

I suggest you put it in assetsfolder under the src/mainfolder. Then you can use the getAssetsmethod to retrieve the file like this

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

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

If the folder does not exists, create one :-/

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

回答by Sayed Muhammad Idrees

or You can use this Function

或者您可以使用此功能

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;
}

just past in the path Location.

刚刚过去的路径位置。