Anexar datos a un archivo usando Apache Commons I / O


La función FileUtils.writeStringToFile(fileName, text) de Apache Commons I/O sobrescribe el texto anterior en un archivo. Me gustaría añadir datos a mi archivo. ¿Hay alguna forma de que pueda usar E/S de Commons para lo mismo? Puedo hacerlo usando normal BufferedWriter desde Java pero tengo curiosidad con respecto a lo mismo usando Commons I/O.

Author: skaffman, 2010-06-03

7 answers

Se ha implementado en la versión 2.1 de Apache IO. Para añadir una cadena al archivo simplemente pase true como un parámetro adicional en funciones:

  • FileUtils.writeStringToFile
  • FileUtils.openOutputStream
  • FileUtils.escribir
  • FileUtils.writeByteArrayToFile
  • FileUtils.writeLines

Ex:

    FileUtils.writeStringToFile(file, "String to append", true);
 53
Author: JJ Roman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-11-28 10:44:11

Descargue la última versión Commons-io 2.1

FileUtils.writeStringToFile(File,Data,append)

Establecer append a true....

 5
Author: Makky,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-30 09:50:38

Cuidado. Esa implementación parece estar filtrando un controlador de archivo...

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() {}

}
 4
Author: Ryan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-03-12 00:31:14

Esta cosita debería hacer el truco:

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() {
    }

}

Editar: mi eclipse se rompió, por lo que no me mostró los errores anteriores. errores corregidos

 2
Author: Sean Patrick Floyd,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-06-04 09:30:31

En realidad, la versión 2.4 de apache-commons-io FileUtils ahora también tiene el modo anexar para las colecciones.

Aquí está el Javadoc

Y la dependencia maven:

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
    <type>jar</type>
</dependency>
 2
Author: gps,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-20 01:48:48
public static void writeStringToFile(File file,
                                     String data,
                                     boolean append)
                              throws IOException


   Writes the toString() value of each item in a collection to the specified File line by line. The default VM encoding and the default line ending will be used.

Parameters:
    file - the file to write to
    lines - the lines to write, null entries produce blank lines
    append - if true, then the lines will be added to the end of the file rather than overwriting 
Throws:
    IOException - in case of an I/O error
Since:
    Commons IO 2.1
 0
Author: White_Sox,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-11-28 11:03:05

En la versión 2.5 es necesario pasar un parámetro adicional, es decir, la codificación.

FileUtils.writeStringToFile(file, "line to append", "UTF-8", true);
 0
Author: Roushan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-23 02:40:47