java reading and generation of CSV file

CSV file is a comma separated value file format, which is usually opened with WORDPAD or notepad and excel. CSV (comma separated value) is a kind of plain text file used to store data. It is usually a file format used to store spreadsheets or data. It is very simple to read and generate CSV files. As long as (,) is used to cut during reading, corresponding column elements can be obtained. When generating, add (,) between different column elements

The demo is as follows:

   //Read CSV file
    public void readCsvFile(String fileName) throws IOException {
        BufferedReader  bufferedReader=null;
        try{
           bufferedReader=new BufferedReader(new FileReader(fileName));
           String line=null;
           while(null!=(line=bufferedReader.readLine())){
               String[] lines = line.split(",");
               logger.info("This is the content of the document"+ Arrays.toString(lines));
           }
        }catch (IOException e){
           throw  new IOException(e);
        }finally {
           if(bufferedReader!=null){
               try {
                   bufferedReader.close();
               } catch (IOException e) {
                   logger.error("Abnormal closing of input current",e);
               }
           }
        }
    }

  

    //Production CSV file
    public static void writerCsvFile(String fileName, List<String[]> list) throws IOException {
        BufferedWriter   bufferedWriter=null;
        try{
            bufferedWriter= new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName),"GBK"));
            for (String[] s:list) {
                for (int i=0;i<s.length;i++){
                    bufferedWriter.write(s[i]);
                    bufferedWriter.write(",");
                }
                bufferedWriter.newLine();//Remember to wrap new lines.
            }
        }catch (IOException e){
            throw  new IOException(e);
        }finally {
            if(bufferedWriter!=null){
                try {
                    bufferedWriter.close();
                } catch (IOException e2) {
                    logger.error("Abnormal closing of output current",e2);
                }
            }
        }
    }

It is worth noting that when generating CSV files, CSV will automatically convert the long string composed of numbers, i.e. scientific counting method. Whether to process or not depends on the demand

If you want to directly double-click to open without conversion, you need to tell CSV when writing, I am not the number that I write, and when I can write again, I need to splice information such as \ t,; etc

If the generated CSV file is also read from the input stream, it will be recognized automatically without processing, because this is the format of the CSV file

Tags: Java Excel

Posted on Fri, 29 Nov 2019 10:02:38 -0800 by Mike521