Reputation: 55
I want to save text with InputStream from EditText while preserving new lines in the text.
Here's the example of what I'm trying to do:
public void onSaveButtonClick(View v) {
try {
OutputStreamWriter out= new OutputStreamWriter(openFileOutput("STORETEXTBELESKE.txt", 0));
out.write(beleskeEditText.getText().toString());
out.close();
}
catch (Throwable t) {
Toast.makeText(this, "Exception: " + t.toString(), Toast.LENGTH_LONG).show();
}
}
And here is the part of reading the text from the saved file:
public void readSavedFile() {
try {
InputStream in = openFileInput("STORETEXTBELESKE.txt");
if (in != null) {
InputStreamReader tmp = new InputStreamReader(in);
BufferedReader reader = new BufferedReader(tmp);
String str;
StringBuilder buf = new StringBuilder();
while ((str = reader.readLine()) != null) {
buf.append(str);
}
in.close();
beleskeEditText.setText(buf.toString());
}
} catch (java.io.FileNotFoundException e) {
} catch (Throwable t) {
Toast.makeText(this, "Exception: " + t.toString(), Toast.LENGTH_LONG).show();
}
}
And it partially works. All the text is saved correctly but everything is in the same line.
So if the input is:
Test test 123
Output is: Testtest123
Upvotes: 1
Views: 2251
Reputation: 1400
Just do this
while ((str = reader.readLine()) != null) {
buf.append(str);
buf.append('\n');
}
Upvotes: 3