Novice on the road, meet CSV read-write requirements, CSV file has blank lines.
Referring to some blogs, I wrote JAVA read-write CSV file tool class by myself.
CsvReader:
/** * @Title: CsvReader.java * @Package:xxd.tools * @Description:TODO * @author XingXuDong * @date:2018 September 26, 2014 19:47 PM */ package xxd.tools.csvTools; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.InputStreamReader; import java.util.ArrayList; public class CsvReader { // File path private String filePath; private File file; private DataInputStream in; private BufferedReader br; public CsvReader(String filepath) { this.filePath = filepath; } /** * Read title * * @return A row of data stored as an array of strings */ public String[] ReadTitle() { String[] titleItems; try { file = new File(filePath); in = new DataInputStream(new FileInputStream(file)); // CSV defaults to GBK encoding format br = new BufferedReader(new InputStreamReader(in, "GBK")); // The result of solitude is String String titleLine = br.readLine(); // Use string array to store different column data of this row titleItems = titleLine.split(","); // It's a good habit to turn it off br.close(); return titleItems; } catch (Exception ex) { ex.printStackTrace(); return null; } } /** * Read data by line number * * @param index * Line number * @return A row of data stored as an array of strings */ public String[] ReadByLineIndex(int index) { String[] resultItems = null; String resultLine = null; try { file = new File(filePath); in = new DataInputStream(new FileInputStream(file)); br = new BufferedReader(new InputStreamReader(in, "GBK")); // Traverse the file until you find that line for (int i = 0; i < index; i++) { resultLine = br.readLine(); } if (resultLine != null) { resultItems = resultLine.split(","); } br.close(); return resultItems; } catch (Exception ex) { ex.printStackTrace(); return null; } } /** * Read data by column number, including title * * @param index * Column number * @return Data stored in a string linked list, one string for one row of data in this column */ public ArrayList<String> ReadByColumnIndex(int index) { ArrayList<String> resultItems = new ArrayList<String>(); String[] lineItem; String line; try { file = new File(filePath); in = new DataInputStream(new FileInputStream(file)); br = new BufferedReader(new InputStreamReader(in, "GBK")); // Traverse each row and extract the data of the corresponding column of each row while ((line = br.readLine()) != null) { lineItem = line.split(","); if (lineItem.length != 0) { resultItems.add(lineItem[index - 1]); } else { resultItems.add(null); } } br.close(); return resultItems; } catch (Exception ex) { ex.printStackTrace(); return null; } } /** * Read data by column number, excluding title * * @param index * @return Data stored in a string linked list, one string for one row of data in this column */ public ArrayList<String> ReadDataByColumnIndex(int index) { ArrayList<String> result = this.ReadByColumnIndex(index); if (result != null) { result.remove(0); return result; } else { return null; } } /** * Read all data, including headers * * @return The data stored in the linked list of string array, a string array as a row of data */ public ArrayList<String[]> ReadAll() { ArrayList<String[]> result = new ArrayList<String[]>(); String[] lineItem; String line; try { file = new File(filePath); in = new DataInputStream(new FileInputStream(file)); br = new BufferedReader(new InputStreamReader(in, "GBK")); // Ergodic read while ((line = br.readLine()) != null) { lineItem = line.split(","); result.add(lineItem); } br.close(); return result; } catch (Exception ex) { ex.printStackTrace(); return null; } } }
CsvWriter:
/** * @Title: CsvReader.java * @Package:xxd.tools * @Description:TODO * @author XingXuDong * @date:2018 September 27, 2009 09:41 am */ package xxd.tools.csvTools; import java.io.BufferedWriter; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.util.ArrayList; public class CsvWriter { // Save path private String savePath; private File file; private DataOutputStream out; private BufferedWriter bw; public CsvWriter() { } public CsvWriter(String path) { this.savePath = path; } /** * Create a new CSV file and write the data to * * @param data * For data stored in string array list, the first array cannot be empty, and there cannot be empty value in non empty array * @return Success true; failure false */ public boolean SaveNewCsv(ArrayList<String[]> data) { try { file = new File(savePath); if (file.exists()) { file.delete(); } out = new DataOutputStream(new FileOutputStream(file)); // CSV defaults to GBK encoding format bw = new BufferedWriter(new OutputStreamWriter(out, "GBK")); if (data != null && data.size() != 0) { // Get the number of columns based on the first row int colCount = 0; colCount = data.get(0).length; // Traversing linked list for (int i = 0; i < data.size(); i++) { String[] lineItems; String line = ""; lineItems = data.get(i); // Determine whether this line has a value if (lineItems.length != 0) { // If there is a value, the string array will be traversed for (int j = 0; j < lineItems.length; j++) { line = line + lineItems[j] + ","; } // Write after formatting line = line.substring(0, line.lastIndexOf(",")); line = line + "\r"; bw.append(line); } else { // If there is no value, it will be written in the blank line format for (int count = 0; count < colCount; count++) { line = line + " ,"; } line = line + "\r"; bw.append(line); } } // It's a good habit to turn it off bw.close(); return true; } else { bw.close(); return false; } } catch (Exception ex) { ex.printStackTrace(); return false; } } public boolean AppendData(String[] data) { try { file = new File(savePath); // File output stream set to append out = new DataOutputStream(new FileOutputStream(file, true)); bw = new BufferedWriter(new OutputStreamWriter(out, "GBK")); String line = ""; for (int i = 0; i < data.length; i++) { line = line + data[i] + ","; } line = line.substring(0, line.lastIndexOf(",")); line = line + "\r"; bw.append(line); bw.close(); return true; } catch (Exception ex) { return false; } } }
Simple test data compiled by ourselves:
colour | number | Fruits |
Violet | 1 | Grape |
Red | 2 | Apple |
orange | 3 | orange |
yellow | 4 | Banana |
blue | 5 | Blueberry |
Test code:
package test.main; import java.util.ArrayList; import xxd.tools.csvTools.CsvReader; import xxd.tools.csvTools.CsvWriter; public class test { public static void main(String[] args) { CsvReader csvReader = new CsvReader( "test.csv");//Path changes by itself // Read title String[] re1 = csvReader.ReadTitle(); String result1 = ""; for (int i = 0; i < re1.length; i++) { result1 = result1 + re1[i] + ","; } result1 = result1.substring(0, result1.lastIndexOf(",")); System.out.println(result1); System.out.println("***************"); // Read a row of data String[] re2 = csvReader.ReadByLineIndex(3); String result2 = ""; for (int i = 0; i < re2.length; i++) { result2 = result2 + re2[i] + ","; } result2 = result2.substring(0, result2.lastIndexOf(",")); System.out.println(result2); System.out.println("***************"); //Read a blank line String[] re3 = csvReader.ReadByLineIndex(6); String result3 = ""; if (re3.length != 0) { for (int i = 0; i < re3.length; i++) { result3 = result3 + re3[i] + ","; } result3 = result3.substring(0, result3.lastIndexOf(",")); } else { result3 = null; } System.out.println(result3); System.out.println("***************"); //Index of determining exceeding travel String[] re4 = csvReader.ReadByLineIndex(9); String result4 = ""; if (re4 != null) { if (re4.length != 0) { for (int i = 0; i < re4.length; i++) { result4 = result4 + re4[i] + ","; } result4 = result4.substring(0, result4.lastIndexOf(",")); } else { result4 = null; } } else { result4 = "Out of index range!"; } System.out.println(result4); System.out.println("***************"); // Read a column of data with title ArrayList<String> re5 = csvReader.ReadByColumnIndex(3); if (re5 != null) { if (re5.size() != 0) { for (int i = 0; i < re5.size(); i++) { System.out.println(re5.get(i)); } } } else { System.out.println("Out of index range!"); } System.out.println("***************"); // Read a column of data without a title ArrayList<String> re6 = csvReader.ReadDataByColumnIndex(1); if (re6 != null) { if (re6.size() != 0) { for (int i = 0; i < re6.size(); i++) { System.out.println(re6.get(i)); } } else { System.out.println("null"); } } else { System.out.println("Out of index range!"); } System.out.println("***************"); // Read all data in the table with title ArrayList<String[]> re7 = csvReader.ReadAll(); if (re7 != null) { if (re7.size() != 0) { for (int i = 0; i < re7.size(); i++) { String[] lineItems; String line = ""; lineItems = re7.get(i); if (lineItems.length!=0) { for (int j = 0; j < lineItems.length; j++) { line = line + lineItems[j] + ","; } line = line.substring(0, line.lastIndexOf(",")); System.out.println(line); } else { System.out.println("null"); } } } } else { System.out.println("Out of index range!"); } System.out.println("***************"); // Write the data read in result 7 back to the new CSV CsvWriter csvWriter = new CsvWriter("test1.csv");//Path changes by itself csvWriter.SaveNewCsv(re7); // Append a line to the new CSV file String[] appendData = new String[3]; appendData[0]="color"; appendData[1]="number"; appendData[2]="fruit"; csvWriter.AppendData(appendData); } }
Test output:
Color, number, fruit
***************
Red, 2, apple
***************
null
***************
Out of index range!
***************
Fruits
Grape
Apple
orange
Banana
null
Blueberry
***************
Violet
Red
orange
yellow
null
blue
***************
Color, number, fruit
Purple, 1, grape
Red, 2, apple
Orange, 3, orange
Yellow, 4, banana
null
Blue, 5, blueberry
***************
Output test file:
colour | number | Fruits |
Violet | 1 | Grape |
Red | 2 | Apple |
orange | 3 | orange |
yellow | 4 | Banana |
blue | 5 | Blueberry |
color | number | fruit |
Reference resources: https://blog.csdn.net/ganzhantoulebi0546/article/details/72954409
https://www.cnblogs.com/beihoushan/p/6428162.html