{Java}ファイルの文字コード変換

https://www.zunouissiki.com/java-file-convert-sjis-utf8/


notepad a.java

 

import java.io.*;
import java.nio.file.*;


public class a {
  public static void main(String args) throws Exception {
  
    String targetFilePath = null;
    byte
data = null;
    String outPut = null;

    FileOutputStream fos = null;
    BufferedOutputStream bos = null;
    OutputStreamWriter osw = null;

    // テストファイル作成

    outPut = "H:\\tmp\\test1.txt";

    fos = new FileOutputStream(outPut);
    bos = new BufferedOutputStream(fos);
    osw = new OutputStreamWriter(bos, "MS932");
    osw.write("テストファイルです");

    osw.close();
    bos.close();
    fos.close();


    // SJIS -> UTF8

    targetFilePath = "H:\\tmp\\test1.txt";
    data = Files.readAllBytes(Paths.get(targetFilePath));
    outPut = "H:\\tmp\\text2.txt";

    fos = new FileOutputStream(outPut);
    bos = new BufferedOutputStream(fos);
    osw = new OutputStreamWriter(bos, "UTF-8");
    osw.write(new String(data, "MS932") );

    osw.close();
    bos.close();
    fos.close();

 

    // UTF8 -> SJIS

    targetFilePath = "H:\\tmp\\test2.txt";
    data = Files.readAllBytes(Paths.get(targetFilePath));
    outPut = "H:\\tmp\\text3.txt";


    fos = new FileOutputStream(outPut);
    bos = new BufferedOutputStream(fos);
    osw = new OutputStreamWriter(bos, "MS932");
    osw.write(new String(data, "UTF-8"));

    osw.close();
    bos.close();
    fos.close();


  }
}

 

javac -encoding utf-8 a.java
java a