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);
There are several ways to read a plain text file in Java e.g. you can use FileReader, BufferedReader, or Scanner to read a text file. Every utility provides something special e.g. BufferedReader provides buffering of data for fast reading, and Scanner provides parsing ability.
You can open a TXT file with any text editor and most popular web browsers. In Windows, you can open a TXT file with Microsoft Notepad or Microsoft WordPad, both of which come included with Windows. To open a TXT file with Notepad, select File → Open....
Step 1: We will use InputStream to open the file and we will stream the data into it. Step 2: Create a variable to store the size of the file. Step 3: Create a buffer of the size of the file. Step 4: We will read the inputStream file into the buffer.
We can use Files class to read all the contents of a file into a byte array. Files class also has a method to read all lines to a list of string.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With