有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java从csv文件读取unicode字符

我有一个csv file,里面有英文单词,后面是印地语翻译。我正在尝试读取csv文件并对其进行进一步处理。csv文件如下所示:

English,,Hindi,,,  
,,,,,  
Cat,,बिल्ली,,,  
Rat,,चूहा,,,  
abandon,,छोड़ देना,त्याग देना,लापरवाही की स्वतन्त्रता,जाने देना  

我试图逐行读取csv文件并显示已写入的内容。代码片段(Java)如下所示:

   //Step 2. Read csv file and get the string.
            FileInputStream fis = null;
            BufferedReader br = null;
            try {
                fis = new FileInputStream(new File(csvFile));
            } catch (FileNotFoundException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            boolean startSeen = true;
            if(fis != null) {
                try {
                    br = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
                } catch (UnsupportedEncodingException e2) {
                    // TODO Auto-generated catch block
                    e2.printStackTrace();
                    System.out.print("Unsupported encoding");
                }
                String line = null;
                if(br != null) {
                    try {
                        while((line = br.readLine()) != null) {
                            if(line.contains("English") == true) {
                                startSeen = true;
                            }

                            if((startSeen == true) && (line != null)) {
                                StringBuffer sbuf = new StringBuffer();
                                //Step 3. Parse the line.
                                sbuf.append(line);
                                System.out.println(sbuf.toString());
                            }
                        }
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                }  
}

但是,我得到的是以下输出:

English,,Hindi,,,
,,,,,
Cat,,??????,,,
Rat,,????,,,
abandon,,???? ????,????? ????,???????? ?? ???????????,???? ????  

我的Java不是很好,虽然我已经在上面写了很多文章,但是我需要更多的帮助来找出这个问题的确切原因


共 (3) 个答案

  1. # 1 楼答案

    我认为你的控制台不能显示印地语字符。试一试

    System.out.println("Cat,,बिल्ली,,,");
    

    检验

  2. # 2 楼答案

    对于读取文本文件,最好使用字符流,例如使用java。util。直接扫描而不是FileInputStream。关于编码,您必须首先确保要读取的文本文件保存为“UTF-8”,而不是其他形式。我还注意到,在我的系统中,我必须将java源文件保存为“UTF-8”并使其正确显示印地语字符

    但是,我想建议更简单的方法来读取csv文件,如下所示:

    Scanner scan = new Scanner(new File(csvFile));
    while(scan.hasNext()){
       System.out.println(scan.nextLine());
    }
    

    see the output