从 Android Studio Java 中的文本文件读取

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30417810/
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-08-11 09:36:10  来源:igfitidea点击:

Reading from a Text file in Android Studio Java

javaandroid

提问by Tintinabulator Zea

I have a class QuoteBank that needs to read in a txt file with scanner but it is giving me a file not found exception

我有一个 QuoteBank 类需要用扫描仪读取一个 txt 文件,但它给了我一个文件未找到异常

java file is at app/src/main/java/nate.marxBros/QuoteBank.java

java 文件位于 app/src/main/java/nate.marxBros/QuoteBank.java

txt file is at app/src/main/assets/Quotes.txt

txt 文件位于 app/src/main/assets/Quotes.txt

the code is

代码是

File file = new File("assets/QuotesMonkeyBusiness.txt");
    Scanner input = null;
    try {
        input = new Scanner(file);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

Shouldnt this work just like any other java program? but it gives file not found exception

这不应该像任何其他 Java 程序一样工作吗?但它给出了找不到文件的异常

I've tried many things on this site like Android Studio Reading from Raw Resource Text Filebut that method does not work because i dont know how to pass in Context

我在这个网站上尝试了很多东西,比如 Android Studio 从原始资源文本文件中读取,但该方法不起作用,因为我不知道如何传入 Context

thanks for any help

谢谢你的帮助

updated code

更新代码

public class QuoteBank {
private ArrayList<ArrayList<QuoteBank>> bank;
private Context mContext;
private ArrayList<QuoteQuestion> monkeyBuisness;


public QuoteBank(Context context){
    mContext = context;
    InputStream is = null;
    try {
        is = mContext.getAssets().open("QuotesMonkeyBusiness.txt");
    } catch (IOException e) {
        e.printStackTrace();
    }

    ArrayList<QuoteQuestion> monkeyBuisness = parseFileToBank(is);
}

MainActivity

主要活动

public class MainActivity extends ActionBarActivity {
QuoteBank b = new QuoteBank(MainActivity.this);

采纳答案by AndyRoid

You should have a MainActivity.javaor some Activitywhich instantiates QuoteBank. You would want the constructor to take in a parameter of context:

你应该有一个MainActivity.java或一些Activity实例化QuoteBank. 您希望构造函数接受上下文参数:

Setup a private variable in QuoteBank.java:

在 中设置私有变量QuoteBank.java

private Context mContext;

Setup up the constructor:

设置构造函数:

public QuoteBank(Context context) {
   this.mContext = context;
}

Then instantiate it in your activity,

然后在您的活动中实例化它,

QuoteBank quoteBank = new QuoteBank(context);

The context variable can be called within an activity by the thiscommand or Activity.thiswhere you replace "Activity" with your activity name. Alternatively if you are within a fragment, you can get the context from the Viewobject inside your onCreateView(...)method. Usually by calling view.getContext().

上下文变量可以通过this命令在活动中调用,或者Activity.this在您用活动名称替换“活动”的地方调用。或者,如果您在片段内,则可以从方法View内的对象获取上下文onCreateView(...)。通常通过调用view.getContext().

Now in your method where you are grabbing the assets, you can use the context:

现在,在您获取资产的方法中,您可以使用上下文:

InputStream is = mContext.getAssets().open("QuotesMonkeyBusiness.txt")

Since you're using android studio you can either create a main(String[] args) { ... }method and run it or just start the emulator and have it use Log.d(...)to show output from the file.

由于您使用的是 android studio,您可以创建一个main(String[] args) { ... }方法并运行它,也可以启动模拟器并使用它Log.d(...)来显示文件的输出。

Alternatively you can use the following method as well:

或者,您也可以使用以下方法:

AssetManager am = mContext.getAssets();
InputStream is = am.open("QuotesMonkeyBusiness.txt");

It might also make sense to have QuoteBankas a singleton instance, that might increase efficiency although it all depends on your requirements, maybe something like:

QuoteBank作为单例实例也可能有意义,这可能会提高效率,尽管这完全取决于您的要求,可能类似于:

List<String> allTextLines = QuoteBank.readFromFile(context, path_to_file);

And then in your QuoteBank.javaclass you can have a method like so:

然后在你的QuoteBank.java课堂上你可以有一个这样的方法:

/**
* Created by AndyRoid on 5/23/15.
*/
public class QuoteBank {

private Context mContext;

public QuoteBank(Context context) {
    this.mContext = context;
}

public List<String> readLine(String path) {
    List<String> mLines = new ArrayList<>();

    AssetManager am = mContext.getAssets();

    try {
        InputStream is = am.open(path);
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String line;

        while ((line = reader.readLine()) != null)
            mLines.add(line);
    } catch (IOException e) {
        e.printStackTrace();
    }

    return mLines;
}

}

}

and then in my MainActivity.javaclass I have the following:

然后在我的MainActivity.java课上我有以下内容:

/**
 * Created by AndyRoid on 5/23/15.
 */
public class MainActivity extends AppCompatActivity {

public static final String TAG = MainActivity.class.getSimpleName();

public static final String mPath = "adventur.txt";
private QuoteBank mQuoteBank;
private List<String> mLines;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mQuoteBank = new QuoteBank(this);
    mLines = mQuoteBank.readLine(mPath);
    for (String string : mLines)
        Log.d(TAG, string);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

This is my project structure:

这是我的项目结构:

enter image description here

在此处输入图片说明

This is the adventur.txtfile I downloaded from a random database:

这是adventur.txt我从随机数据库下载的文件:

file

文件

This is my log output:

这是我的日志输出:

enter image description here

在此处输入图片说明



UPDATE: Why you should not use a Scanner in Android

更新:为什么你不应该在 Android 中使用扫描仪

From the official documentation:

来自官方文档:

http://developer.android.com/reference/java/util/Scanner.html

http://developer.android.com/reference/java/util/Scanner.html

This class is not as useful as it might seem. It's very inefficient for communicating between machines; you should use JSON, protobufs, or even XML for that. Very simple uses might get away with split(String). For input from humans, the use of locale-specific regular expressions make it not only expensive but also somewhat unpredictable. The Scanner class is not thread-safe.

这个类并不像看起来那么有用。机器之间的通信非常低效;为此,您应该使用 JSON、protobufs 甚至 XML。使用 split(String) 可能会非常简单的使用。对于来自人类的输入,使用特定于语言环境的正则表达式不仅成本高昂,而且有些不可预测。Scanner 类不是线程安全的。



FINAL NOTE:

最后说明:

I highly suggest you read up on the documentation of all the objects used here so you can understand the process.

我强烈建议您阅读此处使用的所有对象的文档,以便您了解该过程。

回答by Elltz

Context.getResources().getAssets().open("QuotesMonkeyBusiness.txt");returns an InputStreamthe rest you can take it from there

Context.getResources().getAssets().open("QuotesMonkeyBusiness.txt");返回一个InputStream你可以从那里拿走的其余部分

Edit

编辑

because i dont know how to pass in Context

因为我不知道如何传入 Context

Contextis everywhere actually if you have a Viewyou can get a Context, if you an Activityyou can get Contextso find it

Context实际上无处不在,如果您有一个,View您可以获得一个Context,如果您有一个,Activity您就可以Context找到它

Hope it helps

希望能帮助到你

回答by Sayed Muhammad Idrees

A simple Answer For A Simple Question.

一个简单问题的简单答案。

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 use the Function to Read a External File.

只需使用函数读取外部文件。