[英]Line breaks are lost when saving a string to internal storage and retrieving it. How do I preserve line breaks?
The original string has line breaks. 原始字符串有换行符。 I am saving the string in one activity and retrieving it in another.
我将字符串保存在一个活动中并在另一个活动中检索它。
Here the code I use to write to Internal Storage 这里是我用来写入内部存储的代码
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput(FILENAME, Context.MODE_PRIVATE));
outputStreamWriter.write(strText);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
Here is the code I use to read 这是我用来阅读的代码
InputStream inputStream = openFileInput(FILENAME);
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());
}
SomeArray.add(ret);
The code works only problem is that im losing my line breaks. 代码工作的唯一问题是我失去了我的换行符。
I fixed it by changing the while loop to 我通过改变while循环来修复它
while ( (receiveString = bufferedReader.readLine()) != null ) {
ret += receiveString + "\n";
}
readLine strips the end-line characters: http://docs.oracle.com/javase/6/docs/api/java/io/BufferedReader.html#readLine() readLine剥离结束字符: http : //docs.oracle.com/javase/6/docs/api/java/io/BufferedReader.html#readLine()
Use the read method to read the file in reasonable chunks at a time and concatenate those chunks. 使用read方法一次以合理的块读取文件并连接这些块。 End-lines will be preserved this way.
终点线将以这种方式保留。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.