Android Studio read/write from .txt file, save path? - android

so im trying to write data that I recieve from a socket into text file and then read those data.
I have these 2 methods in my MainActivity (just tests to see how read and write from/into a file works) :
public void WriteBtn() {
// add-write text into file
try {
FileOutputStream fileout=openFileOutput("mytextfile.txt", MODE_PRIVATE);
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write("Test");
outputWriter.close();
//display file saved message
Toast.makeText(getBaseContext(), "File saved successfully!",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
public void ReadBtn() {
//reading text from file
try {
FileInputStream fileIn=openFileInput("mytextfile.txt");
InputStreamReader InputRead= new InputStreamReader(fileIn);
char[] inputBuffer= new char[256];
String s="";
int charRead;
while ((charRead=InputRead.read(inputBuffer))>0) {
// char to string conversion
String readstring=String.copyValueOf(inputBuffer,0,charRead);
s +=readstring;
}
InputRead.close();
Toast.makeText(getBaseContext(), s,Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
I call them with buttons but I was wondering, where does it save my "mytextfile.txt" ???

Take a look at Context.getExternalFilesDir() and pass it Environment.DIRECTORY_DOCUMENTS. That should give you the default output path for text files.
https://developer.android.com/reference/android/content/Context.html#getExternalFilesDir(java.lang.String)
EDIT
I just tested this. It looks like Context.openFileOutput() dumps everything, regardless of file type, to Conext.getFilesDir()
https://developer.android.com/reference/android/content/Context.html#getFilesDir()

Related

write text file in res/raw folder

I have a text file in folder res/raw name "pass.txt" and some data in it i want to delete this data and enter new data in it.... is it possible to write data on it?? otherwise what is correct path to store my text file so i can easily read/write data on it.... and what is the code to read and write data from it?? below is the code through which i can only read data from this text file
InputStream fr = getResources().openRawResource(R.raw.pass);
BufferedReader br = new BufferedReader(new InputStreamReader(fr));
String s=br.readLine().toString().trim();
Resources contained in your raw directory in your project will be packaged inside your APK and will not be writeable at runtime.
Look at Internal or External Data Storage APIs to read write files.
https://developer.android.com/training/basics/data-storage/files.html
you can use Android internal storage to Read and write file ... as res/raw is only Read only..you can not change content at runtime.
Here is the code:
Create file
String MY_FILE_NAME = “mytextfile.txt”;
// Create a new output file stream
FileOutputStream fileos = openFileOutput(MY_FILE_NAME, Context.MODE_PRIVATE);
// Create a new file input stream.
FileInputStream fileis = openFileInput(My_FILE_NAME);
Read from file:
public void Read(){
static final int READ_BLOCK_SIZE = 100;
try {
FileInputStream fileIn=openFileInput("mytextfile.txt");
InputStreamReader InputRead= new InputStreamReader(fileIn);
char[] inputBuffer= new char[READ_BLOCK_SIZE];
String s="";
int charRead;
while ((charRead=InputRead.read(inputBuffer))>0) {
// char to string conversion
String readstring=String.copyValueOf(inputBuffer,0,charRead);
s +=readstring;
}
InputRead.close();
Toast.makeText(getBaseContext(), s,Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
Write to file:
public void Write(){
try {
FileOutputStream fileout=openFileOutput("mytextfile.txt", MODE_PRIVATE);
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write("TEST STRING..");
outputWriter.close();
//display file saved message
Toast.makeText(getBaseContext(), "File saved successfully!",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}

Saving a bunch of integers to file android

So I have a bunch of EditText fields that I need the user to enter in. After this is done I want to save all the input-values to a file and make them loadable by clicking on them in another tab.
I'm kinda lost though.
I have about 5 EditText fields that I convert to ints (they are inputting ints) and then calculating different values from them. I want to save these values in int form. How do I achieve this easiest way? I'm only finding how to save strings.
If I want to save every click on the "calculate" button to a different file (if the user changes a input value and clicks calculate again I want a second file to be made with those values). How do I achieve creating a lot of files that are different (or the same if the button gets spammed).
Thirdly, how can I show what files there are to be loaded from the directory?
To write the text of all the edittext you have to use following code:
// write text to file
public void WriteBtn(String finalString) {
// add-write text into file
try {
FileOutputStream fileout=openFileOutput("mytextfile.txt", MODE_PRIVATE);
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write(finalString.toString());
outputWriter.close();
//display file saved message
Toast.makeText(getBaseContext(), "File saved successfully!",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
To read the text from file following code can be usefull:
// Read text from file
public String ReadBtn() {
//reading text from file
try {
FileInputStream fileIn=openFileInput("mytextfile.txt");
InputStreamReader InputRead= new InputStreamReader(fileIn);
char[] inputBuffer= new char[100];
String s="";
int charRead;
while ((charRead=InputRead.read(inputBuffer))>0) {
// char to string conversion
String readstring=String.copyValueOf(inputBuffer,0,charRead);
s +=readstring;
}
InputRead.close();
return s;
} catch (Exception e) {
e.printStackTrace();
return "";
}
}

how to write json data to a file in android

Can someone explain what is going wrong here I am using following function
public void WriteSettings(Context context, String data){
FileOutputStream fOut = null;
OutputStreamWriter osw = null;
try{
fOut = context.openFileOutput("schemas.json",Context.MODE_APPEND);
osw = new OutputStreamWriter(fOut);
osw.write(data);
osw.flush();
Toast.makeText(context, data+"Data",Toast.LENGTH_SHORT).show();
Toast.makeText(context, "Settings saved",Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
e.printStackTrace();
Toast.makeText(context, "Settings not saved",Toast.LENGTH_SHORT).show();
}
finally {
try {
osw.close();
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
And calling with once my http request is completed
JSONObject json_res = currentDFD.getJSONObject("result");
WriteSettings(getBaseContext(),json_res.toString());
The result is alerted in toast however not written to the file
the file is located in assets folder
thanks in advance
AFAIK You can't. The assets folder is read-only at runtime.
Pick a different location to save your data, see Data Storage in Android for more information.
The assets folder is like folders res, src, gen, etc. These are all useful to provide different files as input to build system to generate APK file for your app.
All these are read-only while your app is running. At run-time you can only write to SD card.

Android filewriting, reading

I have a dialog with spinners and an OK button. I also have an arraylist that is populated by the user selecting items in the spinners. I want the app to save the arraylist to a file and load it at every launch (because without saving the arraylist is always empty at launch).
So here is the code i am using. The saving should be okay, at least i get the Toast message saying Saving OK. This code is the OKbtn listener so when user clicks ok, an item is added to the arraylist and there comes this code:
if (assignArr.size() > 0)
{
String filename = "file.txt";
ArrayList<String> report = new ArrayList<String>();
for (int i=0; i<assignArr.size(); i++)
{
report.add(assignArr.get(i));
}
FileOutputStream fos;
try {
fos = openFileOutput(filename,Context.MODE_PRIVATE);
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject(report);
out.close();
Toast.makeText(MainActivity.this, "Saving OK", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I put the loading part to the beginning of the code, but i don't think it matters:
words = new ArrayList<String>(50);
try {
InputStream is = getResources().getAssets().open("file.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while((line = br.readLine()) != null)
{
words.add(line);
}
is.close();
}
catch (IOException e)
{
e.printStackTrace();
}
if (words.size() > 0)
{
for (int i=0; i<words.size(); i++)
{
assignArr.add(words.get(i));
Toast.makeText(MainActivity.this, "Loading OK", Toast.LENGTH_LONG).show();
}
}
In this case i never get the toast message.
One problem can be that where is the file created? Where in the emulator and where on the phone? And regarding the phone, is it created on the sd card or the phone memory?
I hope this is the right code to save and load an arraylist.
What is wrong with the code?
Update:
I replaced InputStream is = getResources().getAssets().open("file.txt"); withInputStream is = openFileInput("file.txt");
Now something happens. I write out the result of the saving and the loading into a toast message, which is weird:
Toast.makeText(MainActivity.this, "Saving OK + " + report, Toast.LENGTH_LONG).show();
Please take a look at it. The words on the bottom are partly hungarian names. So maybe the saving an arraylist to a file is the problem.
The file you create via openFileOutput is written into your app's private directory, which you can get using Context#getFilesDir() (usually it's /data/data/<your-app-package>/).
This directory has nothing to do with the assets folder.

write and read strings to/from internal file

I see a lot of examples how to write String objects like that:
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
but not how to read them back from internal application file. Most of examples assume specific string length to calculate byte buffer but I do not know what the length will be. Is there an easy way to do so? My app will write up to 50-100 strings to the file
Writing strings this way doesn't put any sort of delimiters in the file. You don't know where one string ends and the next starts. That's why you must specify the length of the strings when reading them back.
You can use DataOutputStream.writeUTF() and DataInputStream.readUTF() instead as these methods put the length of the strings in the file and read back the right number of characters automatically.
In an Android Context you could do something like this:
try {
// Write 20 Strings
DataOutputStream out =
new DataOutputStream(openFileOutput(FILENAME, Context.MODE_PRIVATE));
for (int i=0; i<20; i++) {
out.writeUTF(Integer.toString(i));
}
out.close();
// Read them back
DataInputStream in = new DataInputStream(openFileInput(FILENAME));
try {
for (;;) {
Log.i("Data Input Sample", in.readUTF());
}
} catch (EOFException e) {
Log.i("Data Input Sample", "End of file reached");
}
in.close();
} catch (IOException e) {
Log.i("Data Input Sample", "I/O Error");
}

Categories

Resources