JDS
JDS

Reputation: 16978

Android read in a .txt file packaged with app

I want to be able to read in a file, myFile.txt, that I ship with my app, either in the assets folder, the res/raw folder, where ever, it does not matter.

BUT! I do not want an InputStream of that file... I want to be able to do something like:

while ((reader = is.readLine()) != null) { ... }

I've searched around and found stuff that was close but not really what I'm looking for..

Thank you for any help.

EDIT - some code I was trying:

InputStream in = this.mCtx.getResources().openRawResource(R.raw.myFile);
Reader is = new BufferedReader(new InputStreamReader(in, "UTF8"));

(now what? The Reader class doesn't have a readLine() method)

Upvotes: 1

Views: 255

Answers (6)

FrancescoAzzola
FrancescoAzzola

Reputation: 2654

I think you should use something like that:

BufferedReader in = new BufferedReader(new     InputStreamReader(activity.getAssets().open("yourfile")));

StringBuilder buffer = new StringBuilder(); while ((line = in.readLine()) != null) buffer.append(line).append('\n');

And in your assets dir simply put your file without .txt extension. Hope this help you.

Upvotes: 0

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33534

Use these steps to get it done....

File f = new File("/sdcard/MyFolder/MyFile.txt");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);

StringBuilder sb = new StringBuilder();
String str = new String();

while((br.readLine())!=null){


   sb.append(br.readLine());  


 }

str = sb.toString();

Upvotes: 0

Name is Nilay
Name is Nilay

Reputation: 2783

You can store the file in sdcard and specify its location in "file_path" in below code:

File selectedFile = new File("file_path");
FileInputStream fstream = new FileInputStream(selectedFile);
BufferedReader reader = new BufferedReader(new InputStreamReader(fstream));

And then

while ((strLine = reader.readLine()) != null)
{
        //Do Stuff Here
}

Upvotes: 1

Rajesh J Advani
Rajesh J Advani

Reputation: 5710

Just change

Reader is = new BufferedReader(new InputStreamReader(in, "UTF8"));

to

BufferedReader is = new BufferedReader(new InputStreamReader(in, "UTF8"));

BufferedReader has a readLine() method. You're unnecessarily upcasting to Reader and losing the additional features.

Upvotes: 4

nandeesh
nandeesh

Reputation: 24820

use BufferedReader instead of Reader for definition.

BufferedReader is = new BufferedReader(new InputStreamReader(in, "UTF8"));

Bufferedreader has readline method but not reader

Upvotes: 1

Marc-Christian Schulze
Marc-Christian Schulze

Reputation: 3254

What about

BufferedReader reader = new BufferedReader(new BufferedInputStream(is));

Edit: Sorry - my fault. Just stick with the BufferedReader. Opening a ressource can be done with

InputStream is = getClass().getResourceAsStream("/org/example/res/my_file.txt");

See Class#getResourceAsStream)

Upvotes: 0

Related Questions