2013-02-16 61 views
-1

我是Java新手。任何人都可以向我建議如何閱讀7列的CSV文件?從java中的.csv文件讀取7列?

這裏是我的代碼:

import java.io.BufferedReader; 
import java.io.DataInputStream; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.InputStreamReader; 
import java.util.HashMap; 
import java.util.List; 
import java.util.Map; 

public class main { 

    public static Map<String,String> map1 = null; 
    public static Map<String,String> map2 = null; 

    public static void main(String[] args) { 
     try { 
      readFileandPopulate(); 
      for (Map.Entry<String, String> entry : map1.entrySet()) { 
       System.out.println("Key : " + entry.getKey() + " Value : " 
        + entry.getValue()+" address :"+map2.get(entry.getKey())); 
       //insert into DB 
      } 
     } catch (Exception e) {//Catch exception if any 
      e.printStackTrace(); 
      System.err.println("Error: " + e.getMessage()); 
     } 
    } 

    public static void readFileandPopulate() throws Exception { 
     FileInputStream fstream = new FileInputStream("/Users/Desktop/Pattern Recognition/DataSetR/1a19.csv"); 
     // Use DataInputStream to read binary NOT text. 
     BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); 
     String strLine; 
     map1 = new HashMap<String,String>(); 
     while ((strLine = br.readLine()) != null) { 
      System.out.println(strLine); 
      String temp[] = strLine.split(","); 
      map1.put(temp[0], temp[1]); 
     } 
     in.close(); 
     System.out.println("done 1"); 

    } 
} 

是否有剛剛讀幾列,並刪除其餘的數據還是可以的所有值存儲在數組,並使用數組的索引使用值來計算一個方程的任何方法?

回答

0

我會推薦使用CSV解析器,如http://opencsv.sourceforge.net/。然後,你可以做到以下幾點:

CSVReader reader = new CSVReader(new FileReader(filePath), ','); 

List<String[]> rows= reader.readAll(); 

for (String[] row : rows) 
{ 
    for (int i = 0; i < numColumnsToParse; i++) 
    { 
     //do something with row[i] 
    } 
} 
0
import java.io.FileReader; 
import java.io.IOException; 
import java.util.List; 

import au.com.bytecode.opencsv.CSVReader; 

public class ReadCSV 
{ 
    public static void main(String[] args) throws IOException 
    { 
     String[] row = null; 
     String csvFilename = "C:/Users/Hussain/Desktop/data.csv"; 
     CSVReader csvReader = new CSVReader(new FileReader(csvFilename)); 
     List content = csvReader.readAll(); 
     for (Object object : content) 
     { 
      row = (String[]) object; 
      System.out.println("value in row 7 ===>>>"+row[6]); 
     } 
     csvReader.close(); 
     } 
} 

你可以從here

添加JAR