Writing to a File in Android - android

I am just a beginner in learning Android.I want to learn how to write a piece of text to a file in Android.
My code to write, on clicking a button looks like this:
write.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
FileOutputStream fos;
try {
fos = openFileOutput("filename", Context.MODE_PRIVATE);
fos.write(data.getBytes());
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tv.setText("Values saved");
}
});
When I execute this the FileNotFoundException is thrown in logcat. As far as I know a new file will be created if no file with such name exists.
The logcat message is:
> 05-14 08:37:55.085: W/System.err(281): java.io.FileNotFoundException: /data/data/com.example.myproject11/files/test (No such file or directory)

First we should check, file is exists or not. Better you try:
File fileDir = new File("filepath");
if (!fileDir.exists())
fileDir.mkdirs();
try {
File file = new File(fileDir, "filename");
FileOutputStream outputStream = new FileOutputStream(file);
outputStream.write(data.getBytes());
outputStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tv.setText("Values saved");

Related

Write file to sdcard in android

I want to create a file on sdcard. Here I can create file and read/write it to the application, but what I want here is, the file should be saved on specific folder of sdcard. How can I do that using FileOutputStream?
// create file
public void createfile(String name)
{
try
{
new FileOutputStream(filename, true).close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// write to file
public void appendToFile(String dataAppend, String nameOfFile) throws IOException
{
fosAppend = openFileOutput(nameOfFile, Context.MODE_APPEND);
fosAppend.write(dataAppend.getBytes());
fosAppend.write(System.getProperty("line.separator").getBytes());
fosAppend.flush();
fosAppend.close();
}
Here's an example from my code:
try {
String filename = "abc.txt";
File myFile = new File(Environment
.getExternalStorageDirectory(), filename);
if (!myFile.exists())
myFile.createNewFile();
FileOutputStream fos;
byte[] data = string.getBytes();
try {
fos = new FileOutputStream(myFile);
fos.write(data);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
And don't forget the:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Try like this,
try {
File newFolder = new File(Environment.getExternalStorageDirectory(), "TestFolder");
if (!newFolder.exists()) {
newFolder.mkdir();
}
try {
File file = new File(newFolder, "MyTest" + ".txt");
file.createNewFile();
} catch (Exception ex) {
System.out.println("ex: " + ex);
}
} catch (Exception e) {
System.out.println("e: " + e);
}
It's pretty easy to create folder and write file on sd card in android
Code snippet
String ext_storage_state = Environment.getExternalStorageState();
File mediaStorage = new File(Environment.getExternalStorageDirectory()
+ "/Folder name");
if (ext_storage_state.equalsIgnoreCase(Environment.MEDIA_MOUNTED)) {
if (!mediaStorage.exists()) {
mediaStorage.mkdirs();
}
//write file writing code..
try {
FileOutputStream fos=new FileOutputStream(file name);
try {
fos.write(filename.toByteArray());
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
//Toast message sd card not found..
}
Note: 'getExternalStorageDirectory()'
actually gives you a path to /storage/emulated/0 and not the actual sdcard
'String path = Syst.envr("SECONDARY_STORAGE");' gives you a path to the sd card

read/write an object to file

here is the code :
my mission is to serialize an my object(Person) , save it in a file in android(privately), read the file later,(i will get a byte array), and deserialize the byta array.
public void setup()
{
byte[] data = SerializationUtils.serialize(f);
WriteByteToFile(data,filename);
}
Person p =null ;
public void draw()
{
File te = new File(filename);
FileInputStream fin = null;
try {
fin=new FileInputStream(te);
byte filecon[]=new byte[(int)te.length()];
fin.read(filecon);
String s = new String(filecon);
System.out.println("File content: " + s);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
text(p.a,150,150);
}
and my function :
public void WriteByteToFile(byte[] mybytes, String filename){
try {
FileOutputStream FOS = openFileOutput(filename, MODE_PRIVATE);
FOS.write(mybytes);
FOS.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("done");
}
it is returning a filenotfoundexception .
(i am new at this, so please be patient and understanding)
EDIT ::this is how i am (trying to ) read, (for cerntainly)
ObjectInputStream input = null;
String filename = "testFilemost.srl";
try {
input = new ObjectInputStream(new FileInputStream(new File(new File(getFilesDir(),"")+File.separator+filename)));
} catch (StreamCorruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Person myPersonObject = (Person) input.readObject();
text(myPersonObject.a,150,150);
} catch (OptionalDataException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
input.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and for reading :::
if(mousePressed)
{
Person myPersonObject = new Person();
myPersonObject.a=432;
String filename = "testFilemost.srl";
ObjectOutput out = null;
try {
out = new ObjectOutputStream(new FileOutputStream(new File(getFilesDir(),"")+File.separator+filename));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out.writeObject(myPersonObject);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
You don't need to use the 'byte array' approach. There is an easy way to (de)serialize objects.
EDIT: here's the long version of code
Read:
public void read(){
ObjectInputStream input;
String filename = "testFilemost.srl";
try {
input = new ObjectInputStream(new FileInputStream(new File(new File(getFilesDir(),"")+File.separator+filename)));
Person myPersonObject = (Person) input.readObject();
Log.v("serialization","Person a="+myPersonObject.getA());
input.close();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
Write:
public void write(){
Person myPersonObject = new Person();
myPersonObject.setA(432);
String filename = "testFilemost.srl";
ObjectOutput out = null;
try {
out = new ObjectOutputStream(new FileOutputStream(new File(getFilesDir(),"")+File.separator+filename));
out.writeObject(myPersonObject);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Person class:
public class Person implements Serializable {
private static final long serialVersionUID = -29238982928391L;
int a;
public int getA(){
return a;
}
public void setA(int newA){
a = newA;
}
}
FileNotFoundException when creating a new FileOutputStream means that one of the intermediate directories didn't exist. Try
file.getParentFile().mkdirs();
before creating the FileOutputStream.
Add this code to manifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
Go to phone setting/applications/your_app/permissions/ allow files and media permission. You can ask permission via by code and when user enter app program will ask permission. If you want I can give you code.
All writen and readen objects must be serializable.(Must implements Serializable interface) If A class extends B class, to set B class serializable is enough.
And add this code to writen and readen class:
private static final long serialVersionUID = 1L;
Write to external memory:
public static void writeToExternal(Serializable object, String filename) {
try {
//File root = new File(Environment.getExternalStorageDirectory(), "MyApp");
//or
File root = new File("/storage/emulated/0/MyApp/");
if (!root.exists()) {
root.mkdirs();
}
File file = new File(root, filename);
FileOutputStream fos = new FileOutputStream(file);
ObjectOutput out = new ObjectOutputStream(fos);
out.writeObject(object);
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
If you want to write to internal memory(This memory is not visible and doesn't need permission. This is your app stored in. For this, you can use getFilesDir() instead of getExternalStorageDirectory(). More about https://developer.android.com/reference/android/content/ContextWrapper#getFilesDir%28%29
https://developer.android.com/reference/android/os/Environment.html#getDataDirectory%28%29
https://gist.github.com/granoeste/5574148
https://source.android.com/docs/core/storage
public static void writeToInternal(Context context, Serializable object, String filename){
try {
//File root1 = new File(context.getFilesDir(), "MyApp");
//or
File root = new File("/data/user/0/com.example.myapplication/files/MyApp/");
if (!root.exists()) {
root.mkdirs();
}
File file = new File(root, filename);
FileOutputStream fos = new FileOutputStream(file);
ObjectOutput out = new ObjectOutputStream(fos);
out.writeObject(object);
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Read an object:
public static Object read(String filename) {
try {
File file = new File("/storage/emulated/0/MyApp/" + filename);
FileInputStream fis = new FileInputStream(file);
ObjectInputStream input = new ObjectInputStream(fis);
Object data = (Object) input.readObject();
input.close();
return data;
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
When you call read method you must cast to your readen and writen class.(For example Person p = (Person)read("file.txt");
Import all classes and run.

Android External Storage BufferedWriter doesn't accept NewLine

i have problem with file writing. I want to create OnClick method of button that add line to file on sdcard but instead it delete previous line and put all content in place of current one. In result i got only the Text i put at the last click of Button, here is my code:
if (txtFile.createNewFile() || txtFile.isFile()) {
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(txtFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
BufferedWriter bwriter = new BufferedWriter(myOutWriter);
EditText desc__ = (EditText)findViewById(R.id.descriptionEditTExt);
try {
bwriter.newLine();
bwriter.write(lat+"|"+lng+"|"+desc__.getText().toString()+"|"+f+"|"+position);
bwriter.close();
myOutWriter.close();
fOut.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
/* handle directory here */
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Please rewrite your FileOutputStream constructor as
FileOutputStream fos = new FileOutputStream(file, true);
here is suggests that your file will be opened in the append mode which will solve your first problem..
secondly if you want to add new line to the file use "\r\n" string
e.g. fos.write("\r\n".getBytes());
Hope this helps..

How to write to a textfile in one Activity & read that file in another Activity?

I am able to write and then read a text file in the SAME activity, but I am unable to read a text file after writing to it from another Activity.
Ex: Activity A creates and writes to a text file. Activity B reads that text file.
I use this code to write to the text file in Activity A:
FileOutputStream fos = null;
OutputStreamWriter osw = null;
try
{
fos = openFileOutput("user_info.txt", Context.MODE_WORLD_WRITEABLE);
osw = new OutputStreamWriter(fos);
osw.write("text here");
osw.close();
fos.close();
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
And then I use this code to try and read the same text file created by Activity A, but I get a FileNotFoundException:
try
{
FileInputStream fis = openFileInput("user_info.txt");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader buff = new BufferedReader(isr);
String line;
while((line = buff.readLine()) != null)
{
Toast.makeText(this, line, Toast.LENGTH_LONG).show();
}
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
Does anyone know why I am getting the FileNotFoundException?
Is it a path issue?
Don't really know how is built your application, but, the error you get does seem like a path issue, are you sure both Activities are in the same folder ?
If not, you'll need to set either an abolute path (like : "/home/user/text.txt") for the text file or a relative path (like : "../text.txt").
If you're not sure, try to print the current path for the Activity using some command like
new File(".").getAbsolutePath();
And, although I can't say I'm expert with Android, are you sure you need the Context.MODE_WORLD_WRITEABLE for your file ? If no other application than yours is reading or writing from/to it, it should not be necessary, right ?
it is surealy a path issue.
you can write like this
fpath=Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+"yourdirectory";
File custdir=new File(fpath);
if(!custdir.exists())
{
custdir.mkdirs();
}
File savedir=new File(custdir.getAbsolutePath());
File file = new File(savedir, filename);
if(file.exists())
{
file.delete();
}
FileOutputStream fos;
byte[] data = texttosave.getBytes();
try {
fos = new FileOutputStream(file);
fos.write(data);
fos.flush();
fos.close();
Toast.makeText(getBaseContext(), "File Saved", Toast.LENGTH_LONG).show();
finish();
} catch (FileNotFoundException e) {
Toast.makeText(getBaseContext(), "Error File Not Found", Toast.LENGTH_LONG).show();
Log.e("fnf", ""+e.getMessage());
// handle exception
} catch (IOException e) {
// handle exception
Toast.makeText(getBaseContext(), "Error IO Exception", Toast.LENGTH_LONG).show();
}
and you can read like
String locatefile=Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+"yourdirectory"+"/filename";
try {
br=new BufferedReader(new FileReader(locatefile));
while((text=br.readLine())!=null)
{
body.append(text);
body.append("\n");
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Write a List to internal storage onPause(), then read the List onResume()

I'm so confused. After reading this thread, I'm trying to write a List to internal storage onPause(), then read the List onResume(). Just for testing purposes, I'm trying to write a simple string as the example showed. I've got this to write with:
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = null;
try {
fos = openFileOutput(FILENAME, Context. MODE_WORLD_READABLE);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
fos.write(string.getBytes());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
fos.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
And I'm trying to read it in onResume() by calling:
try {
resultText01.setText(readFile("hello_file"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
resultText01.setText("exception, what went wrong? why doesn't this text say hello world!?");
}
Which of course uses this:
private static String readFile(String path) throws IOException {
FileInputStream stream = new FileInputStream(new File(path));
try {
FileChannel fc = stream.getChannel();
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
/* Instead of using default, pass in a decoder. */
return Charset.defaultCharset().decode(bb).toString();
}
finally {
stream.close();
}
}
For some reason, resultText01.setText(...) isn't being set to "hello world!", and is instead calling the catch exception. I'm sorry if my lingo isn't correct, I'm new to this. Thanks for any pointers.
Instead of the following in your readFile(...) method...
FileInputStream stream = new FileInputStream(new File(path));
Try...
FileInputStream stream = openFileInput(path);

Categories

Resources