0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Javaからyamlを生成してファイルに書き込む

Last updated at Posted at 2021-06-01

はじめに

Selenideでテスト自動化をした際に、シナリオA→Bでデータの受け渡しをする上でyamlに書き込みをしたい場面があった。その時の実装の備忘録を残しておく。

Javaでyamlを生成してファイルに書き込む

snakeyamlOutputStreamWriter・BufferedWriterを使って簡単にできる。
OutputStreamWriterを使う理由は、書き込み時の文字コードを指定し文字化けを防ぐため。

sample.java
User user = new User();
user.setId("12345");
user.setName("hoge hoge");

Yaml yaml = new Yaml();   // org.yaml.snakeyaml
File file = new File("C:\\temp\\test.yaml");

OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");   // 文字コードを指定するためにOutputStreamWriterを使う
BufferedWriter bw = new BufferedWriter(osw);
bw.write(yaml.dump(user));   // クラスのインスタンス(オブジェクト)
bw.close();
User.java
@Data
public class User {
    private String id;
    private String name;
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?