How to write an array to a text file in internal memory?

I need to save some data as a text file in internal memory. for example below, I have a button, I would like to save some data in a text file every time the button is clicked. I am testing an example in:

http://developer.android.com/training/basics/data-storage/files.html

import java.io.FileOutputStream; import android.os.Bundle; import android.app.Activity; import android.content.Context; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends Activity implements OnClickListener { Button b; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); b = (Button) findViewById(R.id.button1); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public void onClick(View v) { String filename = "myfile"; String string = "Hello world!"; FileOutputStream outputStream; try { outputStream = openFileOutput(filename, Context.MODE_APPEND); outputStream.write(string.getBytes()); outputStream.close(); } catch (Exception e) { e.printStackTrace(); } } } 

I just changed "mode_private" to "mode_append", so I can see the saved file, but I can’t find the saved file, I can’t even find the directory in which the file should be saved.

Also, more specifically, I need to save an array of numbers in a text file (let's say i = {1,2,3} to output.txt). I would be grateful if you could help me.

+4
source share
1 answer

Firstly, you are missing a setOnClickListener for your button. It should be...

 b = (Button) findViewById(R.id.button1); b.setOnClickListener(this); 

"but I can’t find the saved file, I can’t even find the directory in which the file should be saved."

getApplicationContext().getFilesDir() will tell you where the file was saved.

Android docs say ...

The internal application storage directory is indicated by your application package name in a special place on the Android file system.

To save the array to a file, try the following ...

 String filename = "myfile"; String[] numbers = new String[] {"1, 2, 3"}; FileOutputStream outputStream; try { outputStream = openFileOutput(filename, Context.MODE_APPEND); for (String s : numbers) { outputStream.write(s.getBytes()); } outputStream.close(); } catch (Exception e) { e.printStackTrace(); } 
+3
source

Source: https://habr.com/ru/post/1486159/


All Articles