Saturday, April 7, 2012

Finding Java Character Set/Encoding in Linux


Hi all,
I have just come to a situation where we want to know about Character set used by Java on Linux Server. So for that I have done some R&D and then find some good code that help me to find or set Character code for Java.

Below is the code. I have commented out the code for updating java Character Set.


Steps:
1.) Create a file named as CharacterEncodingExample.java.
2.) Copy & Paste the code to new created file.
3.) Compile Java source code as :
#javac CharacterEncodingExample.java
4.) Then run the compiled program.

[mc26157@ph132704]~$ java CharacterEncodingExample
defaultCharacterEncoding by property: UTF-8
defaultCharacterEncoding by code: UTF8
defaultCharacterEncoding by charSet: UTF-8

=======================================================================
import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

public class CharacterEncodingExample {

    public static void main(String args[]) throws FileNotFoundException, UnsupportedEncodingException, IOException {
        String defaultCharacterEncoding = System.getProperty("file.encoding");
        System.out.println("defaultCharacterEncoding by property: " + defaultCharacterEncoding);
        System.out.println("defaultCharacterEncoding by code: " + getDefaultCharEncoding());
        System.out.println("defaultCharacterEncoding by charSet: " + Charset.defaultCharset());
      
 /*       System.setProperty("file.encoding", "UTF-16");
      
        System.out.println("defaultCharacterEncoding by property after updating file.encoding : " + System.getProperty("file.encoding"));

        System.out.println("defaultCharacterEncoding by code after updating file.encoding : " + getDefaultCharEncoding());

        System.out.println("defaultCharacterEncoding by java.nio.Charset after updating file.encoding : " + Charset.defaultCharset());
*/
    }
  
    public static String getDefaultCharEncoding(){
        byte [] bArray = {'w'};
        InputStream is = new ByteArrayInputStream(bArray);
        InputStreamReader reader = new InputStreamReader(is);
        String defaultCharacterEncoding = reader.getEncoding();
        return defaultCharacterEncoding;
    }
}

======================================================================

Thanks!!
Kuldeep Sharma

No comments:

Post a Comment

Kubernetes 1.31 || Testing the Image Volume mount feature using Minikube

With Kubernetes new version 1.31 ( https://kubernetes.io/blog/2024/08/13/kubernetes-v1-31-release/ ) there are so many features releases for...