Javaはマルチプラットフォームに対応しているため、特定のハードウェアやOSに依存しません。どんなOSでも同じように動作するのがJavaの強みですね。
ただ、OSによって一部動作が異なるものがあります。その1つが改行コードです。
例えば、以下コードの場合、Mac OS X(10以降)やLinuxでは改行されますが、WindowsやMac OS(9以前)では改行されません。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
System.out.println("Hello\nWorld"); // -> WindowsやMac OS(9以前)では改行されない |
これは、OSによって改行を指示するための改行コードが異なるからです。参考までに、以下にOSごとの改行コードを載せます。
- Windows:CR + LF(\r\n)
- Mac OS(9以前):CR(\r)
- Mac OS X(10以降):LF(\n)
- Linux:LF(\n)
そこでこの記事では、Javaで環境依存せずに改行コードを取得・設定する方法をご紹介します。
環境依存せずに改行コードを取得・設定する方法
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
String br = System.getProperty("line.separator"); | |
System.out.println("Hello" + br + "World"); // -> HelloとWorldの間に改行 |
line.separator
システムプロパティを利用することで、現在動作中のOSが採用している改行コード(\r\nや\n)を取得することができます。
あとは、取得した改行コードを適切な箇所に設定してやればOKです。
まとめ
Javaで環境依存せずに改行コードを取得・設定する方法をご紹介しました。
本内容は以下書籍を参考にしました。Java初心者から中級者になるためのエッセンスが詰まっている良書です。
スッキリわかる Java入門 実践編 第2版 (スッキリシリーズ)
- 中山 清喬
- インプレス
- 価格¥700(2025/04/01 16:22時点)
- 発売日2014/09/22
- 商品ランキング286,359位