java有專門操作CSV文件的類和方法。java開源框架csvreader提供了一個輕量級的、簡單方便的統(tǒng)一操作接口可用。要使用CsvReader,CsvWriter需要下載一個javacsv.jar導(dǎo)入到項目中才行,在項目上點擊右鍵--屬性--庫--添加jar文件,選擇javacsv.jar文件即可,然后在程序中用import
網(wǎng)站建設(shè)哪家好,找成都創(chuàng)新互聯(lián)公司!專注于網(wǎng)頁設(shè)計、網(wǎng)站建設(shè)、微信開發(fā)、微信小程序定制開發(fā)、集團企業(yè)網(wǎng)站建設(shè)等服務(wù)項目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了依蘭免費建站歡迎大家使用!
com.csvreader.CsvReader,import com.csvreader.CsvWriter導(dǎo)入即可。
示范代碼:
package test;
import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class readandwrite {
public static void main(String[] args) throws IOException {
String [] str = {"省","市","區(qū)","街","路","里","幢","村","室","園","苑","巷","號"};
String inString = "";
String tmpString = "";
File inFile = new File("C://in.csv"); // 讀取的CSV文件
File outFile = new File("C://outtest.csv");//輸出的CSV文
try {
BufferedReader reader = new BufferedReader(new FileReader(inFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(outFile));
CsvReader creader = new CsvReader(reader, ',');
CsvWriter cwriter = new CsvWriter(writer,',');
while(creader.readRecord()){
inString = creader.getRawRecord();//讀取一行數(shù)據(jù)
for(int i = 0;i str.length;i++){
tmpString = inString.replace(str[i], "," + str[i] + ",");
inString = tmpString;
}
//第一個參數(shù)表示要寫入的字符串數(shù)組,每一個元素占一個單元格,第二個參數(shù)為true時表示寫完數(shù)據(jù)后自動換行
cwriter.writeRecord(inString.split(","), true);
//注意,此時再用cwriter.write(inString)方法寫入數(shù)據(jù)將會看到只往第一個單元格寫入了數(shù)據(jù),“,”沒起到調(diào)到下一個單元格的作用
//如果用cwriter.write(String str)方法來寫數(shù)據(jù),則要用cwriter.endRecord()方法來實現(xiàn)換行
//cwriter.endRecord();//換行
cwriter.flush();//刷新數(shù)據(jù)
}
creader.close();
cwriter.close();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
}
}
思想:先獲取csv文件的路徑,通過BufferedReader類去讀該路徑中的文件,使用readLine方法進行逐行讀取。
注意:使用readLine方法后會自動轉(zhuǎn)到下一行。因此在判斷是否為空后得先將讀取到的內(nèi)容賦值給一變量,在循環(huán)中使用該變量即可。
public?static?void?main(String[]?args)
{
File?csv?=?new?File("C:\\Users\\chenxumin\\Desktop\\Result.csv");??//?CSV文件路徑
BufferedReader?br?=?null;
try
{
br?=?new?BufferedReader(new?FileReader(csv));
}?catch?(FileNotFoundException?e)
{
e.printStackTrace();
}
String?line?=?"";
String?everyLine?=?"";
try?{
ListString?allString?=?new?ArrayList();
while?((line?=?br.readLine())?!=?null)??//讀取到的內(nèi)容給line變量
{
everyLine?=?line;
System.out.println(everyLine);
allString.add(everyLine);
}
System.out.println("csv表格中所有行數(shù):"+allString.size());
}?catch?(IOException?e)
{
e.printStackTrace();
}
}
import?java.io.BufferedReader;??
import?java.io.FileReader;??
import?java.util.*;
public?class?Test{
public?static?void?main(String[]?args)?{
HashtableString,?String[]?dict?=?new?HashtableString,?String[]();
try?{??
BufferedReader?reader?=?new?BufferedReader(new?FileReader("test.csv"));
String?line?=?null;??
while((line=reader.readLine())!=null){??
String?item[]?=?line.split(",");
String?item2[]?=?new?String[19];
System.arraycopy(item,1,item2,0,19);
dict.put(item[0],item2);
}??
Enumeration?e2?=?dict.keys();
while?(e2.hasMoreElements())?{
String?key?=?(String)?e2.nextElement();
System.out.println(key);
String[]?dd?=?(String[])dict.get(key);
for?(int?i=0;idd.length;i++)?{
System.out.print(dd[i]+"\t");
}
System.out.println();
}
}
catch?(Exception?e)?{
e.printStackTrace();?
}??
}
}
這是我寫的個類 你參考下 其實那個引號是不用管的
public class CsvUtil1 {
private String filename = null;
private BufferedReader bufferedreader = null;
private List list = new ArrayList();
public CsvUtil1() {
}
public CsvUtil1(String filename) throws IOException {
this.filename = filename;
bufferedreader = new BufferedReader(new FileReader(filename));
String stemp;
while ((stemp = bufferedreader.readLine()) != null) {
list.add(stemp);
}
}
public List getList() throws IOException {
return list;
}
public int getRowNum() {
return list.size();
}
public int getColNum() {
if (!list.toString().equals("[]")) {
if (list.get(0).toString().contains(",")) {
return list.get(0).toString().split(",").length;
} else if (list.get(0).toString().trim().length() != 0) {
return 1;
} else {
return 0;
}
} else {
return 0;
}
}
public String getRow(int index) {
if (this.list.size() != 0)
return (String) list.get(index);
else
return null;
}
public String getCol(int index) {
if (this.getColNum() == 0) {
return null;
}
StringBuffer scol = new StringBuffer();
String temp = null;
int colnum = this.getColNum();
if (colnum 1) {
for (Iterator it = list.iterator(); it.hasNext();) {
temp = it.next().toString();
scol = scol.append(temp.split(",")[index] + ",");
}
} else {
for (Iterator it = list.iterator(); it.hasNext();) {
temp = it.next().toString();
scol = scol.append(temp + ",");
}
}
String str = new String(scol.toString());
str = str.substring(0, str.length() - 1);
return str;
}
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 IOException {
this.bufferedreader.close();
}
public void test() throws IOException {
CsvUtil1 cu = new CsvUtil1("D:/學習/00dw.csv");
List tt = cu.getList();
for (Iterator itt = tt.iterator(); itt.hasNext();) {
System.out.println(itt.next().toString()+"||");
}
// System.out.println(cu.getRowNum());
// System.out.println(cu.getColNum());
// System.out.println(cu.getRow(0));
// System.out.println(cu.getCol(0));
// System.out.println(cu.getString(0, 0));
cu.CsvClose();
}
public void createCsvTest1(HttpServletResponse Response) throws IOException {
CsvUtil1 cu = new CsvUtil1("D:/學習/00dw.csv");
List tt = cu.getList();
String data = "";
SimpleDateFormat dataFormat = new SimpleDateFormat("yyyyMMddHHmm");
Date today = new Date();
String dateToday = dataFormat.format(today);
File file=new File("D:/學習/001dw.csv");
if(!file.exists())
file.createNewFile();
// else
// file.delete() ;
String str[] ;
StringBuilder sb = new StringBuilder("");
BufferedWriter output=new BufferedWriter(new FileWriter(file,true));
for (Iterator itt = tt.iterator(); itt.hasNext();) {
String fileStr = itt.next().toString() ;
str = fileStr.split(",");
for(int i=0;i=str.length-1;i++){ //拆分成數(shù)組 用于插入數(shù)據(jù)庫中
System.out.print("str["+i+"]="+str[i]+" ");
}
System.out.println("");
sb.append(fileStr+"\r\n") ;
}
//System.out.println(sb.toString());
output.write(sb.toString());
output.flush() ;
output.close();
cu.CsvClose();
}
public static void main(String[] args) throws IOException {
CsvUtil1 test = new CsvUtil1();
//test.test();
HttpServletResponse response = null ;
test.createCsvTest1(response);
}
}