简体   繁体   中英

Reading from a Text file in Android Studio Java

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.

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.

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

Edit

because i dont know how to pass in Context

Context is everywhere actually if you have a View you can get a Context , if you an Activity you can get Context so find it

Hope it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM