当前位置:首页 > 开发 > 编程语言 > Java > 正文

JAVA CSV文件读写

发表于: 2015-02-25   作者:cielwp   来源:转载   浏览:
摘要: package com.huifu.uss.common.util; import static org.junit.Assert.fail; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStrea
package com.huifu.uss.common.util;

import static org.junit.Assert.fail;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import org.junit.Assert;
import org.junit.Test;

import au.com.bytecode.opencsv.CSVParser;
import au.com.bytecode.opencsv.CSVReader;
import au.com.bytecode.opencsv.CSVWriter;

/**
 * test for au.com.bytecode.opencsv
 * @author peng.wang
 * 2015/02/25
 */
public class OpenCsvTest {
	File localFile = new File("D:\\test.csv");
	String[] info = {"Hello","OpenCsv"};
	private CSVWriter csvWriter;
	private CSVReader csvReader;

	@Test
	public void testRead() {
		try{
			FileInputStream fis = new FileInputStream(localFile);	
			BufferedReader bf = new BufferedReader(new InputStreamReader(fis,"GBK"));
			csvReader = new CSVReader(bf, CSVParser.DEFAULT_SEPARATOR);
			while(true){
				String [] line = csvReader.readNext();
				if(line == null){
					break;
				}
				Assert.assertSame(line.length,2);
				Assert.assertEquals(line[0], info[0]);
				Assert.assertEquals(line[1], info[1]);
			}
		}catch(Exception e){
			e.printStackTrace();
			fail("exception happend");
		}
	}
	
	@Test
	public void testWrite(){
		try{
			FileOutputStream fos = new FileOutputStream(localFile);
			OutputStreamWriter osw = new OutputStreamWriter(fos,"GBK");
			csvWriter = new CSVWriter(osw, CSVParser.DEFAULT_SEPARATOR);
			csvWriter.writeNext(info);
			csvWriter.flush();
		}catch(Exception e){
			e.printStackTrace();
			fail("exception happend");
		}
	}

}
 

 

JAVA CSV文件读写

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号