Copy Code code as follows:
Package com.huateng.readcsv;
Import Java.io.BufferedReader;
Import Java.io.FileReader;
Import java.util.ArrayList;
Import Java.util.Iterator;
Import java.util.List;
public class Csvutil {
Private String fileName = null;
Private BufferedReader br = NULL;
Private list<string> List = new arraylist<string> ();
Public Csvutil () {
}
Public Csvutil (String fileName) throws Exception {
This.filename = FileName;
br = new BufferedReader (fileName) (new FileReader);
String stemp;
while ((stemp = Br.readline ())!= null) {
List.add (stemp);
}
}
Public List getlist () {
return list;
}
/**
* Get the number of rows
* @return
*/
public int Getrownum () {
return List.size ();
}
/**
* Get the number of columns
* @return
*/
public int Getcolnum () {
if (!list.tostring (). Equals ("[]")) {
if (list.get (0). ToString (). Contains (",")) {//CSV is a comma-delimited file
Return List.get (0). ToString (). Split (","). Length;
else if (list.get (0). toString (). Trim (). Length ()!= 0) {
return 1;
} else {
return 0;
}
} else {
return 0;
}
}
/**
* Get the development line
* @param index
* @return
*/
Public String getRow (int index) {
if (this.list.size ()!= 0) {
Return (String) list.get (index);
} else {
return null;
}
}
/**
* Get the specified column
* @param index
* @return
*/
Public String getcol (int index) {
if (this.getcolnum () = = 0) {
return null;
}
StringBuffer sb = new StringBuffer ();
String tmp = NULL;
int colnum = This.getcolnum ();
if (Colnum > 1) {
for (Iterator it = List.iterator (); It.hasnext ();) {
TMP = It.next (). toString ();
SB = Sb.append (Tmp.split (",") [index] + ",");
}
} else {
for (Iterator it = List.iterator (); It.hasnext ();) {
TMP = It.next (). toString ();
SB = sb.append (tmp + ",");
}
}
String str = new String (sb.tostring ());
str = str.substring (0, Str.length ()-1);
return str;
}
/**
* Get a cell
* @param row
* @param col
* @return
*/
Public String getString (int row, int col) {
String temp = null;
int colnum = This.getcolnum ();
if (Colnum > 1) {
temp = list.get (row). ToString (). Split (",") [Col];
else if (Colnum = 1) {
temp = list.get (row). ToString ();
} else {
temp = null;
}
return temp;
}
public void Csvclose () throws exception{
This.br.close ();
}
public static void Main (string[] args) throws Exception {
Csvutil util = new Csvutil ("D:\\demo.csv");
int rownum = Util.getrownum ();
int colnum = Util.getcolnum ();
String x = Util.getrow (2);
String y = util.getcol (2);
System.out.println ("rownum:" + rownum);
System.out.println ("Colnum:" + colnum);
System.out.println ("x:" + x);
System.out.println ("y:" + y);
for (int i=1;i<rownum;i++) {
for (int j=0;j<colnum;j++) {
System.out.println ("result[" + i + "|" + J + "]:" + util.getstring (i, j));
}
}
}
}