Ozzy
Ozzy

Reputation: 3

This OutputStream Code Does't Save the String into the Txt File

This outputStream Code bellow can Work.. but plzz tell me where can i make a Text File.. i have put it On My deskTop..

Button input = (Button) findViewById(R.id.input);    
input.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            try {
                String str = "MY NAME IS OZEER AHMAD, I BELONGS FROM KASHMIR. DOING BCS FROM PESHAWAR UNIVERSITY";
                FileOutputStream fout = openFileOutput(str, MODE_WORLD_READABLE);
                OutputStreamWriter w = new OutputStreamWriter(fout);
                w.write(str);
                w.flush();
                w.close();
                Toast.makeText(getBaseContext(),  "Data Inserted IN OUTPUT FILE", Toast.LENGTH_LONG).show();    
            } catch (Exception ex) {
                // TODO Auto-generated catch block  
                Toast.makeText(getBaseContext(),  "ERROR FOUND IN OUTPUT FILE", Toast.LENGTH_LONG).show();
                ex.printStackTrace();
            }
        }
    });

Upvotes: 0

Views: 55

Answers (2)

Dmila Ram
Dmila Ram

Reputation: 1074

You are passing the wrong parameters to openFileOutput, the first parameter is the file name not the string which you want to write into file, use this code:

String fileName="SOMEFILENAME.txt";
String str="this is the string you will see inside the file";
            try {
                FileOutputStream outputStream=openFileOutput(fileName,MODE_WORLD_READABLE);
                OutputStreamWriter outputStreamWriter=new OutputStreamWriter(outputStream);
                outputStreamWriter.write(str);
                outputStreamWriter.flush();
                outputStreamWriter.close();
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO: handle exception
                e.printStackTrace();
            }

Upvotes: 2

Minato
Minato

Reputation: 4533

Please remove w.flush(); after w.write(str).

since the writing is done not immediately from the buffer but when buffer has sufficient amount of data or is closed. calling flush() on the stream deletes all the data in it whether its written or not.

Upvotes: 0

Related Questions