天天看點

讀取csv檔案對其檔案内容進行篩選後寫入新csv

程式講解:

  • 需要被讀取的csv檔案中要

    手動添加

    一行資料,個數和内容個數一樣。如圖tempReaderCsv.csv檔案第一行(1,2,3,4,5)。該操作原因請看代碼注解。
  • 代碼邏輯寫死了列名

    sum

    soldNum

    ,因為代碼中的寫檔案是需要總量和售貨量作為參照的。
  • 功能:篩選出售貨量不達标的資料輸出到一個新csv檔案裡,再追加兩列

    剩餘量

    售貨率

  • 很簡單,

    目的

    是提供一個模闆供大家進行檔案讀寫的代碼了解或者進行檔案讀寫其他功能的開發。
  • 歡迎評論私信
package tempExample;

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;
import java.text.DecimalFormat;

//author @ZoHing
public class readerWriterCsv {

	/**
	 * 讀檔案
	 */
	public void fileReader() {

		//先擷取檔案的路徑,通過BufferedReader類去讀該路徑中的檔案
		File filePath = new File("E:\\temp\\tempReaderCsv.csv");
		
		try{
			//通過BufferedReader類建立字元輸入流對象
			BufferedReader readerStream = new BufferedReader(new FileReader(filePath));
		    String lineData = "";
			int index = 1;
			int targetSum = 0;
			int targetsoldNum = 0;
			int Substandard = 0;
	    	String SubstandardFileWriterDataString = null;
	    	//需要給檔案首行加上對應列數,作用: 代碼裡需要取檔案裡列數,但是字元輸入流指派給其他變量後
	    	//指派給變量的那段檔案資料在字元輸入流中就不存在了。
	    	String TempLineData = readerStream.readLine();
	    	String[] tempDataStrings = TempLineData.split(",");
	    	String[] SubstandardFileWriterData = new String[tempDataStrings.length];
	    	System.out.println("this data's length:" + tempDataStrings.length);
		    //将文檔的下一行資料指派給lineData,并判斷是否為空,若不為空則輸出
		    //readLine()解釋:
		    //讀一行文字。換行符(“\n”)、回車(“\r”)、換行符後面緊跟換行符的回車符或到達檔案末尾的任意一個都會将一行視為終止
		    //傳回一個包含行内容的字元串,不包括任何行終止字元,如果在未讀取任何字元的情況下到達流的結尾,則傳回null
		    while ((lineData = readerStream.readLine()) != null){
		    	String[] tempData = lineData.split(",");
	    		if(index == 1 && index!=0) {
	    			for(int i=0;i<tempData.length;i++) {
	    				//( equals )比較兩個對象的内容是否相等,此處不能用( == )
	    				if(tempData[i].equals("sum")) {
	    					targetSum = i;
	    				} else if(tempData[i].equals("soldNum")){
	    					targetsoldNum = i;
	    				}
	    			}
			    } else {
			    	//除法設定保留位數
			    	DecimalFormat df=new DecimalFormat("0.00");
			    	//篩選出售貨量不及格的商品資料
			    	if(Float.parseFloat(df.format((float)Integer.parseInt(tempData[targetsoldNum])/Integer.parseInt(tempData[targetSum]))) < 0.6f) {
			    		System.out.println("Substandard data:"+lineData);
			    		//将不及格資料放入新String[]中
			    		SubstandardFileWriterDataString = lineData;
		    			SubstandardFileWriterData[Substandard] = SubstandardFileWriterDataString;
		    			Substandard++;
			    	}
			    }
	    		index++;
		    }
		    //SubstandardFileWriterData[]:csv一整行作為一個字元串占一個數組長度
		    //Substandard:不達标的整行資料個數
    		SubstandardFileWriter(SubstandardFileWriterData,Substandard,targetSum,targetsoldNum);
		    readerStream.close();
		}catch (FileNotFoundException e){
		    System.out.println("沒有找到指定檔案");
		}catch (IOException e){
		    System.out.println("檔案讀寫出錯");
		}
	}
	
	/**
	 * 輸出不合格資料到csv檔案
	 * 
	 * @param str 字元串數組
	 * @param index 需要輸出的個數
	 * @param sum 總量位于的列數
	 * @param soldnum 售貨量位于的列數
	 */
	public void SubstandardFileWriter(String[] str,int index,int sum,int soldnum) {
		
        File filePath = new File("E:\\temp\\tempSubstandardFile.csv");
 
        try{
            //建立一個字元輸出流對象
            BufferedWriter writeStream = new BufferedWriter(new FileWriter(filePath));
            System.out.println("Substandard data hava:"+index);
        	writeStream.write("The Substandard Data:");
            //換行
    		writeStream.newLine();
        	writeStream.write("name,id,price,sum,soldNum"+",reminder,soldPercent");
    		writeStream.newLine();
            for(int i=0;i<index;i++) {
            	DecimalFormat df=new DecimalFormat("0.00");
    	    	String[] tempDataStrings = str[i].split(",");
    	    	int reminder = Integer.parseInt(tempDataStrings[sum])-Integer.parseInt(tempDataStrings[soldnum]);
    	    	float soldPercent = Float.parseFloat(df.format((float)Integer.parseInt(tempDataStrings[soldnum])/Integer.parseInt(tempDataStrings[sum])));
	        	writeStream.write(str[i] + "," + reminder + ","  + soldPercent);
	    		writeStream.newLine();
            }
            //使用緩沖區的重新整理方法将資料刷到目的地中
            writeStream.flush();
            //關閉緩沖區,緩沖區沒有調用系統底層資源,真正調用底層資源的是FileWriter對象,緩沖區僅僅是一個提高效率的作用
            //是以,此處的close()方法關閉的是被緩存的流對象
            writeStream.close();
        }catch (FileNotFoundException e){
            System.out.println("沒有找到指定檔案");
        }catch (IOException e){
            System.out.println("檔案讀寫出錯");
        }

	}
	
	public static void main(String[] args) {
		readerWriterCsv readercsv = new readerWriterCsv();
		readercsv.fileReader();
	}
}

           

tempReaderCsv.csv檔案:

1,2,3,4,5
name,id,price,sum,soldNum
chicken,1001,54,95,67
duck,2002,69,105,89
fish,3003,35,108,102
sheep,4004,485,12,3
pig,5005,302,9,4
           
讀取csv檔案對其檔案内容進行篩選後寫入新csv

運作結果:

tempSubstandardFile.csv檔案:

讀取csv檔案對其檔案内容進行篩選後寫入新csv