xXJohnRamboXx xXJohnRamboXx - 3 months ago 21
Android Question

Android FileOutputStream location save file

I have an app that save into a file(internal storage) data input by the user and at startup it loads this file and shows the contents. I would know: where can i find my file(data.txt)?
In addition to, if i input "Hello" and then "World" when i load file i see "HelloWorld" in same line but i want "Hello" and "World" printed in 2 different lines.

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;
}


Thanks

[UPDATE]

I've inserted "\n" after every input:

user = (EditText) v.findViewById(R.id.username);
writeToFile(user.getText().toString() + "\n");


But when i print my file they are always on the same line

Answer

where can i find my file(data.txt)?

You can find path of directory which which is created by openFileOutput using YourActivity.this.getFilesDir().getAbsolutePath()

but i want "Hello" and "World" printed in 2 different lines.

Use line.separator after writing word in file as:

String separator = System.getProperty("line.separator");
outputStreamWriter.write(data);
outputStreamWriter.append(separator);
...

Or you can also use replaceAll to break String in multiple lines:

String separator = System.getProperty("line.separator");
data=data.replaceAll(" ",separator);