使用Java操作CSV文件

网上找了个开源实现,用用还不错。因为项目中经常要用到,而我又很容易忘记。为了节省今后使用时到网上漫天寻找的时间,我决定在这做个笔记。

CSV读写开源实现主页:http://opencsv.sourceforge.net

 

import  java.io.File;
import  java.io.FileReader;
import  java.io.FileWriter;
import  java.io.IOException;
import  java.io.StringReader;
import  java.util.List;

import  au.com.bytecode.opencsv.CSVReader;
import  au.com.bytecode.opencsv.CSVWriter;
import  au.com.bytecode.opencsv.bean.ColumnPositionMappingStrategy;
import  au.com.bytecode.opencsv.bean.CsvToBean;

public   class  CsvDemo {
    
    
public   static   void  main(String[] args)  throws  IOException {
        
        
final  String[] header  =   new  String[]{ " name " " sex " " age " };
        
final  String[][] data  =   new  String[][]{header, { " Lucy " " F " " 22 " }, { " Tom " " M " " 25 " }, { " Lily " " F " " 19 " }};

        File tempFile 
=  File.createTempFile( " csvWriterTest " " .csv " );
        tempFile.deleteOnExit();

        CSVWriter writer 
=   new  CSVWriter( new  FileWriter(tempFile));
        
for  ( int  i  =   0 ; i  <  data.length; i ++ ) {
            writer.writeNext(data[i]);
        }
        writer.close();

        CSVReader reader 
=   new  CSVReader( new  FileReader(tempFile));
        String[] line;
        String readline 
=   "" ;
        
for  ( int  row  =   0 ; (line  =  reader.readNext())  !=   null ; row ++ ) {
            
for  ( int  col  =   0 ; col  <  line.length; col ++ ) {
                
if  (data[row][col]  !=   null ) {
                    System.out.print(line[col] 
+  (col  !=  line.length  -   1   ?   " , "  :  "" ));
                    readline 
=  readline  +  line[col]  +  (col  !=  line.length  -   1   ?   " , "  :  "   " );
                }
            }
            System.out.println(
"" );
        }
        
        ColumnPositionMappingStrategy strat 
=   new  ColumnPositionMappingStrategy();
        strat.setType(Person.
class );
        String[] columns 
=   new  String[] { " name " " sex " " age " };
        strat.setColumnMapping(columns);
        CsvToBean csv 
=   new  CsvToBean();
        List
 persons  =  csv.parse(strat,  new  StringReader(readline));
        
for  ( int  i  =   1 ; i  <  persons.size(); i ++ ) {
            System.out.println(((Person)persons.get(i)).getName());
            System.out.println(((Person)persons.get(i)).getSex());
            System.out.println(((Person)persons.get(i)).getAge());
        }
        
        reader.close();
    }
}


这是另一个开源实现:http://sourceforge.net/projects/javacsv/

 测试代码是网上考来的。因为用的日文系统,下面解析csv文件时使用了shift_jis编码方式。

 

import  java.awt.Dimension;
import  java.awt.GridLayout;
import  java.nio.charset.Charset;
import  java.util.ArrayList;
import  java.util.List;
import  javax.swing.JFrame;
 
import  javax.swing.JPanel;
import  javax.swing.JScrollPane;
import  javax.swing.JTable;

public   class  CSVReaderDemo  extends  JPanel{
    
    
private  String filePath  =   " d://sample.csv " ;
    
    
public  CSVReaderDemo() {
        
super ( new  GridLayout( 1 , 0 ));
        
try  {
            CsvReader reader 
=   new  CsvReader(filePath, ' , ' ,Charset.forName( " shift_jis " ));
            reader.readHeaders();
            String[] headers 
=   reader.getHeaders();
            
// int headerCount = reader.getHeaderCount();
            
// int col = reader.getColumnCount();
            List < Object[] >  list  =   new  ArrayList < Object[] > ();
            
while (reader.readRecord()) list.add(reader.getValues());
            Object[][] data 
=   new  String[list.size()][];
            
for ( int  i = 0 ; i < list.size(); i ++ ) data[i]  =  list.get(i);  
            
final  JTable table  =   new  JTable(data, headers);
            table.setPreferredScrollableViewportSize(
new  Dimension( 500 70 ));
            
// table.setFillsViewportHeight(true);
            JScrollPane scrollPane  =   new  JScrollPane(table);
            add(scrollPane);
        } 
catch  (Exception ex) {
            ex.printStackTrace();
        }
    }

    
private   static   void  createAndShowGUI(){
        JFrame frame 
=   new  JFrame( " SimpleTableDemo " );
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        CSVReaderDemo newContentPane 
=   new  CSVReaderDemo();
        newContentPane.setOpaque(
true );  // content panes must be opaque
        frame.setContentPane(newContentPane);
        frame.pack();
        frame.setVisible(
true );
    }
    
    
public   static   void  main(String[] args){
        javax.swing.SwingUtilities.invokeLater(
new  Runnable() {
            
public   void  run() {
                createAndShowGUI();
            }
        });
    } 
}



该文章转载自网络大本营:http://www.xrss.cn/Dev/JAVA/200811618518.Html

你可能感兴趣的:(java基础,csv,java,import,string,object,header)