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?

javaを実行した際、Eclipseとcmdで文字コード関係の挙動が違う

Posted at

発生した問題

文字コードがUTF-8のutf8-in.txtというファイルがあります。内容は以下の通りです。

utf8-in.txt
あいうえお
かきくけこ

Main.javautf-in.txtをすべて読み込み、内容を修正。それをout.txtに出力します。

Main.java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class Main {
	public static void main(String[] args) throws IOException {
		byte[] bytes = Files.readAllBytes(Paths.get("utf8-in.txt"));
		String content = "@@@" + new String(bytes) + "@@@";
		Files.write(Paths.get("out.txt"), content.getBytes());
	}
}

これをEclipseから実行します。

image.png

すると想定通り、out.txtが作成されます。

image.png

次にこのプロジェクトをsample.jarとしてエクスポートし、cmd上から実行します。

D:\temp>java -cp sample.jar Main

処理は正常に終了しますが、作成したout.txtは文字化けを起こしました。

image.png

原因

原因はEclipseとcmdでJVMのデフォルトの文字コードが違うことです。

まずEclipseではUTF-8が利用されます。

image.png

対して、cmdではMS932が利用されます。

D:\temp>jshell
|  JShellへようこそ -- バージョン17.0.8.1
|  概要については、次を入力してください: /help intro

jshell> System.getProperty("file.encoding");
$1 ==> "MS932"

対応方法

対応方法としてはデフォルトの文字コードを適切に設定することです。今回はcmdで実行する際の文字コードをUTF-8にしました。

java -Dfile.encoding=UTF-8 -cp sample.jar Main

環境情報

image.png

image.png

D:\temp>java -version
openjdk version "17.0.8.1" 2023-08-24
OpenJDK Runtime Environment Temurin-17.0.8.1+1 (build 17.0.8.1+1)
OpenJDK 64-Bit Server VM Temurin-17.0.8.1+1 (build 17.0.8.1+1, mixed mode, sharing)
0
0
1

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?