新行命令(“\n”)在读取文件时不起作用(Android)java
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21083171/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
New Line Command ("\n") Doesn't Working While Reading Files (Android) java
提问by semihunaldi
String mystring="Hello"+"\n"+ "World" ;
writeToFile(mystring);
String newstring = readFromFile();
mytextview.setText(newstring);
my text view just shows "HelloWorld" without newline
我的文本视图只显示没有换行符的“HelloWorld”
I Couldn't understand why It doesn't recognizes "\n"
我不明白为什么它不能识别“\n”
These are my writetofile and readfromfile functions;
这些是我的 writetofile 和 readfromfile 函数;
private void writeToFile(String data) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("myfilename", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
// Log.e(TAG, "File write failed: " + e.toString());
}
}
//////////////////////////////////////////////////
private String readFromFile() {
String ret = "";
try {
InputStream inputStream = openFileInput("myfilename");
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(TAG, "File not found: " + e.toString());
} catch (IOException e) {
// Log.e(TAG, "Can not read file: " + e.toString());
}
return ret;
}
what I am trying to do is saving a string to phone's internal storage and read back the same string .
我想要做的是将一个字符串保存到手机的内部存储并读回相同的字符串。
采纳答案by Su-Au Hwang
you are using the BufferedReader, check the documentationfor readLine() it states:
您正在使用 BufferedReader,请查看readLine()的文档,它指出:
Returns the next line of text available from this reader. A line is represented by zero or more characters followed by '\n', '\r', "\r\n" or the end of the reader. The string does not include the newline sequence.
返回此阅读器可用的下一行文本。一行由零个或多个字符后跟“\n”、“\r”、“\r\n”或读取器的结尾表示。该字符串不包括换行符序列。
you could manually add it back in your while loop, or use another readXYZ method.
您可以手动将其添加回 while 循环,或使用其他 readXYZ 方法。
回答by Siddhpura Amit
I have found the solution as suggested by Su-Au Hwang by this way
我通过这种方式找到了 Su-Au Hwang 建议的解决方案
addded manually \n by replacing ordinary \n
通过替换普通\n手动添加\n
String[] strLines = new String[lines.size()];
for (int i = 0; i < lines.size(); i++) {
lines.set(i, lines.get(i).replace("\n","\n"));
strLines[i] = lines.get(i);
}
return strLines;