Skip to content

Instantly share code, notes, and snippets.

@nerestaren
Last active September 28, 2017 22:06
Show Gist options
  • Save nerestaren/88cbd1a922856a622c039418ca494b6c to your computer and use it in GitHub Desktop.
Save nerestaren/88cbd1a922856a622c039418ca494b6c to your computer and use it in GitHub Desktop.
Java System.in System.out encoding playground
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package encoding;
import java.io.*;
/**
*
* @author Antoni
*/
public class Encoding {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
String inputEncoding;
BufferedReader in = null;
char lastCharacter = '\0';
char c;
BufferedReader tmp = new BufferedReader(new InputStreamReader(System.in));
// INPUT ENCODING
System.out.printf("Type the input encoding. Examples: %n"
+ " Netbeans: ISO-8859-1 (n)%n"
+ " Windows CMD: cp850 (c)%n"
+ " BufferedReader with default encoding (.)%n"
+ " or skip to use System.in directly%n"
+ ">");
inputEncoding = tmp.readLine();
switch (inputEncoding) {
case "n":
inputEncoding = "ISO-8859-1";
break;
case "c":
inputEncoding = "cp850";
break;
}
if (!inputEncoding.equals("")) {
if (inputEncoding.equals(".")) {
in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Using BufferedReader with default encoding");
} else {
in = new BufferedReader(new InputStreamReader(System.in, inputEncoding));
System.out.printf("Using BufferedReader with %s%n", inputEncoding);
}
} else {
System.out.println("Using System.in");
}
System.out.println("");
// MAIN
System.out.println("I will tell you what character you typed. Type the same character twice to exit");
while (true) {
System.out.println("Type a character");
System.out.print(">");
if (in != null) {
// Use an encoding
c = (char) in.read();
in.readLine();
} else {
// Use System.in
c = (char) System.in.read();
while (System.in.available() > 0) {
System.in.read();
}
}
System.out.printf("You typed '%c'. Dec: %d. Hex: %02X%n", c, (int) c, (int) c);
if (c == lastCharacter) {
break;
}
lastCharacter = c;
}
System.out.println("Goodbye!");
}
}
@nerestaren
Copy link
Author

Ignoring the output encoding.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment