Saboor880 9 Junior Poster

Hello to all! I have started learning android recently and I am facing a problem in file handling (in internal storage). I wrote a simple program which creates a file and writes some data in that file . I have two buttons first button writes data in the file and creates a toast message saying: "file saved" and second button reads data from the file and creates a toast message "file read". But the problem is that I when i press first button The toast message displays perfectly but I don't know that where the file goes in my device "Nexus 7". When I press second button then it does not read the data from file and no data displays in the text view, but toas message(file read) displays perfectly. I have checked my device download folder and also tried to find my file by file explorer but can't find my file. I am pasting code of my program below.

package com.hatflabs.writingfile;

import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Text;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class MainActivity extends AppCompatActivity {

    Button b1, b2;
    EditText ed1;
    TextView tv1;
    String data;
    String filename = "my file";


    FileOutputStream outputStream;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // finding views by giving their id's
         b1 = (Button)findViewById(R.id.button);
         b2 = (Button)findViewById(R.id.button2);
         ed1 = (EditText)findViewById(R.id.editText);
        data = ed1.getText().toString();
         tv1 = (TextView)findViewById(R.id.tv);


        // click listener method for button 1
        b1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                try {


                    outputStream =  openFileOutput(filename, Context.MODE_PRIVATE);
                    outputStream.write(data.getBytes());
                    outputStream.close();
                    Toast.makeText(getBaseContext(),"file saved", Toast.LENGTH_SHORT).show();
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        });

        // click listener method for button2
              b2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    FileInputStream fin = openFileInput(filename);
                    int c;
                    String temp="";
                    while((c = fin.read())!= -1)
                    {

                        temp = temp + Character.toString((char)c);


                    }


                    tv1.setText(temp);
                    Toast.makeText(getBaseContext(),"file read",Toast.LENGTH_SHORT).show();


                }

                catch(Exception e)
                {
                }

            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

Please guide me i shall be thankfull to you.

Dani AI

Generated

Most likely cause: the app is creating an empty file and you can’t see it with a normal file manager because it’s in the app’s private internal storage. In your posted code data = ed1.getText().toString() runs in onCreate (before the user types), so the saved file contains nothing. The write/read calls then succeed (so you see both toasts) but the TextView stays empty. Also avoid swallowing exceptions with an empty catch {} — that hides useful errors.

Fixes (practical, minimal changes)

  • Read the EditText inside the save button handler, not in onCreate.
  • Use a simple filename (no spaces), and log the absolute path so you can inspect it.
  • Don’t swallow exceptions; show or log them.
  • Use a StringBuilder or buffered reader to read files instead of concatenating characters.

Example write + read pattern to drop into your activity (adjust names to match your code):

String filename = "myfile.txt";

b1.setOnClickListener(v -> {
    String data = ed1.getText().toString();               // get text when button pressed
    try (FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE)) {
        fos.write(data.getBytes("UTF-8"));
        Toast.makeText(MainActivity.this, "file saved", Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        Toast.makeText(MainActivity.this, "save failed: " + e.getMessage(), Toast.LENGTH_LONG).show();
    }
});

b2.setOnClickListener(v -> {
    try (FileInputStream fis = openFileInput(filename);
         InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
         BufferedReader br = new BufferedReader(isr)) {
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) sb.append(line).append('\n');
        tv1.setText(sb.toString());
        Toast.makeText(MainActivity.this, "file read", Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        Toast.makeText(MainActivity.this, "read failed: " + e.getMessage(), Toast.LENGTH_LONG).show();
    }
});

How to inspect the file

  • Log the path: Log.d("FILES", getFilesDir().getAbsolutePath()); — file is stored at /data/data/<your.package.name>/files/<filename>.
  • To view it use the Android Studio Device File Explorer (emulator or debuggable app) or adb shell run-as your.package.name cat files/myfile.txt (works for debuggable apps/emulator). On non-rooted release devices internal files are not visible to normal file managers.

Quick tip for : test on the emulator first (easy to inspect files), add logging or a Toast on exceptions, and try the small fixes above — that will make the saved text appear when you press the read button.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.