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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6126164/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 14:25:45  来源:igfitidea点击:

How can I read a .txt file into a single Java string while maintaining line breaks?

javastringfile

提问by slashline

Virtually every code example out there reads a TXT file line-by-line and stores it in a String array. I do not want line-by-line processingbecause I think it's an unnecessary waste of resources for my requirements: All I want to do is quickly and efficiently dump the .txt contents into a single String. The method below does the job, however with one drawback:

实际上,那里的每个代码示例都逐行读取 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);
}

... the drawback is that the line breaks are converted into long spaces e.g. "                                 ".

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

I want the line breaks to be converted from \n or \r to <br> (HTML tag) instead.

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

Thank you in advance.

先感谢您。

采纳答案by user unknown

What about using a Scanner and adding the linefeeds yourself:

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

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

I don't see where you get your long spaces from.

我不知道你从哪里得到长空格。

回答by Robert

You can read directly into the buffer and then create a String from the buffer:

您可以直接读入缓冲区,然后从缓冲区创建一个字符串:

    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");

回答by Fabrizio D'Ammassa

You could add this code:

您可以添加以下代码:

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

Is this what you are looking for?

这是你想要的?

回答by d-live

The code will read the file contents as they appear in the file - including line breaks. If you want to change the breaks into something else like displaying in html etc, you will either need to post process it or do it by reading the file line by line. Since you do not want the latter, you can replace your return by following which should do the conversion -

该代码将读取文件中出现的文件内容 - 包括换行符。如果您想将中断更改为其他内容,例如在 html 中显示等,您将需要对其进行后期处理或通过逐行读取文件来完成。由于您不想要后者,您可以通过以下应该进行转换来替换您的回报 -

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

回答by james

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

        }

your resulting String: String result = sb.toString();

你的结果StringString result = sb.toString();

then replace whatever you want in this result.

然后替换你想要的任何东西result

回答by Sanket Patel

You should try org.apache.commons.io.IOUtils.toString(InputStream is) to get file content as String. There you can pass InputStream object which you will get from

您应该尝试 org.apache.commons.io.IOUtils.toString(InputStream is) 以字符串形式获取文件内容。在那里你可以传递 InputStream 对象,你将从

getAssets().open("xml2json.txt")    *<<- belongs to Android, which returns InputStream* 

in your Activity. To get String use this :

在您的活动中。要获得 String 使用这个:

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

So,

所以,

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

回答by demongolem

I agree with the general approach by @Sanket Patel, but using Commons I/O you would likely want File Utils.

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

So your code word look like:

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

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

There is also another version to specify an alternate character encoding.

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