Append data into a file using Apache Commons I/O

前端 未结 7 1608
野的像风
野的像风 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:39

    Careful. That implementation seems to be leaking a file handle...

    public final class AppendUtils {
    
        public static void appendToFile(final InputStream in, final File f) throws IOException {
            OutputStream stream = null;
            try {
                stream = outStream(f);
                IOUtils.copy(in, stream);
            } finally {
                IOUtils.closeQuietly(stream);
            }
        }
    
        public static void appendToFile(final String in, final File f) throws IOException {
            InputStream stream = null;
            try {
                stream = IOUtils.toInputStream(in);
                appendToFile(stream, f);
            } finally {
                IOUtils.closeQuietly(stream);
            }
        }
    
        private static OutputStream outStream(final File f) throws IOException {
            return new BufferedOutputStream(new FileOutputStream(f, true));
        }
    
        private AppendUtils() {}
    
    }
    

提交回复
热议问题