Java Files read text by Charset via byte array

Description

Java Files read text by Charset via byte array

import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;

public class Main {

  public static void main(String[] args) throws Exception{
    String path = "Main.java";
    byte[] encodedBytes = Files.readAllBytes(Paths.get(path));
    String result = new String(encodedBytes, Charset.forName("US-ASCII"));
    System.out.println(result);/*from  w w  w.  j  a v  a2s  .  co m*/
    
    encodedBytes = Files.readAllBytes(Paths.get(path));
    result =  new String(encodedBytes, Charset.forName("ISO-8859-1"));
    
    encodedBytes = Files.readAllBytes(Paths.get(path));
    result =  new String(encodedBytes, Charset.forName("UTF-8"));

    encodedBytes = Files.readAllBytes(Paths.get(path));
    result =  new String(encodedBytes, Charset.forName("UTF-16BE"));

    encodedBytes = Files.readAllBytes(Paths.get(path));
    result =  new String(encodedBytes, Charset.forName("UTF-16LE"));
    
    encodedBytes = Files.readAllBytes(Paths.get(path));
    result =  new String(encodedBytes, Charset.forName("UTF-16"));  }
}



PreviousNext

Related