如何在保持换行符的同时将.txt文件读入单个Java字符串?

时间:2011-05-25 14:36:21

标签: java string file

几乎每个代码示例都会逐行读取TXT文件并将其存储在String数组中。 我不想逐行处理,因为我认为这对我的要求是不必要的资源浪费:我想做的就是快速有效地将.txt内容转储到单个字符串中。下面的方法完成了这项工作,但有一个缺点:

private static String readFileAsString(String filePath) throws java.io.IOException{
    byte[] buffer = new byte[(int) new File(filePath).length()];
    BufferedInputStream f = null;
    try {
        f = new BufferedInputStream(new FileInputStream(filePath));
        f.read(buffer);
        if (f != null) try { f.close(); } catch (IOException ignored) { }
    } catch (IOException ignored) { System.out.println("File not found or invalid path.");}
    return new String(buffer);
}

......缺点是换行符被转换为长空格,例如“”。

我希望换行符从\ n或\ r \ n转换为< br> (HTML标签)改为。

提前谢谢。

7 个答案:

答案 0 :(得分:3)

如何使用扫描仪并自行添加换行符:

sc = new java.util.Scanner ("sample.txt")
while (sc.hasNext ()) {
   buf.append (sc.nextLine ());
   buf.append ("<br />");
}

我看不到你从哪里获得长距离。

答案 1 :(得分:3)

您可以直接读入缓冲区,然后从缓冲区中创建一个String:

    File f = new File(filePath);
    FileInputStream fin = new FileInputStream(f);
    byte[] buffer = new byte[(int) f.length()];
    new DataInputStream(fin).readFully(buffer);
    fin.close();
    String s = new String(buffer, "UTF-8");

答案 2 :(得分:1)

您可以添加以下代码:

return new String(buffer).replaceAll("(\r\n|\r|\n|\n\r)", "<br>");

这是你在找什么?

答案 3 :(得分:1)

代码将读取文件中显示的文件内容 - 包括换行符。 如果你想把休息改成其他东西,比如在html等中显示,你需要发布它或者通过逐行读取文件来进行处理。由于您不需要后者,因此您可以按照应该进行转换来替换您的回报 -

return (new String(buffer)).replaceAll("\r[\n]?", "<br>");

答案 4 :(得分:0)

StringBuilder sb = new StringBuilder();
        try {
            InputStream is = getAssets().open("myfile.txt");
            byte[] bytes = new byte[1024];
            int numRead = 0;
            try {
                while((numRead = is.read(bytes)) != -1)
                    sb.append(new String(bytes, 0, numRead));
            }
            catch(IOException e) {

            }
            is.close();
        }
        catch(IOException e) {

        }

结果StringString result = sb.toString();

然后在此result中替换您想要的任何内容。

答案 5 :(得分:0)

您应该尝试使用org.apache.commons.io.IOUtils.toString(InputStream is)将文件内容作为String。在那里你可以传递你将从

获得的InputStream对象
getAssets().open("xml2json.txt")    *<<- belongs to Android, which returns InputStream* 

在你的活动中。要获得String,请使用:

String xml = IOUtils.toString((getAssets().open("xml2json.txt")));

所以,

String xml = IOUtils.toString(*pass_your_InputStream_object_here*);

答案 6 :(得分:0)

我同意@Sanket Patel的一般方法,但是使用Commons I / O你可能需要File Utils

所以你的代码字看起来像:

String myString = FileUtils.readFileToString(new File(filePath));

还有另一个版本可以指定备用字符编码。