繁体   English   中英

读取txt文件时检测换行符-Android

[英]Detect newlines while reading a txt file - 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;
}

我需要帮助。

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

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

那是你想做什么?

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

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

您获得的每个“行”实例都以一种或另一种方式终止(\\ r,\\ n或\\ r \\ n)。 因此,代替更换,您可以执行类似的操作

text.append(line + "\n");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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