Issues in reading of data from text file Android Development - android

i have been experiencing problem reading data from text files which resides in my internal storage of my mobile phone. My code is as below:
public void recommend(View view) {
Context context = getApplicationContext();
String filename = "SendLog.txt";
TextView tv = (TextView)findViewById(R.id.textView134);
try {
FileInputStream fis = context.openFileInput(filename);
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line).append("\n");
tv.getText();
tv.setText(line);
}
} catch (IOException e) {
e.getStackTrace();
}
I'm not getting any data input to my mobile phone. My "SendLog.txt" file reside in /storage/emulated/0/SendLog.txt directory. Anyone can assist me? I want to read everything from the text file and display in textView134. Anyone can assist?
Thank you in advance!

"/storage/emulated/0/SendLog.txt" is located on the External Storage, not the internal.
Instead of context.openFileInput(filename) you should be using Environment.getExtenalStorageDirectory() for example,
FileInputStream fis = new FileInputStream(new File(Environment.getExtenalStorageDirectory(), filename));
Though you will need to handle possibilities such as the External Storage being unavailable / unmounted.
You will also need the manifest permission to read external storage, or alternately to write it if you plan to do that as well (you only need one of the two, as write implies read).

You are building a string using stringbuilder but instead are settexting line. The result is last line in file, which may be an empty line

Related

Reading from a file in android studio and testing on phone

I am trying to read from a text file in Android Studio.
FileInputStream fin=new FileInputStream("./quizdata.txt");
int size = fin.available();
byte[] buffer = new byte[size];
fin.read(buffer);
fin.close();
Now, when I run this test on a phone connected to my computer, android doesn't find this file. My best guess is, the file should be on my phone and not on the computer.
If yes, at what location in the phone shall I store this file?
Thanks
You need to add the file to your Android code, not to your Android phone. You need to save it either in assets folder (src/main/assets) or raw folder (src/res/raw).
If you save it in the raw folder, you can read it with:
// you don't need to have the file extension. Note that you can't use uppercase
InputStream is = Context.getResources().openRawResource(R.raw.quizdata);
If you save it in asset folder, you can read it with:
AssetManager am = context.getAssets();
InputStream is = am.open("quizdata.txt");
To get all the lines in the file, you can use the following code:
// getting all the line
BufferedReader r = new BufferedReader(new InputStreamReader(is));
StringBuilder quiz = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
quiz.append(line).append('\n');
}

How to read from a file in my application on android?

I created a file on my pc, and I want my app to read from it.
How do I read from that file in my app?
Thanks
Put the file in assets/ (e.g., app/src/main/assets/ in a typical Android Studio project). Then use open() on an AssetManager to get an InputStream on that content. You can get an AssetManager from your Activity or other Context by calling getAssets().
Move your file to card and add path instead of "file.txt"
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,"file.txt");
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
}catch (IOException e) {
//You'll need to add proper error handling here
}
//Find the view by its id
TextView tv = (TextView)findViewById(R.id.text_view);
//Set the text
tv.setText(text);
it example best if you want to read text

Can't access file in assets subfolder

Im developing an app using Andriod Studio and I´ve got some problemns accessing my assets subfolders.
When I try to access a file, say file1, in the assets root folder, like this
AssetManager assetMng = getAssets();
InputStream textoInput;
String path = "file1.txt";
try {
textoInput = assetMng.open(path);
BufferedReader r = new BufferedReader(new InputStreamReader(textoInput));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
} catch (IOException e){
lista.add("Exception: " + e.toString());
e.printStackTrace();
}
I get the text successfuly. But when I change "file1.txt" to "sub\file2.txt" I get an file not found execption.
Anyone has any idea what is going on? Am I missing something?
Thanks!
Android is linux based - use a forward slash not backslash. So, sub/file2.txt

Storing txt files

I'm working on a sort of a magazine app which contains a lot of txt files which I read the text from (only read not write) , And I'm a little bit confused , I have read the documentation about file storage but still don't seem to get the right way to store my txt files. Should those files be in the the Assets? Is it possible to have a folders inside the assets? And if yes how can I acsses these folders?
res/raw will be a good place to put them. If you placed a text file named "article.txt" in the raw resource folder, you would start by putting the file into an InputStream like this (note that "ctx" is a Context which an Activity inherits from):
InputStream inputStream = ctx.getResources().openRawResource(R.raw.article);
Then you turn the InputStream into a String. This can be done about 1000 different ways. Here's one way:
InputStreamReader inputreader = new InputStreamReader(inputStream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
StringBuilder text = new StringBuilder();
try {
while (( line = buffreader.readLine()) != null) {
text.append(line);
text.append('\n');
}
} catch (IOException e) {
return null;
}
String fileContentsStr = text.toString();
Here is a fully working method (using the above conversion technique) to turn a text file from the raw folder into a string. Which I got from this post Android read text raw resource file.
public static String readRawTextFile(Context ctx, int resId)
{
InputStream inputStream = ctx.getResources().openRawResource(resId);
InputStreamReader inputreader = new InputStreamReader(inputStream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
StringBuilder text = new StringBuilder();
try {
while (( line = buffreader.readLine()) != null) {
text.append(line);
text.append('\n');
}
} catch (IOException e) {
return null;
}
return text.toString();
}
Using "article.txt" still, you would call this method from an Activity like so:
readRawTextFile(this, R.raw.article);

Load a simple text file in Android Studio

Got a brand new project using Google's new Android Studio IDE.
I'm trying to load a simple text file using an InputStreamReader. I'm getting a file not found exception. Now there isn't any assets/ folder. I tried to create one and add my file at many different spots (at the root of the project, at the root of the .java file, etc...) I've tried to move the file around but still get the file not found.
Now that never was a problem using Eclipse as there is an assets folder created by any template.
Does anyone know where should the assets go to or how to load them?
Here is the code used, it fails at .open():
InputStream iS = resources.getAssets().open("bla.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(iS));
I also tried this code in Eclipse, it works and the file contents get loaded. So there's probably a step needed in Android Studio.
Step 1:
Open in Name_Project-Name_Project.iml file.
See the line :
option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets"
Step 2:
Create a sub-folder "assets" in main folder.
Step 3:
Put file in this folder.
Step 4:
Load it. Done.
The correct answer didn't work for me exactly.
This works:
Go to Project view and then go to app/src/main and create new directory assets
to load the file:
InputStream is = getApplicationContext().getAssets().open("bla.txt");
or:
InputStream is = context.getAssets().open("bla.txt");
and then convert it to string at any way you want, examples here
detailed video of how to do it (not mine)
This code will work for you.It will fetch all data from file.
public class Quiz extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
try {
PlayWithRawFiles();
} catch (IOException e) {
Toast.makeText(getApplicationContext(),
"Problems: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}// onCreate
public void PlayWithRawFiles() throws IOException {
String str="";
StringBuffer buf = new StringBuffer();
InputStream is = this.getResources().openRawResource(R.raw.ashraf);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
if (is!=null) {
while ((str = reader.readLine()) != null) {
buf.append(str + "\n" );
}
}
is.close();
TextView tv=(TextView)findViewById(R.id.tv1);
tv.setText(buf.toString());
}//
}
//Compiled all the codes available in the internet, and this works perfectly fine for reading data from a textfile
//Compiled By: JimHanarose
ArrayList<String> data_base = new ArrayList<String>();
String text = "";
try {
InputStream is = getApplicationContext().getAssets().open("g.txt"); //save this .txt under src/main/assets/g.txt
int size = is.available();
StringBuffer buf = new StringBuffer();
byte [] buffer = new byte[size];
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
if (is!=null) {
while ((text = reader.readLine()) != null) {
data_base.add(text.toString()); //create your own arraylist variable to hold each line being read from g.txt
}
}
is.close();
} catch (IOException e) {
e.printStackTrace();
}

Categories

Resources