将字符串保存到内部存储并检索它时,换行符会丢失。如何保留换行符?

时间:2013-12-01 23:36:23

标签: java android line-breaks 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());
        } 

以下是我用来阅读的代码

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

代码工作的唯一问题是我失去了我的换行符。

2 个答案:

答案 0 :(得分:3)

我通过将while循环更改为

来修复它
 while ( (receiveString = bufferedReader.readLine()) != null ) {

                        ret += receiveString + "\n";
                    }

答案 1 :(得分:0)

readLine剥离结束字符: http://docs.oracle.com/javase/6/docs/api/java/io/BufferedReader.html#readLine()

使用read方法一次以合理的块读取文件并连接这些块。终点线将以这种方式保留。