从Android Studio Java中的文本文件中读取 [英] Reading from a Text file in Android Studio Java

查看:163
本文介绍了从Android Studio Java中的文本文件中读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类QuoteBank需要读取带有扫描程序的txt文件,但是它给了我一个未找到异常的文件



java文件是
app / src / main / java / nate.marxBros / QuoteBank.java



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



代码是

 文件文件=新文件(资产 /QuotesMonkeyBusiness.txt); 
扫描仪输入= null;
try {
input = new Scanner(file);
} catch(FileNotFoundException e){
e.printStackTrace();
}

这不能像其他任何java程序一样工作吗?但它给文件找不到异常



我在这个网站上尝试了很多东西,比如


此课程不是看起来很有用。在机器之间进行通信效率非常低;你应该使用JSON,protobufs甚至XML。非常简单的用法可能会脱离split(String)。对于来自人类的输入,使用特定于语言环境的正则表达式使其不仅昂贵而且有些不可预测。
Scanner类不是线程安全的。







最后注意:



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


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

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

txt file is at 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

I've tried many things on this site like Android Studio Reading from Raw Resource Text File but that method does not work because i dont know how to pass in 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);

解决方案

You should have a MainActivity.java or some Activity which instantiates QuoteBank. You would want the constructor to take in a parameter of context:

Setup a private variable in 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 this command or Activity.this where you replace "Activity" with your activity name. Alternatively if you are within a fragment, you can get the context from the View object inside your onCreateView(...) method. Usually by calling 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.

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 QuoteBank as a singleton instance, that might increase efficiency although it all depends on your requirements, maybe something like:

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

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

/**
* 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.java class I have the following:

/**
 * 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:

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

This is my log output:


UPDATE: Why you should not use a Scanner in Android

From the official documentation:

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.


FINAL NOTE:

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

这篇关于从Android Studio Java中的文本文件中读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆