To export a CSV file by applying Java Generics and reflection

Source: Internet
Author: User

There are requirements in the project to export data to a CSV file, because different classes have different properties, in order to code simple, the application of Java generics and reflection, wrote a function to complete the export function.

 Public<T>voidSaveFile (list<t>list, String outFile) throws IOException {if(List = =NULL||List.isEmpty ()) {            return; }        if(Stringutils.isempty (outFile)) {Throw NewIllegalArgumentException ("outfile is null"); } Boolean IsFirst=true; BufferedWriter out=NULL; Try {             out=NewBufferedWriter (NewFileWriter (outFile));  for(T t:list) {StringBuilder sb1=NewStringBuilder (); StringBuilder SB2=NewStringBuilder (); Class Clazz=(Class) T.getclass (); Field[] FS=Clazz.getdeclaredfields ();  for(inti =0; i < fs.length; i++) {Field F=Fs[i]; F.setaccessible (true); Try {                        if(IsFirst) {sb1.append (F.getname ()); Sb1.append (","); } Object Val= f.Get(t); if(val = =NULL) {sb2.append (""); } Else{sb2.append (val.tostring ()); } sb2.append (","); } Catch(IllegalArgumentException |illegalaccessexception e)                    {E.printstacktrace (); }                }                if(isFirst) { out. Write (Sb1.tostring ()); IsFirst=false;  out. NewLine (); }                 out. Write (Sb2.tostring ());  out. NewLine (); }        } Catch(IOException E1) {ThrowE1; } finally {            Try {                if( out!=NULL) {                     out. Close (); }            } Catch(IOException E2) {ThrowE2; }        }    }

To export a CSV file by applying Java Generics and reflection

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.