package com.test;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final String TAG = MainActivity.class.getName();
private static final String FILENAME = "myFile.txt";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String textToSaveString = "Hello Android";
writeToFile(textToSaveString);
String textFromFileString = readFromFile();
if ( textToSaveString.equals(textFromFileString) )
Toast.makeText(getApplicationContext(), "both string are equal", Toast.LENGTH_SHORT).show();
else
Toast.makeText(getApplicationContext(), "there is a problem", Toast.LENGTH_SHORT).show();
}
private void writeToFile(String data) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput(FILENAME, Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e(TAG, "File write failed: " + e.toString());
}
}
private String readFromFile() {
String ret = "";
try {
InputStream inputStream = openFileInput(FILENAME);
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e(TAG, "File not found: " + e.toString());
} catch (IOException e) {
Log.e(TAG, "Can not read file: " + e.toString());
}
return ret;
}
}
Like this:
Like Loading...
Related
tnx but where you put the file in assets folder ?
@gu
nope. you don’t need to put any files in anywhere
the problem is, you would like to write some data in a file and read it back
if you use the above code, a file will be created in your app sandbox (other app does not have access to it) and you can read it from there
Thx this helped me a lot!
Only got one problem:
When i try to read my data and send it to a TextView it only shows the latest string
hope you can help me
@Satanta, can you explain what are you trying to do and what is latest string?
i have two activities:
in the first, i want to write text from an EditText to a file like in your sample
it looks like this:
private OnClickListener btn=new OnClickListener() {
public void onClick(View v){
String name = etWinner.getText().toString();
writeToFile(name);
startActivity(new Intent(SubmitActivity.this, MainActivity.class));
}
};
private void writeToFile(String data){
String newline=”\r\n”;
try {
OutputStreamWriter oswName = new OutputStreamWriter(openFileOutput(HIGHSCORE, Context.MODE_PRIVATE));
oswName.write(newline);
oswName.write(data);
oswName.close();
}
catch (IOException e) {
Log.e(TAG, “File write failed: ” + e.toString());
}
}
in the second activity i try to read the stored data and write it to a textView:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_highscore);
btn1 = (Button)findViewById(R.id.buttonBack);
btn1.setOnClickListener(btn);
String winners = readFromFile();
TextView tvNames=(TextView)findViewById(R.id.textViewNames);
tvNames.setText(winners);
}
…
private String readFromFile(){
String ret = “”;
try {
InputStream inputStream = openFileInput(HIGHSCORE);
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = “”;
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
ret = stringBuilder.toString();
inputStream.close();
}
}
catch (FileNotFoundException e) {
Log.e(TAG, “File not found: ” + e.toString());
} catch (IOException e) {
Log.e(TAG, “Can not read file: ” + e.toString());
}
return ret;
}
basically its just your code so i don’t get why it doesn’t work :(
thx for the help
Satanta
edit:
by latest string i mean it only shows the last data stored, not all the data
like – let’s say String is “american pie”, it shows “american pie”
if i store another string it just shows this one, probably overwrites “american pie”
yes, previous data is going to be overwritten by the new data, thats how it supposed to work.
if you want to save the data then you need to open the file in MODE_APPEND, not MODE_PRIVATE (line #40)
For more information:
openFileOutput
Ahh okay!
thx for the quick help!
Tnx this is great but i have one question!
J have 3 variables, a,b and c. I want to save them like 0 10 30 etc. (30 is max) and when open application again i want to read them again so b and c wouldnt be 0 they will be 10 and 30 and use that. How J can save them in that way and read them? tnx a lot!
Hi thanks for your post..but after saving data into myFile.txt…i want see where that myFile.txt file is saved either sd card or in apps assets folder or some where else…
It worked. Thanks
@radha
You could use DDMS to see it->choose your devide-> choose: data / data / (your package) / files / mytext.txt
The inputstreamreader does not read my entire file. the size of the file is 15kb..Am struck..please help me out…
My file data is a Json FILE
check this out if you want to read write and delete using random access http://androidjavaio.blogspot.co.uk/2014/01/a-simple-android-java-io-class-using.html
hi
my question is
how to access text document from mobile in android app
I am doing Payment tracker project. My doubt is, if i am giving a number/value then i am pressing a button how to store that number/value in internal phone memory with a mark not send and when the internet is connected it will automatically send to the url given in program(that means post request)and the mark will change after the number/value is send basically it is about JSON Parsing. Can u Help me Plz!
i want to know, where mytextfile.txt is stored
Should i have to give any permission to store files.. I mean in manifest file?
@shwetha
No, You don’t need to provide any permissions.
when i execute this i am not getting where file is saved. Can you help me by giving procedure to execute this? when i execute this its showing “hello world”. I guess file is not getting created.I am getting error in “R.layout.main”. please can you give a steps to execute this?
how to check file present or not!
or value=null?
Hello, i’m so excited to look into your post. But I have a question. that program is about read/write file in txt. How about to read/write file in .doc ?? please help me, Mr. thankyou :)
Hi how do you load the text into a listview using simple adapter ?
I want to append words from edit text one per line and save to text file …
cat
dog
cow
Than i want to load the text from the text file back as an array into listview ….Is that possible please help