【问题标题】:How to read a yaml file to a string with the correct indentation如何将 yaml 文件读取为具有正确缩进的字符串
【发布时间】:2017-10-09 04:50:25
【问题描述】:

我需要读取yaml 文件并将其内容发送到String

由于yaml 格式需要正确的缩进,我必须得到文件中的确切内容。在java 中读取文件的正常方式对我不起作用。

如果有人能告诉我如何将yaml 文件的内容读入String 变量。

问题又来了,

如何读取带有缩进和空格的yaml文件的内容并将文件的内容放入java中的String变量中?换句话说,我需要 yaml 文件的内容,因为它是 String 变量。

【问题讨论】:

  • 什么是“Java读取文件的正常方式”?
  • 使用 BufferReader 和 FileReader,这个方法只是逐行读取文件。我可以使用正确的缩进将其打印出来,但无法将内容转换为字符串。
  • 您可以连接这些行,但不读取行而是读取字符块并将它们放入 StringBuilder 可能更容易。
  • 谢谢,在我第一次尝试连接这些行时,出现了一个愚蠢的错误。现在想通了。

标签: java yaml


【解决方案1】:

不管怎样,你已经明白了,但这里是正确缩进的代码。

package test;

import java.io.BufferedReader;
import java.io.FileReader;

public class test {
    private static String FILENAME = "input.txt";

    public static void main(String[] args) {
        BufferedReader br = null;
        FileReader fr = null;
        StringBuffer stringBuffer = new StringBuffer();
        try {
            fr = new FileReader(FILENAME);
            br = new BufferedReader(fr);
            String sCurrentLine;

            while ((sCurrentLine = br.readLine()) != null) {
                stringBuffer.append(sCurrentLine);
                stringBuffer.append("\n");

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                br.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.out.println(stringBuffer);
    }
}

【讨论】:

    猜你喜欢
    • 2021-10-06
    • 1970-01-01
    • 2020-10-16
    • 2017-11-26
    • 1970-01-01
    • 2018-05-22
    • 1970-01-01
    • 2019-07-05
    • 1970-01-01
    相关资源
    最近更新 更多