I need to store some data as a text file on the internal storage. for example below, I have a button, I'd like to save some data in a text file each time the button is clicked. I am testing an example in:
http://developer.android.com/training/basics/data-storage/files.html
import java.io.FileOutputStream;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
Button b;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button) findViewById(R.id.button1);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onClick(View v) {
String filename = "myfile";
String string = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_APPEND);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I only changed the "mode_private" to "mode_append", so I can see the saved file, but I cannot find the saved file, I even cannot find the directory in which the file is supposed to be saved.
Also, more specifically, I need to store an array of numbers in the text file (say i={1,2,3} to output.txt). I would be grateful if you can help me out.
Firstly, you are missing the setOnClickListener
for your button. It should be...
b = (Button) findViewById(R.id.button1);
b.setOnClickListener(this);
"but I cannot find the saved file, I even cannot find the directory in which the file is supposed to be saved."
getApplicationContext().getFilesDir()
will tell you where the file was saved.
Android DOCS say...
Your app's internal storage directory is specified by your app's package name in a special location of the Android file system.
To store an array in a file, try the following...
String filename = "myfile";
String[] numbers = new String[] {"1, 2, 3"};
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_APPEND);
for (String s : numbers) {
outputStream.write(s.getBytes());
}
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With