FileReader (probably) doing crazy stuff after calling a 2nd time - android

My App is writing data into a txt-file. (the code was on here some time ago for another reason)
Im always reading the whole file into a String Array and replacing an explicit line.
After reading the File I log the Data to observe it. My main is calling the App 7 times (for each line) but after the first call the data im logging is just weird.
Here is my code:
public void writeFileData(String data, int line) {
String[] lines = new String[999];
File file = null;
BufferedReader br = null;
FileOutputStream fos = null;
OutputStreamWriter os = null;
try {
file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "data.txt");
if(!file.exists())
{
try
{
if(file.createNewFile())
{
Toast.makeText(BaseActivity.this, "File was created", Toast.LENGTH_LONG).show();
}
}
catch(Exception ex)
{
Log.e("Error creating file", ex.getMessage());
}
}
br = new BufferedReader(new FileReader(file));
int i = 0;
while(i < 7)
{
buffer = br.readLine();
lines[i] = buffer;
i++;
}
br.close();
fos = new FileOutputStream(file, false);
lines[line] = data;
for(i = 0; i < 7; i++)
{
if (lines[i].isEmpty())
{
Log.e(TAG, i + "is empty");
}
else
{
Log.e(TAG, lines[i]);
}
}
for(i = 0; i < 7; i++)
{
try {
fos.write(lines[0].getBytes());
}
catch (Exception ex)
{
Log.e("Error writing", ex.getMessage());
}
}
try
{
fos.close();
}
catch(Exception ex)
{
Log.e("Error closing/flushing", ex.getMessage());
}
}
catch(Exception ex)
{
Log.e("Error creating streams", ex.getMessage());
}
}
My logcat
The calls inside the main look like:
writeFullData();
writeFileData("001",0);
writeFileData("002",1);
writeFileData("110",2);
writeFileData("110",3);
writeFileData("110",4);
writeFileData("110",5);
writeFileData("110",6);
writeFullData(); is writing into the txt file (visible in the logcat image)
Thanks in advance.
Xaver Seiringer

I called a function overwriting the whole file. That way i was able to overwatch every single line and Log the input so i will notice a change in the lines and my writeFileData() Function also had to read something.
I didnt write false in the FileWriter!
BufferedWriter bw = new BufferedWriter(new FileWriter(file, true));
I wrote 21 lines into the file instead of 7 (after calling 4 times).
The 2nd mistake was i forgot to bw.newLine in writeFileData.
Those mistakes doe...
But thanks for the help.

Related

Read data of type double from a text file in Android

I want to read data of type double saved in a .txt file from a previously specified folder. I've implemented the following code to read data then put them in an array of type double named savg1. when I run my application , it going to crash and the application stop. I tried to debug the application step by step and found that crash happens when the code reaches to savg1[i] = Double.parseDouble(str).
public void filereader()
{
InputStream is=this.getResources().openRawResource(R.raw.nums);
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String str=null;
int i=0;
try
{
if (is !=null)
{
str=br.readLine();
while (str != null) {
savg1[i] = Double.parseDouble(str);
i++;
str=br.readLine();
}
is.close();
br.close();
}
} catch (IOException e)
{
e.printStackTrace();
}
}
I am a newbie in Android developing so excuse me about my elementary question. Can anybody guide me how I can solve this problem?
Use following code to read data from your file. Note that in this method each number should be in a separate line:
double svg1[] = new double[10];
try {
InputStream is = getResources().openRawResource(R.raw.data);
DataInputStream dis = new DataInputStream(is);
while (dis.available() > 0) {
String test = dis.readLine();
double a = Double.parseDouble(test);
}
}catch (Exception e){
e.printStackTrace();
}
You can use file scanner for reading double type data saved in a text file as bellow:
public void fileReader(){
Scanner scan;
File file = new File("resources\\scannertester\\data.txt");
int idx = 0;
try {
scan = new Scanner(file);
while(scan.hasNextDouble())
savg1[idx++] = scan.nextDouble();
} catch (FileNotFoundException error) {
error.printStackTrace();
}
scan.close();
}

read and write in a file android

I have next problems:
(1) How to check whether a file exists ? I do it this way in MainActivity onCreate
File f = new File("punteggio.txt");
if(f.exist())
readFromFile();
else{
writeToFile();
readFromFile();
}
but it does not work because every time I open my application file does not exist.
(2) Another problem.
In my first activity I write and read from the file without problems, while in the second activity when I read from the file the string is empty .
Main activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textScore = (TextView) findViewById(R.id.textRecord);
File f = new File("punteggio.txt");
if (!f.exists()) {
Log.d(TAG, "Writeee");
writeToFile();
} else {
readFromFile();
}
}
private void readFromFile() {
String ret = "";
try {
FileInputStream fis = openFileInput("punteggio.txt");
byte[] buffer = new byte[(int) fis.getChannel().size()];
fis.read(buffer);
String str = "";
for (byte b : buffer) str += (char) b;
fis.close();
Log.d(TAG, str);
textScore.setText("Record: " + str);
Log.i("STACKOVERFLOW", String.format("GOT: [%s]", str));
} catch (IOException e) {
Log.e("STACKOVERFLOW", e.getMessage(), e);
}
}
public void startGame(View v) {
Intent i = new Intent(MainActivity.this, GamePanel.class);
startActivity(i);
}
private void writeToFile() {
String string = "0";
try {
FileOutputStream fos = openFileOutput("punteggio.txt", Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.flush();
fos.close();
} catch (IOException e) {
Log.e(TAG, e.getMessage(), e);
}
}
This is the secondActivity
private int readFromFile() {
String str = "";
int i = 0;
try {
FileInputStream fis = openFileInput("punteggio.txt");
byte[] buffer = new byte[(int) fis.getChannel().size()];
fis.read(buffer);
for (byte b : buffer) str += (char) b;
i = Integer.parseInt(str);
fis.close();
} catch (IOException e) {
Log.e("STACKOVERFLOW", e.getMessage(), e);
}
Log.d(TAG, "Stringa iiiii: " + i);
return i;
}
The variable is empty, why?
Can you help me? Thanks
answer for (1) - opening and writing to file depend on where the file is located, it could be in phone storage OR in SD Card. as such, when implementing reading files system, care should be taken considering the location of the file. This, sometime will cause the error, cannot locating the file.
Alternatively, a better way of doing it would be using share preference.
sidenote : storing game score in a text file is vulnerable because user can directly edit the scores in the text file and alter the game result.

Data stored in file is erased after exiting the app

I'm using this code to save data to file and read data from the file:
public static void save(FileIO files) {
BufferedWriter out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(
files.writeFile(".save")));
for (int i = 0; i < 20; i++) {
out.write(Integer.toString(scores[i]));
out.write("\n");
}
} catch (IOException e) {
} finally {
try {
if (out != null)
out.close();
} catch (IOException e) {
}
}
}
public static void load(FileIO files) {
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(
files.readFile(".save")));
for (int i = 0; i < 20; i++) {
scores[i] = Integer.parseInt(in.readLine());
}
} catch (IOException e) {
} catch (NumberFormatException e) {
} finally {
try {
if (in != null)
in.close();
} catch (IOException e) {
}
}
}
FileIO.java
package com.avoidblocks.avoidblocks.framework;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.SharedPreferences;
public interface FileIO {
public InputStream readFile(String file) throws IOException;
public OutputStream writeFile(String file) throws IOException;
public InputStream readAsset(String file) throws IOException;
public SharedPreferences getSharedPref();
}
I'm calling save(FileIO files) and load(FileIO files) multiple times in an app and it works fine while I'm in an app, but when I exit the app and start the app again, all data is gone.
Does anyone know how to create that data remains saved even when I exit the app, so that I could restore the data when I start the app again?
Also, is this the right way to save data if I want that saved data is only visible to my app and that after uninstall, all saved data is erased?
EDIT-EDIT-EDIT:
ok its your FileIO files variable that looks like it is wrong,
what are you using to get that variable?
should be
context.openFileOutput(".save", Context.MODE_PRIVATE)
for save and
context.openFileInput(".save")
for load
and it should be FileOutputStream for save and FileInputStream for read instead of FileIO.
and when adding it to the stream just pass that in.
so in your code you should create the BufferedWriter like this:
out = new BufferedWriter(new OutputStreamWriter(
context.openFileOutput(".save", Context.MODE_PRIVATE)));
and create BufferedReader like this:
in = new BufferedReader(new InputStreamReader(
context.openFileInput(".save")));
==================EDIT: my testing code=================
Ok, I created an activity and made the following two methods and declared an array of ints:
public static int scores[] = {11,12,13,14,15};
public static void save(Context context) {
BufferedWriter out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(
context.openFileOutput(".saveingTest", Context.MODE_PRIVATE)));
for (int i = 0; i < scores.length; i++) {
out.write(Integer.toString(scores[i]));
out.write("\n");
}
} catch (IOException e) {
} finally {
try {
if (out != null)
out.close();
} catch (IOException e) {
}
}
}
public static void load(Context context) {
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(
context.openFileInput(".saveingTest")));
for (int i = 0; i < scores.length; i++) {
Log.d("testingApp", "test: " + Integer.parseInt(in.readLine()));
// scores[i] = Integer.parseInt(in.readLine());
}
} catch (IOException e) {
} catch (NumberFormatException e) {
} finally {
try {
if (in != null)
in.close();
} catch (IOException e) {
}
}
}
in my onCreate I have the following two lines of code:
save(this);
load(this);
to test I did the following:
commented out load in onCreate, ran the app, than I removed the comment on load and commented out save in onCreate and i changed the numbers in the scores variable(this is unnecessary but i did it anyway) and ran the app, the result was the int values in scores from the first time the app was run, inside the android log viewer window on eclipse. you can also have buttons that trigger save and load instead if you don't want to comment and run.
try it yourself, it should work, and make sure you are doing the same thing in your actual android app, if it still dose not work you are doing something else wrong and its not an issue with saving the file.

I can create file but can't write to it

Could someone look at this snippet of code please and let me know what I'm doing wrong? It's a simple function that takes a string as parameter which it uses as a file name, adding ".txt" to the end of it.
The function checks if the file exists, creating it if it doesn't and then writes two lines of text to the file. Everything appears to be working and the file is created successfully on the sd card. However, after everything is done, the file is empty (and has a size of 0 bytes).
I suspect it's something obvious that I'm overlooking.
public void writeFile(String fileName) {
String myPath = new File(Environment.getExternalStorageDirectory(), "SubFolderName");
myPath.mkdirs();
File file = new File(myPath, fileName+".txt");
try {
if (!file.exists()) {
if (!file.createNewFile()) {
Toast.makeText(this, "Error Creating File", Toast.LENGTH_LONG).show();
return;
}
}
OutputStreamWriter writer = new OutputStreamWriter(openFileOutput(file.getName(), Context.MODE_PRIVATE));
writer.append("First line").append('\n');
writer.append("Second line").append('\n');
writer.close();
}
catch (IOException e) {
// Do whatever
}
}
Hi I will show you the full code I use, works perfect.
I don't use
new OutputStreamWriter()
i use
new BufferedWriter()
here is my Snippet
public void writeToFile(Context context, String fileName, String data) {
Writer mwriter;
File root = Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + File.separator + "myFolder");
if (!dir.isDirectory()) {
dir.mkdir();
}
try {
if (!dir.isDirectory()) {
throw new IOException(
"Unable to create directory myFolder. SD card mounted?");
}
File outputFile = new File(dir, fileName);
mwriter = new BufferedWriter(new FileWriter(outputFile));
mwriter.write(data); // DATA WRITE TO FILE
Toast.makeText(context.getApplicationContext(),
"successfully saved to: " + outputFile.getAbsolutePath(), Toast.LENGTH_LONG).show();
mwriter.close();
} catch (IOException e) {
Log.w("write log", e.getMessage(), e);
Toast.makeText(context, e.getMessage() + " Unable to write to external storage.",Toast.LENGTH_LONG).show();
}
}
-- Original Code --
That one took a while to find out. The javadocs
here brought me on the right track.
It says:
Parameters
name The name of the file to open; can not contain path separators.
mode Operating mode. Use 0 or MODE_PRIVATE for the default operation, MODE_APPEND to append to an existing file, MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE to control permissions.
The file is created, if it does not exist, but it is created in the private app space. You create the file somewhere on the sd card using File.createNewFile() but when you do context.openFileOutput() it creates always a private file in the private App space.
EDIT: Here's my code. I've expanded your method by writing and reading the lines and print what I got to logcat.
<pre>
public void writeFile(String fileName) {
try {
OutputStreamWriter writer = new OutputStreamWriter(
getContext().openFileOutput(fileName + ".txt", Context.MODE_PRIVATE));
writer.append("First line").append('\n');
writer.append("Second line").append('\n');
writer.close();
}
catch (IOException e) {
Log.e("STACKOVERFLOW", e.getMessage(), e);
return;
// Do whatever
}
// Now read the file
try {
BufferedReader is = new BufferedReader(
new InputStreamReader(
getContext().openFileInput(fileName + ".txt")));
for(String line = is.readLine(); line != null; line = is.readLine())
Log.d("STACKOVERFLOW", line);
is.close();
} catch (IOException e) {
Log.e("STACKOVERFLOW", e.getMessage(), e);
return;
// Do whatever
}
}
Change the mode from Context.MODE_PRIVATE to Context.MODE_APPEND in openFileOutput()
MODE_APPEND
MODE_PRIVATE
Instead of
OutputStreamWriter writer = new OutputStreamWriter(openFileOutput(file.getName(), Context.MODE_PRIVATE));
Use
OutputStreamWriter writer = new OutputStreamWriter(openFileOutput(file.getName(), Context.MODE_APPEND));
UPDATE :
1.
FileOutputStream osr = new FileOutputStream(file.getName(), true); // this will set append flag to true
OutputStreamWriter writer = new OutputStreamWriter(osr);
BufferedWriter fbw = new BufferedWriter(writer);
fbw.write("First line");
fbw.newLine();
fbw.write("Second line");
fbw.newLine();
fbw.close();
Or 2.
private void writeFileToInternalStorage() {
FileOutputStream osr = new FileOutputStream(file.getName(), true); // this will set append flag to true
String eol = System.getProperty("line.separator");
BufferedWriter fbw = null;
try {
OutputStreamWriter writer = new OutputStreamWriter(osr);
fbw = new BufferedWriter(writer);
fbw.write("First line" + eol);
fbw.write("Second line" + eol);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fbw != null) {
try {
fbw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Using internal storage to save list of integers

i'm trying to save a list of integers in my application by saving each integer in a new line of a file in the internal storage.
For retreiving it I read it line by line and put every linevalue, parsed as integer, in my list of integers.
I know a database is better for this kinda stuff, but this should work.
I am trying for quite a while now, but it never seems to work. I always get a nullpointerexception when trying to read. I logged "line", it gave the value it should have. But
saving one id, adding it as a new string:
private void saveToFavorites(Integer saveFav) {
String favstr = String.valueOf(saveFav);
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(openFileOutput("favorites", MODE_WORLD_WRITEABLE)));
writer.newLine();
writer.append((favstr));
System.out.println(" added to favs :"+ saveFav);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
And the reading method:
#SuppressWarnings("null")
private List<Integer> readFileFromInternalStorage() {
List<Integer> favs = null;
BufferedReader input = null;
try {
input = new BufferedReader(new InputStreamReader(openFileInput("favorites")));
String line;
while ((line = input.readLine()) != null) {
System.out.println("readFileFromInternalStorage line value: "+ line );
favs.add(Integer.parseInt(line));
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("readFileFromInternalStorage: fail" );
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return favs;
}
Which is in an other activity. I thought it would work but it clearly doesnt. When reading back, the logline: System.out.println("readFileFromInternalStorage line value: "+ line );
displays that the value of line equals the LAST added id,and an empty line, and not the others too. So the line by line saving fails. Also when parsing it to an integer it fails, what is weird because it is only a number.
08-01 12:29:54.190: I/System.out(1540): readFileFromInternalStorage line value:
08-01 12:29:54.190: I/System.out(1540): readFileFromInternalStorage line value: 301
Anyone knows what i need to change?
Since Integer is Serializable I sugget to serialize the entire List:
private void saveList(List<Integer> list) {
try {
File file = Environment.getExternalStorageDirectory();
File filename = new File(file, "yourfilename");
fos = new FileOutputStream(filename);
out = new ObjectOutputStream(fos);
out.writeObject(list);
out.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
private void readList()
{
try {
File file = Environment.getExternalStorageDirectory();
File filename = new File(file, "yourfilename");
fis = new FileInputStream(filename);
in = new ObjectInputStream(fis);
List<Integer> list= (List<Integer>) in.readObject();
in.close();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
}
try this May it help you :-
1 - String saveFav = contaains all integer this form I1+"/"I2+"/"I3;
2:- then save it into file
private void saveToFavorites(String saveFav) {
//right here your code for write into file saveFave string
}
in reading file read string and split("/").it's working for me .
Here's some working code that will read and write ints to the phones internal memory.
You can create an array or list of ints and basically just iterate over it until all ints are saved/read to/from the memory:
Here's the code to write an int to the memory:
public void writePrimitiveInternalMemory(String filename, int value) {
SharedPreferences preferences = this.getPreferences(Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt(filename, value);
editor.commit();
}
Here's code to read from the memory:
public int readPrimitiveInternalMemoryInteger(String filename) {
SharedPreferences preferences = this.getPreferences(Activity.MODE_PRIVATE);
return preferences.getInt(filename, 0);
}
I hope this helps you!
You are not allocating the integer list...
List<Integer> favs = null;
Allocate a new arraylist..
List<Integer> favs = new ArrayList<Integer>();

Categories

Resources