Append data into a file using Apache Commons I/O

前端 未结 7 1646
野的像风
野的像风 2020-12-09 14:48

The FileUtils.writeStringToFile(fileName, text) function of Apache Commons I/O overwrites previous text in a file. I would like to append data to my file. Is th

7条回答
  •  死守一世寂寞
    2020-12-09 15:38

    this little thingy should do the trick:

    package com.yourpackage;
    
    // you're gonna want to optimize these imports
    import java.io.*;
    import org.apache.commons.io.*;
    
    public final class AppendUtils {
    
        public static void appendToFile(final InputStream in, final File f)
                throws IOException {
            IOUtils.copy(in, outStream(f));
        }
    
        public static void appendToFile(final String in, final File f)
                throws IOException {
            appendToFile(IOUtils.toInputStream(in), f);
        }
    
        private static OutputStream outStream(final File f) throws IOException {
            return new BufferedOutputStream(new FileOutputStream(f, true));
        }
    
        private AppendUtils() {
        }
    
    }
    

    edit: my eclipse was broken, so it didn't show me the errors earlier. fixed errors

提交回复
热议问题