I am trying to write to a new file named "filename.txt" and write out "hi" when I open an app. How do I go about this? I run this code in Eclipse, press F11, open up the AVD, and click on the app. I get the "Hello World, appname!" message, but no file is created.
package com.paad.comparison;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.widget.Toast;
public class ComparisonOfControlCreationActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
String string1 = "Hey you";
FileWriter fWriter;
try{
fWriter = new FileWriter("filename.txt", true);
fWriter.write("hi");
fWriter.flush();
fWriter.close();
} catch(Exception e) {
e.printStackTrace();
}
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
EDIT: For anyone that happens to run into this problem in the future, make sure your AndroidManifest.xml file has the following line in it:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Try like this:
FileWriter fWriter;
File sdCardFile = new File(Environment.getExternalStorageDirectory() + " \filename.txt");
Log.d("TAG", sdCardFile.getPath()); //<-- check the log to make sure the path is correct.
try{
fWriter = new FileWriter(sdCardFile, true);
fWriter.write("hi");
fWriter.flush();
fWriter.close();
}catch(Exception e){
e.printStackTrace();
}