从System.in流中读取和写入UTF-8字符 [英] Read and Write UTF-8 characters from System.in stream

查看:162
本文介绍了从System.in流中读取和写入UTF-8字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用System.out流的print方法在控制台上打印诸如ελληνικά之类的Unicode字符串,则按预期进行打印(因为我在支持UTF字符的输出控制台中使用Ubuntu mono ).

if i print unicode String like ελληνικά on the console using the print method of System.out stream, its printed as expected (As i use Ubuntu mono in my output console which supports UTF characters).

但是,如果我尝试使用System.in流从控制台读取具有UTF-8编码的Unicode字符,它将无法正确读取. 我尝试了许多不同的方法来使用System.in流中的各种读取器类来实现它,但是它永远无法正常工作.有谁知道我可以做到的方式

But if i try to read from the console unicode characters with UTF-8 encoding using System.in stream, it doesn't read properly. I have tried many different ways to achieve it using various reader classes with the System.in stream but it never works. So does anyone know a way i could do that

以下是代码示例

BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in, "UTF-8"));
BufferedWriter console = new BufferedWriter(new OutputStreamWriter(System.out, "UTF-8"));

console.write("p1: Γίνεται πάντως\n");
console.flush();
System.out.println("p2: Γίνεται πάντως");

byte dataBytes[] = keyboard.readLine().getBytes(Charset.forName("UTF-8"));
System.out.println("p3: " + new String(dataBytes));
console.write("p4: " + new String(dataBytes, "UTF-8") + "\n");
console.flush();
Scanner scan = new Scanner(System.in, "UTF-8");

System.out.println("p5: " + (char) System.in.read());
System.out.println("p6: " + scan.nextLine());
System.out.println("p7: " + keyboard.readLine());

以及我的控制台上的输出:

and the output on my console:

p1: Γίνεται πάντως
p2: Γίνεται πάντως
Δέν
p3: ���
p4: ���
Δέν
p5: Ä
p6: ��
Δέν
p7: ���

我的IDE是Netbeans

my IDE is Netbeans

推荐答案

尝试使用java.io.Console.readLine()java.io.Console.readLine(String, Object...). Console实例由System.console()方法返回.例如:

Try using java.io.Console.readLine() or java.io.Console.readLine(String, Object...). Console instance is returned by System.console() method. For example:

package package01;

import java.io.Console;

public class Example {

    public static void main(String[] args) {
        Console console = System.console();
        if (console == null) {
            System.err.println("No console");
            System.exit(1);
        }
        String s = console.readLine("Enter string: ");
        System.out.println(s);
    }

}

这篇关于从System.in流中读取和写入UTF-8字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆