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.
Related
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.
Here how I write bytes to a file. I'm using FileOutputStream
private final Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
FragmentActivity activity = getActivity();
byte[] readBuffer = (byte[]) msg.obj;
FileOutputStream out = null;
try {
out = new FileOutputStream("myFile.xml");
out.write(readBuffer);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
and now I want to open that file, so I need to have path of that file. So how I need to open that file?
EDIT:
Here how I read from file, but I can't see anything...
BufferedReader reader = null;
FileInputStream s = null;
try {
s = new FileInputStream("mano.xml");
reader = new BufferedReader(new InputStreamReader(s));
String line = reader.readLine();
Log.d(getTag(), line);
while (line != null) {
Log.d(getTag(), line);
line = reader.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I recommend to use this for writting:
OutputStream out = new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath()+"/yourfilename");
So to read the location:
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+transaction.getUniqueId()+".pdf");
To read the path:
file.getAbsolutePath();
Your file is save in path /Data/Data/Your package Name/files/myFile.xml
you can use this.getFileDir() method to get the path of the files folder on the Application.
So use this.getFileDir() + "myFile.xml" to read the file.
How it is reported inside the developers guide you have to specify where you want to save your file. You can choose between:
Saving the file in the internal storage:
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();
}
Or on second instance you could save your file in external storage:
// Checks if external storage is available to at least read
public boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
Just remember to set permissions!!!!
Here there is the entire documentation: Documentation
I admittedly am still learning and would consider myself a novice (at best) regarding programming. I am having trouble with appending a file in android. Whenever I save, it will rewrite over the file, and I am having trouble understanding how to keep the file that is already there and only add a new line. Hoping for some clarity/advice. Here is how I am saving to the file (which rewrites the file each time I save).
public void saveText(View view){
try {
//open file for writing
OutputStreamWriter out = new OutputStreamWriter(openFileOutput("save.txt", MODE_PRIVATE));
//write information to file
EditText text = (EditText)findViewById(R.id.editText1);
String text2 = text.getText().toString();
out.write(text2);
out.write('\n');
//close file
out.close();
Toast.makeText(this,"Text Saved",Toast.LENGTH_LONG).show();
} catch (java.io.IOException e) {
//if caught
Toast.makeText(this, "Text Could not be added",Toast.LENGTH_LONG).show();
}
}
Change this,
OutputStreamWriter out = new OutputStreamWriter(openFileOutput("save.txt", MODE_PRIVATE));
to,
OutputStreamWriter out = new OutputStreamWriter(openFileOutput("save.txt", Context.MODE_APPEND));
This will append your new contents to the already existing file.
I Hope it helps!
Use this method, pass filename and the value to be added in the file
public void writeFile(String mValue) {
try {
String filename = Environment.getExternalStorageDirectory()
.getAbsolutePath() + mFileName;
FileWriter fw = new FileWriter("ENTER_YOUR_FILENAME", true);
fw.write(mValue + "\n\n");
fw.close();
} catch (IOException ioe) {
}
}
To display the content of the saved file with the line breaks with a button click use:
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
FileInputStream fin = openFileInput(fileTitle);
int c;
String temp = "";
while ((c = fin.read()) != -1) {
temp = temp + Character.toString((char) c);
}
tv.setText(temp);
Toast.makeText(getBaseContext(), "file read", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
}
}
});
To Delete content of existing file whist retaining the filename you can use:
deleteOrder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
FileOutputStream fOut = openFileOutput(fileTitle,MODE_PRIVATE);
// fOut.write(data.getBytes());
dataTitle = "";
fOut.write(data.getBytes());
fOut.close();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
This worked for me. Takes content of a TextEdit called textTitle. Writes it to file called dataTitle. Then writes a new line with fOut.write("\n"). The next text entered into TextEdit is added to the file with a line break.
try {
FileOutputStream fOut = openFileOutput(fileTitle,MODE_APPEND);
fOut.write(dataTitle.getBytes());
fOut.write('\n');
fOut.close();
Toast.makeText(getBaseContext(),"file saved",Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
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>();
I'm writting an Android's app. Two activities, one has TextEdit to type 'hello message', and button to save message in Internal Storage. Second is main activity. Hello mesage should appear after app's start.
Second activity:
String s = ((EditText) findViewById(R.id.message_act_editText_hello)).getText().toString();
FileOutputStream fos = openFileOutput(Lab2AndroidActivity.FILENAME, Context.MODE_PRIVATE);
fos.write(s.getBytes());
fos.close();
first (main) activity:
static String FILENAME = "message_file.zip";
FileOutputStream fos;
try {
//piece of code to guarantee that file exists
fos = openFileOutput(Lab2AndroidActivity.FILENAME, Context.MODE_APPEND);
fos.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
fis = openFileInput(FILENAME);
messageString = new StringBuffer("");
while ((length = fis.read(buffer)) != -1) {
String temp = new String(buffer, 0,length);
messageString.append(temp);
fis.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Toast t = Toast.makeText(this, messageString, 3000);
t.show();
I'm getting IO Exception in logcat at line:
while ((length = fis.read(buffer)) != -1)
but app seems to work correctly (defined message appears after app's start). I tried to find explanation, I found several topics, but all was according to large files, or files in assets, or compressed files.
I tried to name my file like
static String FILENAME = "message_file.zip",
static String FILENAME = "message_file.txt",
to try different extensions, but always i'm getting the same IO Exception.
Thanks for suggestions.
of course you will get an IO Exception your file doesn't exit and you request to open it
You forget this peice of code
File myFile = new File("/sdcard/mysdfile.txt");
In your first activity you can use this code
public class MainActivity extends Activity {
/** Called when the activity is first created. */
EditText txtData;
Button btnWriteSDFile;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// bind GUI elements with local controls
txtData = (EditText) findViewById(R.id.txtData);
txtData.setHint("Enter some lines of data here...");
btnWriteSDFile = (Button) findViewById(R.id.btnWriteSDFile);
btnWriteSDFile.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// write on SD card file data in the text box
try {
File myFile = new File("/sdcard/mysdfile.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(txtData.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Done writing SD 'mysdfile.txt'",
Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(),SecondActivity.class);
startActivity(i);
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}// onClick
});
}
}
in the second one you can use this:
public class SecondActivity extends Activity {
private TextView txtData2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
txtData2 = (TextView) findViewById(R.id.textView2);
try {
File myFile = new File("/sdcard/mysdfile.txt");
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
txtData2.setText(aBuffer);
myReader.close();
Toast.makeText(getBaseContext(),
"Done reading SD 'mysdfile.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
}
The first latout uses a linearlayout that contain an edittext and a button
The second a linearLayout with only a textview
Try it works fine if you find problem let me know!!
Ah i forget you have to add in your manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
I found reason. Problem was in fragment:
while ((length = fis.read(buffer)) != -1) {
String temp = new String(buffer, 0,length);
messageString.append(temp);
fis.close();
}
What's the catch?
fis.close();
should be after while. I didn't notice that yesterday...