d3vpasha
d3vpasha

Reputation: 528

write into a file and read it to save the content into a variable like String

firstly, i search an answer everywhere but i didn't found. Thank you very much for your answers. In fact, i try to write into a file. Then, i try to save the content into a StringBuffer. And finally i try to show it via a TextView, but it shows nothing!

public class MainActivity extends Activity {

String finall;

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

    String FILENAME = "hello_file";
    String string = "hello world!";

    FileOutputStream fos;
    try
    {
        fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
        fos.write(string.getBytes());
        fos.close();
    } 
    catch (FileNotFoundException e) { e.printStackTrace(); } 
    catch (IOException e) { e.printStackTrace(); }



    FileInputStream in = null;
    try
    {
        in = openFileInput("hello_file.txt");
        StringBuffer fileContent = new StringBuffer("");

        byte[] buffer = new byte[1024];

        while(in.read(buffer) != -1)
        {
            fileContent.append(new String(buffer));
        }
        finall = fileContent.toString();
    }
    catch (FileNotFoundException e) { e.printStackTrace(); } 
    catch (IOException e) { e.printStackTrace(); }

    TextView text = (TextView)findViewById(R.id.mehmet);
    text.setText(finall);
}

}

Upvotes: 0

Views: 268

Answers (2)

Marco Capoferri
Marco Capoferri

Reputation: 224

As said by @Piovezan you should close your file, but you should also consider that the intended valued returned by in.read(buffer) may not be equal to buffer.length

So you could have some dirty values at the end. And I don't know if this is your case but StringBuffer is thread safe, so if you aren't working in a multi thread section of your app you could switch to StringBuilder for better performance and less overhead

Upvotes: 0

Piovezan
Piovezan

Reputation: 3223

Try closing your FileInputStream after the read is finished as you did with FileOutputStream. This makes the data get flushed.

Upvotes: 1

Related Questions