JAVA Operations CSV file (Import Export) __java

Source: Internet
Author: User

CSV is the initials of a comma-delimited file (Comma separated Values), a plain text format for storing data, often used in spreadsheets or database software. In a CSV file, the Data "column" is separated by commas, allowing the program to re-create the correct column structure for the data by reading the file and starting a new column each time a comma is encountered.


1, CSV file opened with text to display as:

1, John, male
2, Dick, male
3, Xiao Hong, female

2, CSV file opened in Excel display as:



First, the use of javacsv2.0 operation CSV file:

Package Com.iflytek.demo;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.nio.charset.Charset;
Import java.util.ArrayList;

Import java.util.List;
Import Com.csvreader.CsvReader;

Import Com.csvreader.CsvWriter; /** * Use javacsv2.0 to do Import Export CSV file Tool class <br/> * * * * @author kpchen * */public class Csvutil {static char Separat

	or = ', ';
		public static void Main (string[] args) throws Exception {//test export String FilePath = "D:/test.csv";
		list<string[]> dataList = new arraylist<string[]> ();
		for (int i = 0; i < i++) {Datalist.add (new string[] {"0" + I, "xiaoming" + I, "Java" + i});


		} exportcsv (DataList, FilePath);
		Test import list<string[]> datas = ImportCSV (FilePath);
		For (string[] strings:datas) {System.out.println (strings[0]); /** * Java Import CSV file * * @param filePath * Import path * @return * @throws Exception/Public STA Tic list<string[]> importcsv (String filePath) throws Exception {Csvreader reader = null;
		list<string[]> dataList = new arraylist<string[]> ();

			try {reader = new Csvreader (FilePath, separator, charset.forname ("GBK"));
			Read the table header reader.readheaders ();
				Read each record until you have read the while (Reader.readrecord ()) {Datalist.add (Reader.getrawrecord ()). Split (","));
				Here are a few common methods//read a record System.out.println (Reader.getrawrecord ());
				Reads the value of this record by column name System.out.println (reader.get (0));
				System.out.println (Reader.get (1));
				System.out.println (Reader.get (2));
			System.out.println (Reader.get (3));
			} catch (Exception e) {System.out.println ("Error reading CSV ..." + e);
		Throw e;
			finally {if (null!= reader) {reader.close ();
	} return dataList;
	 /** * Java Export CVS file * * @param dataList * Data set * @param filePath * Export path * @return  * @throws Exception */public static Boolean exportcsv (List<string[]> dataList, String filePath) throws Exception {
		Boolean issuccess = false;
		Csvwriter writer = null;
		FileOutputStream out = null;
			try {out = new FileOutputStream (FilePath, true);
			writer = new Csvwriter (out, separator, charset.forname ("GBK"));
			For (string[] strs:datalist) {Writer.writerecord (STRs);
		} issuccess = true;
			The catch (Exception e) {System.out.println ("Generate CSV error ..." + e);
		Throw e;
			finally {if (null!= writer) {writer.close ();
				} if (null!= out) {try {out.close ();
					catch (IOException e) {System.out.println ("Exportcsv close Exception:" + e);
				Throw e;
	}} return issuccess;
 }

}

Second, the use of flow operation CSV file

Package Com.iflytek.demo;
Import Java.io.BufferedReader;
Import Java.io.BufferedWriter;
Import Java.io.File;
Import Java.io.FileOutputStream;
Import Java.io.FileReader;
Import java.io.IOException;
Import Java.io.OutputStreamWriter;
Import java.util.ArrayList;

Import java.util.List; public class CSVUtil2 {public static void main (string[] args) {//Test export//list<string> dataList = new Array
		List<string> ();
		Datalist.add ("1, John, Male");
		Datalist.add ("2, Dick, male");
		Datalist.add ("3, Little Red, female");
		Boolean issuccess = Exportcsv (New File ("D:/test.csv"), dataList);

		System.out.println (issuccess);
		Test import list<string> dataList = ImportCSV (New File ("D:/test.csv"));
			if (dataList!= null &&!datalist.isempty ()) {for (String data:datalist) {System.out.println (data);            }}/** * Export * * @param file * CSV files (path + filename), the CSV file does not exist will automatically create * @param dataList * Data * @return */public static Boolean Exportcsv(File file, list<string> dataList)

		{Boolean issucess = false;
		FileOutputStream out = null;
		OutputStreamWriter OSW = null;
		BufferedWriter bw = NULL;
			try {out = new FileOutputStream (file);
			OSW = new OutputStreamWriter (out);
			BW = new BufferedWriter (OSW); if (dataList!= null &&!datalist.isempty ()) {for (String data:datalist) {bw.append (data). Append ("\r\
				n ");
		} issucess = true;
		catch (Exception e) {issucess = false;
					finally {if (BW!= null) {try {bw.close ();
				BW = NULL;
				catch (IOException e) {e.printstacktrace ();
					} if (OSW!= null) {try {osw.close ();
				OSW = null;
				catch (IOException e) {e.printstacktrace ();
					} if (out!= null) {try {out.close ();
				out = null;
				catch (IOException e) {e.printstacktrace ();
	}} return issucess; /** * Import * * @param file * CSV files (path + file) * @return */public static list<string> importcsv (file file) {list<string> dataList = new Arraylist<string&gt

		;();
		BufferedReader br = null;
			try {br = new BufferedReader (new FileReader (file));
			String line = "";
			while (line = Br.readline ())!= null) {Datalist.add (line);
					} catch (Exception e) {} finally {if (br!= null) {try {br.close ();
				br = NULL;
				catch (IOException e) {e.printstacktrace ();
	}} return dataList;
 }

}

Source: Http://pan.baidu.com/s/1nt1r7ap


Reference: http://write.blog.csdn.net/postedit/49755535

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.