Reading from a file in android studio and testing on phone - android

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');
}

Related

Get a StreamReader from a resource file in Xamarin Android

I have a text file named dictionary.txt in the Resource folder of a Xamarin Android project. I need a StreamReader to read the file. I improvised the following code to get it:
Stream res = Resources.OpenRawResource(Resource.Raw.dictionary);
MemoryStream ms = new MemoryStream();
res.CopyTo(ms);
ms.Position = 0;
StreamReader stream = new StreamReader(ms, Encoding.UTF8, true);
Is there a better way to get a usable StreamReader from a resource file? It seems converting and copying the stream several times may make the code slow.
You need to mark your file as an AndroidAsset:
And then yes you can use something similar to this code:
AssetManager assets = ApplicationContext.Assets;
Stream stream = assets.Open(ConfigurationFilePath);
// Play with the stream and dispose it.
I explained something similar in an old article: Xamarin - Loading configuration file.
you can use the using statement.
Try this code:
try{
var _file = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "dictionary.txt");
if(_file == null || !File.Exists(_file)){
//file does not exist
}
string FileData = string.Empty;
using(var reader = new StreamReader(_file, true)){
string line;
while((line = reader.ReadLine()) != null)
{
FileData = line;
}
}
//
}catch(Exception ex){
//Exception error
}

Issues in reading of data from text file Android Development

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

Read textfile in Android - where to place the file

Where do I place a certain textfile in the project of Eclipse if I want to read the contents?
Which objects should I use?
I tried with the following syntax but the file could not be found? Maybe the computers filesystem is used in this case?
private void read() throws FileNotFoundException, IOException {
File file = new File("test.txt");
FileReader fileReader = new FileReader(file);
BufferedReader buffReader = new BufferedReader(fileReader);
String[] stringBuffer = new String[2];
String line;
int i = 0;
while ( (line = buffReader.readLine()) != null) {
stringBuffer[i] = line;
i++;
}
System.out.println(stringBuffer[0] + stringBuffer[1]);
}
My idea was that the search begins in the rootfolder of the project but I guess its completely wrong because the computers filesystem is used?
If you want to bundle this file with your Android application at build time, you have two choices: the /raw folder under /res or the /assets folder. You should place your file here and access it in the correct way for the chosen directory. For more information, read more about the built in folders for an Android project here.
For an example, if you store your text file in /assets/, which is most likely the correct place for a text file, you need to access the contents of the file using AssetManager. Let's assume you created a file called:
/assets/test.txt
You can access the file as such, assuming that you are doing this from an Activity, so that the this keyword points to your Activity:
AssetManager assetManager = this.getResources().getAssets();
InputStream input = assetManager.open("test.txt");
You can now use that input stream to read from the file in a way similar to how you have done in your original question. You can use that InputStream to create a BufferedReader, as below, assuming your text content is encoded in UTF-8:
BufferedReader br =
new BufferedReader(new InputStreamReader(input, "UTF-8"));

Can we access any files in phone directory after an apk file has been installed?

I'm developing an Android App, a Book. It is a long with many contents paragraph. I'm thinking about dividing that paragraph into small paragraphs and store them in database using SQLite Database by creating a table with these attributes: ID,Title,Path,... I store those small paragraph in text files and copy them into phone directory. I want to ask that can we access those files by their path in phone directory? if yes then how to do it?
//Find the directory for the SD Card using the API
//*Don't* hardcode "/sdcard"
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');
}
}
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);
I hope its useful to you..

how to read binary .AMF file in android

I am new to android and I want to read a binary file extension .AMF file.
I really need your help this is really urgent.
Thanks in advance.
I made a folder in RES named raw. Here is the code I tried, it says file not found.
FileInputStream in = new FileInputStream("R.raw.hello.txt");
StringBuffer inLine = new StringBuffer();
InputStreamReader isr = new InputStreamReader(in);
BufferedReader inRd = new BufferedReader(isr);
String text;
while ((text = inRd.readLine()) != null) {
inLine.append(text);
inLine.append("\n");
}
in.close();
return inLine.toString();
From the Andoid SDK:
To read a file from internal storage:
Call openFileInput() and pass it the name of the file to read. This returns a FileInputStream.
Read bytes from the file with read().
Then close the stream with close().
Tip: If you want to save a static file in your application at compile time, save the file in your project res/raw/ directory. You can open it with openRawResource(), passing the R.raw. resource ID. This method returns an InputStream that you can use to read the file (but you cannot write to the original file).
InputStream input = getResources().openRawResource(R.raw.hello.txt);

Categories

Resources