简体   繁体   中英

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

Use the read method to read the file in reasonable chunks at a time and concatenate those chunks. End-lines will be preserved this way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM