java對csv格式的讀寫操作
阿新 • • 發佈:2018-12-29
CSV格式:
它可以用excel開啟,如果用記事本開啟,會發現它是一種使用逗號(",")作為不同列之間的分隔符.
讀取CSV格式:
import java.io.*; /** * 使用例子: * CSVReader reader = new CSVReader("D:\\114.csv"); * String str1 = reader.readLine();//得到第一行 * String str2 = reader.readLine();//得到第二行 */ public class CSVReader { BufferedReader reader; public String readLine() throws IOException { return reader.readLine(); } public CSVReader(String pathname) throws FileNotFoundException { this.reader = new BufferedReader(new FileReader(new File(pathname))); } }
寫入CSV格式:
import java.io.*; /** * 使用例子 * CSVWriter writer = new CSVWriter("D:\\114.csv"); * writer.write(new String[]{"a", "b", "c"});//第一行寫入 a b c * writer.write(new String[]{"d", "e", "f"});//第二行寫入 d e f */ public class CSVWriter { private BufferedWriter writer; public void write(String[] writeStrings) throws IOException { for (String str : writeStrings) { writer.append(str + ","); } writer.append("\r"); writer.flush(); } public CSVWriter(String writePath) throws FileNotFoundException, UnsupportedEncodingException { this.writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(writePath)), "GBK")); } }