How can I write into text file for android application? - android

I want to write some information about users to reuse them but I cannot create a text file so I cannot read it, too. Before starting to read, I want to accomplish writing to text file.
I wrote the user permission into manifest file.
Also, my code for writing into text file as in below:
public static void writeFile(String item, String fileName) throws IOException {
BufferedWriter out;
try {
FileWriter fileWriter= new FileWriter(Environment.getExternalStorageDirectory().getPath()+"/"+fileName);
out = new BufferedWriter(fileWriter);
out.write(item);
out.close();
}catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
So can anyone say the problem? Thank you.

As far I understood, you may want to use sharedpreferences, take a look: Simple Example Sharedpreferences
You can store and retrieve data easily...
Anyway...
Make sure your manifest contains:
1. android:name="android.permission.READ_EXTERNAL_STORAGE
2. android:name="android.permission.WRITE_EXTERNAL_STORAGE
String string1 = "Hey you";
FileOutputStream fos ;
try {
fos = new FileOutputStream("/sdcard/filename.txt", true);
FileWriter fWriter;
try {
fWriter = new FileWriter(fos.getFD());
fWriter.write("hi");
fWriter.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
fos.getFD().sync();
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}

Related

Can't create file in the internal storage

i am trying to create a file in the internal storage, i followed the steps in android developers website but when i run the below code there is no file created
please let me know what i am missing in the code
code:
File file = new File(this.getFilesDir(), "myfile");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
FileOutputStream fOut = null;
try {
fOut = openFileOutput("myfile",Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fOut.write("SSDD".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
By default these files are private and are accessed by only your application and get deleted , when user delete your application
For saving file:
public void writeToFile(String data) {
try {
FileOutputStream fou = openFileOutput("data.txt", MODE_APPEND);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fou);
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
For loading file:
public String readFromFile() {
String ret = "";
try {
InputStream inputStream = openFileInput("data.txt");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
Try to get the path for storing files were the app has been installed.The below snippet will give app folder location and add the required permission as well.
File dir = context.getExternalFilesDir(null)+"/"+"folder_name";
If you are handling files that are not intended for other apps to use, you should use a private storage directory on the external storage by calling getExternalFilesDir(). This method also takes a type argument to specify the type of subdirectory (such as DIRECTORY_MOVIES). If you don't need a specific media directory, pass null to receive the root directory of your app's private directory.
Probably, this would be the best practice.
Use this method to create folder
public static void appendLog(String text, String fileName) {
File sdCard=new File(Environment.getExternalStorageDirectory().getPath());
if(!sdCard.exists()){
sdCard.mkdirs();
}
File logFile = new File(sdCard, fileName + ".txt");
if (logFile.exists()) {
logFile.delete();
}
try {
logFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
try {
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.write(text);
buf.newLine();
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
In this method, you have to pass your data string as a first parameter and file name which you want to create as second parameter.

Save arraylist of objects and reading it from file

I have an arraylist of objects in a fragmentActivity
private List<Movie> myMovies = null;
I have options to add, remove and all that from the movie list, but once I close the application all is lost. How can I save the array into a file and retrieve the array from the file?
I have:
public void writeArray() {
File f = new File(getFilesDir()+"MyMovieArray.srl");
try {
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream objectwrite = new ObjectOutputStream(fos);
objectwrite.writeObject(myMovies);
fos.close();
if (!f.exists()) {
f.mkdirs();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public ArrayList<Movie> read(Context context) {
ObjectInputStream input = null;
ArrayList<Movie> ReturnClass = null;
File f = new File(this.getFilesDir(),"MyMovieArray");
try {
input = new ObjectInputStream(new FileInputStream(f));
ReturnClass = (ArrayList<Movie>) input.readObject();
input.close();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return ReturnClass;
}
but it is not working. getFilesDir() always points to a nullpointerexception
Is this the right way to do it?
Any sugestions on how can I save the array into a file and retrieve the array from the file?
UPDATE 1: Found the fix, just needed to write File f = new File(getFilesDir(), "MyMovieArray.srl");
New problem arrised: I have this code for onCreate:
myMovies = read(this);
if(myMovies==null){
myMovies = new ArrayList<Movie>();
populateMovieListWithExamples();
writeArray();
}
Everytime I start the application it always shows the list with the populate examples... if I add or remove once I reopen it is always the same list. Sugestions?
UPDATE 2 Just needed Movie class to be serializable. Thank you all for your help. Have a good day everyone
You are saving to MyMovieArray.srl but reading from MyMovieArray. Read also from MyMovieArray.srl
File object should be created like this (both in write and read):
File f = new File(getFilesDir(), "MyMovieArray.srl");
Use File f = new File(getFilesDir(), "MyMovieArray.srl");
in both writeArray() and read() methods

Read a file, if it doesn't exist then create

Honestly, I've searched a lot do this task so I ended up trying various methods but nothing worked until I ended up on this code. It works for me perfectly like it should, so I do not want to change my code.
The help I need is to put this code in a such a way that it begins to read a file, but if it the file doesn't exist then it will create a new file.
Code for saving data:
String data = sharedData.getText().toString();
try {
fos = openFileOutput(FILENAME, MODE_PRIVATE);
fos.write(data.getBytes());
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Code for loading data:
FileInputStream fis = null;
String collected = null;
try {
fis = openFileInput(FILENAME);
byte[] dataArray = new byte [fis.available()];
while (fis.read(dataArray) != -1){
collected = new String(dataArray);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
So If I add the saving data code in to the "FileNotFoundException" catch of the loading data part then could I achieve what I want?
Add
File file = new File(FILENAME);
if(!file.exists())
{
file.createNewFile()
// write code for saving data to the file
}
above
fis = openFileInput(FILENAME);
This will check if there exists a File for the given FILENAME and if it doesn't it will create a new one.
If you're working on Android, why don't you use the API's solution for saving files?
Quoting:
String filename = "myfile";
String string = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
You should really read the whole document, they explain pretty well the basic ways of creating or accessing files, you can also check the different ways of storing data.
But regarding your original question:
So If I add the saving data code in to the "FileNotFoundException"
catch of the loading data part then could I achieve what I want?
Yes, you could achieve it.
Try this one:
public static void readData() throws IOException
{
File file = new File(path, filename);
if (!file.isFile() && !file.createNewFile()){
throw new IOException("Error creating new file: " + file.getAbsolutePath());
}
BufferedReader r = new BufferedReader(new FileReader(file));
try {
// ...
// read data
// ...
}finally{
r.close();
}
}
Ref: Java read a file, if it doesn't exist create it

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);
}
}
Try closing your FileInputStream after the read is finished as you did with FileOutputStream. This makes the data get flushed.
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

Problems with Serialization

i'm having a few problems with serializing my objects.
I think that i'm missing something, because my application doesn't save the .dat like should be.
Let's show some code :
Load .dat file
public void gravar(ObjectOutputStream out) throws IOException {
out.writeObject(lista);
out.writeObject(cadeiras);
out.writeObject(notas);
out.close();
}
Save .dat file
public void carregar(ObjectInputStream in) throws IOException, ClassNotFoundException {
lista=(ArrayList<String>) in.readObject();
cadeiras=(ArrayList<String>) in.readObject();
notas= (ArrayList<String>) in.readObject();
in.close();
}
When i try to save the file, my application catch the exception FileNotFoundException here :
case R.id.gravar:
ObjectOutputStream out;
try {
out = new ObjectOutputStream(new FileOutputStream(fich));
gravar(out);
Toast.makeText(getApplicationContext(), "nice!", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), "error1!", Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "error2!", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
return true;
fich is this :
private static String fich = "gravar.dat";
what i'm missing? For better help, i let my code here.
http://pastebin.com/Ax2cHjUA
Thanks in advance!
You should pass the whole path instead of only the filename to FileOutputStream.
If that doing that does not work try
new FileOutputStream(new File(fich));
The solution for this is, instead of
out = new ObjectOutputStream(new FileOutputStream(fich));
paste this
out = new ObjectOutputStream(this.openFileOutput(fich, Context.CONTEXT_IGNORE_SECURITY));
the same for output.

Categories

Resources