Java 读取 CSV 文件

这篇博客讨论了在Windows XP系统下,由于Excel保存的CSV文件编码问题导致的乱码现象。作者提供了四种Java读取CSV文件的方法,包括指定GBK编码、UTF-8编码以及使用opencsv和javacsv库,强调了在不同编码环境下正确读取CSV文件的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

操作系统默认内部编码一般并不是GB18030,目前已知在WINDOWS XP操作系统中,进行某些组件的升级后,会把操作系统的默认编码由GB2312变更为GB18030。所以我们用 Excel 将文档存储为 CSV 文档后,该 CSV 文档的编码为ANSI。如果当我们改变 CSV 文档的编码格式,由于 Excel 还是按照 ANSI 编码来读取文档的,所以会出现乱码。
eclipse默认编码与操作系统的默认编码一致为 GBK,在实际开发中我们的项目编码被设置为 UTF-8,而 csv 文档却是 ansi 格式,所以要求读取 CSV 文档显示的指定文档的编码格式;
常见的几种读取方式如下:
方式一:
a1.csv编码为ANSI,java源文件编码为utf-8读取文档的示例代码:
    DataInputStream in = new DataInputStream(new FileInputStream(new File("e://a1.csv")));
    BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(in,"GBK"));
    String stemp;  
       while((stemp = bufferedreader.readLine()) != null){ 
           System.out.println(stemp);
       }
该方式同样适合读取utf-8编码的csv文档。
    DataInputStream in = new DataInputStream(new FileInputStream(new File("e://aUTF8.csv")));
    BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
    String stemp;  
       while((stemp = bufferedreader.readLine()) != null){ 
           System.out.println(stemp);
       }
方式二:
以下代码由于没有指定源文件的编码方式,所以只适合a1.csv编码为ANSI,java源文件编码为GBK的场景。在实际应用中局限性很大,不推荐使用者种方式。在此列出只为学习和使用该方式出错后找错误用。
    BufferedReader bufferedreader = new BufferedReader(new FileReader("e://a1.csv"));
    String stemp;  
       while((stemp = bufferedreader.readLine()) != null){ 
           System.out.println(stemp);
       }
方式三:
使用 opencsv.jar读取utf-8编码的csv示例代码:
    CSVReader reader = new CSVReader(new FileReader("e://aUTF8.csv"));
    String [] nextLine;
    while ((nextLine = reader.readNext()) != null) {
         // nextLine[] is an array of values from the line
         System.out.println(nextLine[0] + nextLine[1] + ":"+nextLine[2]+":"+nextLine[3]);
    }
指定编码方式示例代码:
    DataInputStream in = new DataInputStream(new FileInputStream(new File("e://aUTF8.csv")));
    CSVReader reader = new CSVReader(new InputStreamReader(in,"utf-8"),',');
    String [] nextLine;       
    while ((nextLine = reader.readNext()) != null) {
            // nextLine[] is an array of values from the line
            System.out.println(nextLine[0] + nextLine[1] + ":"+nextLine[2]+":"+nextLine[3]);
    }

方式四:javacsv.jar 读取

方式五:jxl 读取

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值