Java string charset 1251

java convert String windows-1251 to utf8

First java text, String/char/Reader/Writer is internally Unicode, so it can combine all scripts. This is a major difference with for instance C/C++ where there is no such standard.

Now System.in is an InputStream for historical reasons. That needs an indication of encoding used.

Scanner sc = new Scanner(System.in, "Windows-1251"); 

The above explicitly sets the conversion for System.in to Cyrillic. Without this optional parameter the default encoding is taken. If that was not changed by the software, it would be the platform encoding. So this might have been correct too.

Now text is correct, containing the Cyrillic from System.in as Unicode.

You would get the UTF-8 bytes as:

byte[] bytes = text.getBytes(StandardCharsets.UTF_8); 

The old «recoding» of text was wrong; drop this line. in fact not all Windows-1251 bytes are valid UTF-8 multi-byte sequences.

String result = text; System.out.println(result); 

System.out is a PrintStream, a rather rarely used historic class. It prints using the default platform encoding. More or less rely on it, that the default encoding is correct.

For printing to an UTF-8 encoded file:

byte[] bytes = ("\uFEFF" + text).getBytes(StandardCharsets.UTF_8); Path path = Paths.get("C:/Temp/test.txt"); Files.writeAllBytes(path, bytes); 

Here I have added a Unicode BOM character in front, so Windows Notepad may recognize the encoding as UTF-8. In general one should evade using a BOM. It is a zero-width space (=invisible) and plays havoc with all kind of formats: CSV, XML, file concatenation, cut-copy-paste.

Solution 2

The reason why you have gotten the answer to a different question, and nobody answered yours, is because your title doesn’t fit the question. You were not attempting to convert between charsets, but rather between keyboard layouts.

Here you shouldn’t worry about character layout at all, simply read the line, convert it to an array of characters, go through them and using a predefined map convert these.

The code will be something like this:

Map table = new TreeMap(); table.put('q', 'й'); table.put('Q', 'Й'); table.put('w', 'ц'); // . etc String text = sc.nextLine(); char[] cArr = text.toCharArray(); for(int i=0; i > text = new String(cArr); System.out.println(text); 

Now, i don’t have time to test that code, but you should get the idea of how to do your task.

Источник

Читайте также:  Html переключатель on off

Функции перекодировки строк

В переменную записан текст. Текст в кодировке utf-8/koi-8/windows-1251 Мне нужны функции, которые могут переводить их в друг друга.

«функции которые могут переводить их в друг друга» Я так понимаю, это означает перекодирование из одной кодировки в дргую?

4 ответа 4

Давным-давно скопипастил/написал и использую для перекодировки такую функцию:

public static void convert( String infile, //input file name, if null reads from console/stdin String outfile, //output file name, if null writes to console/stdout String from, //encoding of input file (e.g. UTF-8/windows-1251, etc) String to) //encoding of output file (e.g. UTF-8/windows-1251, etc) throws IOException, UnsupportedEncodingException < // set up byte streams InputStream in; if(infile != null) in=new FileInputStream(infile); else in=System.in; OutputStream out; if(outfile != null) out=new FileOutputStream(outfile); else out=System.out; // Use default encoding if no encoding is specified. if(from == null) from=System.getProperty("file.encoding"); if(to == null) to=System.getProperty("file.encoding"); // Set up character stream Reader r=new BufferedReader(new InputStreamReader(in, from)); Writer w=new BufferedWriter(new OutputStreamWriter(out, to)); // Copy characters from input to output. The InputStreamReader // converts from the input encoding to Unicode,, and the OutputStreamWriter // converts from Unicode to the output encoding. Characters that cannot be // represented in the output encoding are output as '?' char[] buffer=new char[4096]; int len; while((len=r.read(buffer)) != -1) w.write(buffer, 0, len); r.close(); w.flush(); w.close(); > 

Работает как часы — с успехом кодировал даже с китайского-писишного на UTF-8. Думаю ее несложно будет приспособить под декодирование строк

Источник

Character, кодировки

Возможно, ты где-то уже слышал, что у каждого символа есть код (число). Именно поэтому тип char считается не только символьным, но и числовым типом.

Например код символа А английского алфавита – 65. B – 66, C – 67и так далее. Свои коды есть у больших букв и у маленьких, у русских букв, у китайских (ага, много, много кодов), у цифр, у различных символов – словом практически у всего, что можно назвать символом.

— Т.е. каждой букве или каждому символу соответствует какое-то число?

Символ можно преобразовать в число, а число в символ. Java вообще практически не видит разницы между ними:

char c = 'A'; //код(число) буквы А – 65 c++; //Теперь с содержит число 66 – код буквы B

— Так вот, кодировкой называется набор символов и соответствующий им набор кодов. Только таких кодировок придумали не одну, а достаточно много. А потом появилась универсальная – Unicode.

Читайте также:  Программа создать html меню

Хотя, сколько бы универсальных стандартов не придумали, от старых никто отказываться не спешит. И все получается прямо как на этой картинке:

Character, кодировки - 1

Вот представь, что Вася и Коля захотели самостоятельно придумать кодировки.

Character, кодировки - 2

Вот кодировка Васи:

Character, кодировки - 3

А вот кодировка Коли:

Они даже используют одни и те же символы, но коды у этих символов разные.

Character, кодировки - 4

И вот когда строку «ABC-123» в кодировке Васи записывают в файл, туда пишется набор байт:

А теперь этот файл хочет прочитать другая программа, которая использует кодировку Коли:

Вот что она прочитает«345-IJK»

И самое плохое то, что обычно нигде в файле тип кодировки не хранится, и разработчикам программ приходится угадывать их.

— Это отдельная тема. Но я хочу тебе рассказать, как работать с кодировками. Как ты уже знаешь, размер типа char в Java – два байта. И строки в Java имеют формат Unicode.

Но Java позволяет преобразовать строку в набор байт любой известной ей кодировки. Для этого есть специальные методы у класса String(!). Также в Java есть специальный класс Charset, который описывает конкретную кодировку.

1) Как получить список всех кодировок, с которыми Java может работать?

Для этого есть специальный статический метод availableCharsets. Этот метод возвращает набор пар (имя кодировки, объект описывающий кодировку)

SortedMap charsets = Charset.availableCharsets();

У каждой кодировки есть уникальное имя, вот некоторые из них: UTF-8, UTF-16, Windows-1251, KOI8-R,…

2) Как получить текущую активную кодировку (Unicode)?

Для этого есть специальный метод defaultCharset

Charset currentCharset = Charset.defaultCharset();

3) Как преобразовать строку в определенную кодировку?

В Java на основе строки можно создать массив байт в любой известной Java кодировке:

byte[] getBytes()
String s = "Good news everyone!"; byte[] buffer = s.getBytes()
byte[] getBytes(Charset charset)
String s = "Good news everyone!"; Charset koi8 = Charset.forName("KOI8-R"); byte[] buffer = s.getBytes(koi8);
byte[] getBytes(String charsetName)
String s = "Good news everyone!"; byte[] buffer = s.getBytes("Windows-1251")

4) А как преобразовать набор байт, которые я прочитал из файла в строку, если я знаю в какой кодировке они были в файле?

Тут все еще проще – у класса String есть специальный конструктор:

String(byte bytes[])
byte[] buffer = new byte[1000]; inputStream.read(buffer); String s = new String(buffer);
String(byte bytes[], Charset charset)
byte[] buffer = new byte[1000]; inputStream.read(buffer); Charset koi8 = Charset.forName("KOI8-R"); String s = new String(buffer, koi8);
String(byte bytes[], String charsetName)
byte[] buffer = new byte[1000]; inputStream.read(buffer); String s = new String(buffer, "Windows-1251");

5) А как преобразовать набор байт из одной кодировки в другую?

Читайте также:  Css таблица со скругленными углами

Есть много способов. Вот тебе один из самых простых:

Charset koi8 = Charset.forName("KOI8-R"); Charset windows1251 = Charset.forName("Windows-1251"); byte[] buffer = new byte[1000]; inputStream.read(buffer); String s = new String(buffer, koi8); buffer = s.getBytes(windows1251); outputStream.write(buffer);

— Я так и думал. Спасибо за интересную лекцию, Риша.

Источник

java convert String windows-1251 to utf8

I’m trying change keyboard: input cyrylic keyboard, output latin. Example: qwerty +> йцукен It doesn’t work, can anyone tell me what i’m doing wrong?

It’s not clear what you were trying to do to start with. This sort of conversion is almost always wrong.

>> It’s not clear what you were trying to do to start with. This sort of conversion is almost always wrong I’m trying change keyboard: input cyrylic keyboard, output latin. Example: QWerty +> ЙЦукен.

2 Answers 2

First java text, String/char/Reader/Writer is internally Unicode, so it can combine all scripts. This is a major difference with for instance C/C++ where there is no such standard.

Now System.in is an InputStream for historical reasons. That needs an indication of encoding used.

Scanner sc = new Scanner(System.in, "Windows-1251"); 

The above explicitly sets the conversion for System.in to Cyrillic. Without this optional parameter the default encoding is taken. If that was not changed by the software, it would be the platform encoding. So this might have been correct too.

Now text is correct, containing the Cyrillic from System.in as Unicode.

You would get the UTF-8 bytes as:

byte[] bytes = text.getBytes(StandardCharsets.UTF_8); 

The old «recoding» of text was wrong; drop this line. in fact not all Windows-1251 bytes are valid UTF-8 multi-byte sequences.

String result = text; System.out.println(result); 

System.out is a PrintStream, a rather rarely used historic class. It prints using the default platform encoding. More or less rely on it, that the default encoding is correct.

For printing to an UTF-8 encoded file:

byte[] bytes = ("\uFEFF" + text).getBytes(StandardCharsets.UTF_8); Path path = Paths.get("C:/Temp/test.txt"); Files.writeAllBytes(path, bytes); 

Here I have added a Unicode BOM character in front, so Windows Notepad may recognize the encoding as UTF-8. In general one should evade using a BOM. It is a zero-width space (=invisible) and plays havoc with all kind of formats: CSV, XML, file concatenation, cut-copy-paste.

Источник

Оцените статью