在阅读文本文件时检测新行 - Android

时间:2014-04-03 11:31:29

标签: java android

我有一个简单的应用程序,它读取一个txt文件并将其放在EditText视图中。 一切都很好,除了我无法检测txt文件中的换行符并将其替换为“\ n”。

  

例如:       我的文件中有这个文字

    this
    is
    a
    file
    with
    newline

but this is what I get in the Edittext view:

    thisisafilewithnewline.

这是我的代码:

private String onFileClick(Option o){

    StringBuilder text = new StringBuilder();//--read text from file---
    String filePath = o.getPath();
    String CHARSET = "ISO-8859-1";
    String fileType = MimeTypeMap.getFileExtensionFromUrl(filePath);
    String NOT_TXT = "NOT TXT FILE";

    try{
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), CHARSET));
        String line;
        while((line = br.readLine()) != null){
            text.append(line.replaceAll("\r\n", "\n"));
        }
        br.close();
    }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());
    }

    if(fileType.equals("txt"))
        return text.toString();
    else
        return NOT_TXT;
}

我需要帮助。

3 个答案:

答案 0 :(得分:2)

您需要阅读Javadoc。 readLine()方法删除行终止符。

答案 1 :(得分:2)

text.append(line+"\n");// this will add new line into your string after reading

是你想要做的吗?

答案 2 :(得分:1)

reader.readLine()函数删除API文档中指定的回车符和换行符:

http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#readLine()

您获得的每个“行”实例都以这种或那种方式终止(\ r,\ n或\ r \ n)。 因此,不是替换你可以做类似

的事情
text.append(line + "\n");
相关问题