Error while writing on a file

0 Mohamed Elkady · March 1, 2015
hey guys, 

what is my error here, this code doesn't do anything 


    public void run(View view) {
        String fileName = "MyFile";
        String content = "Hello World";
        FileOutputStream fileOutputStream;
        File file = new File(this.getFilesDir(), fileName);
        try {
            fileOutputStream = openFileOutput(fileName, Context.MODE_PRIVATE);
            fileOutputStream.write(content.getBytes());
            fileOutputStream.close();
            Toast.makeText(this, "File saved", Toast.LENGTH_SHORT);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

Post a Reply

Replies

Oldest  Newest  Rating
0 Mohamed Elkady · March 2, 2015
first of all, thanks for ur reply.
firstly, i'm new here so i didn't know how to write code here :D , but now i knew 

secondly, internal storage doesn't need any permission to write/read as i knew.

last thing, the file wasn't created
0 Dol Lod · March 3, 2015
Here is code that shows basic file creation. I have used it. I am assuming you have permission to write to the file so I'm not pasting the permissions code here. 

String fileLocation = Environment.getExternalStorageDirectory().getAbsolutePath();
fileLocation+="/..."; // this sets where you want to create the file
File applicationDirectory= new File(fileLocation); //this creates the highest directory at that location if it doesn't already exist
applicationDirectory.mkdirs(); //this makes all subdirectories within the file location if they don't exist
fileLocation="/"+fileName+".txt"; //fileName is the name of the file you wish to create
File exportedFile=new File(appplicationDirectory,fileLocation); //this creates the text file at that location

FileOutputStream fileWriter = null;
try {
fileWriter = new FileOutputStream(exportedFile,false); 
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(fileWriter==null) //this means you couldn't grab the file 
return;
String textToWrite="..."; //this is the text you wish t owrite
OutputStreamWriter writer = new OutputStreamWriter(fileWriter); //this creates a a writer to add to the file
appendToFile(writer,textToWrite);

try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fileWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
  • 1

Java / Android Development

107,265 followers
About

Very popular language used to create desktop applications, website applets, and Android apps.

Links
Moderators
Bucky Roberts Administrator