Pregunta

Necesito agregar texto repetidamente a un archivo existente en Java. ¿Cómo hago eso?

¿Fue útil?

Solución

¿Estás haciendo esto para fines de registro? Si es así, hay varias bibliotecas para esto . Dos de los más populares son Log4j y Logback .

Java 7+

Si solo necesita hacer esto una vez, el La clase de archivos facilita esto:

try {
    Files.write(Paths.get("myfile.txt"), "the text".getBytes(), StandardOpenOption.APPEND);
}catch (IOException e) {
    //exception handling left as an exercise for the reader
}

Cuidado : el enfoque anterior arrojará un NoSuchFileException si el archivo aún no existe. Tampoco agrega una nueva línea automáticamente (que a menudo desea cuando se agrega a un archivo de texto). La respuesta de Steve Chambers cubre cómo puede hacer esto con la clase Files .

Sin embargo, si va a escribir en el mismo archivo muchas veces, lo anterior tiene que abrir y cerrar el archivo en el disco muchas veces, lo cual es una operación lenta. En este caso, un escritor protegido es mejor:

try(FileWriter fw = new FileWriter("myfile.txt", true);
    BufferedWriter bw = new BufferedWriter(fw);
    PrintWriter out = new PrintWriter(bw))
{
    out.println("the text");
    //more code
    out.println("more text");
    //more code
} catch (IOException e) {
    //exception handling left as an exercise for the reader
}

Notas :

  • El segundo parámetro para el constructor FileWriter le dirá que se agregue al archivo, en lugar de escribir un nuevo archivo. (Si el archivo no existe, se creará).
  • Usar un BufferedWriter se recomienda para un escritor costoso (como FileWriter ).
  • Usar un PrintWriter le da acceso a la sintaxis println a la que probablemente esté acostumbrado desde System.out .
  • Pero los envoltorios BufferedWriter y PrintWriter no son estrictamente necesarios.

Java anterior

try {
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true)));
    out.println("the text");
    out.close();
} catch (IOException e) {
    //exception handling left as an exercise for the reader
}

Manejo de excepciones

Si necesita un manejo robusto de excepciones para Java anterior, se vuelve muy detallado:

FileWriter fw = null;
BufferedWriter bw = null;
PrintWriter out = null;
try {
    fw = new FileWriter("myfile.txt", true);
    bw = new BufferedWriter(fw);
    out = new PrintWriter(bw);
    out.println("the text");
    out.close();
} catch (IOException e) {
    //exception handling left as an exercise for the reader
}
finally {
    try {
        if(out != null)
            out.close();
    } catch (IOException e) {
        //exception handling left as an exercise for the reader
    }
    try {
        if(bw != null)
            bw.close();
    } catch (IOException e) {
        //exception handling left as an exercise for the reader
    }
    try {
        if(fw != null)
            fw.close();
    } catch (IOException e) {
        //exception handling left as an exercise for the reader
    }
}

Otros consejos

Puede usar fileWriter con un indicador establecido en true , para agregar.

try
{
    String filename= "MyFile.txt";
    FileWriter fw = new FileWriter(filename,true); //the true will append the new data
    fw.write("add a line\n");//appends the string to the file
    fw.close();
}
catch(IOException ioe)
{
    System.err.println("IOException: " + ioe.getMessage());
}

¿No deberían todas las respuestas aquí con bloques try / catch tener las piezas .close () contenidas en un bloque finalmente?

Ejemplo de respuesta marcada:

PrintWriter out = null;
try {
    out = new PrintWriter(new BufferedWriter(new FileWriter("writePath", true)));
    out.println("the text");
} catch (IOException e) {
    System.err.println(e);
} finally {
    if (out != null) {
        out.close();
    }
} 

Además, a partir de Java 7, puede usar un try- declaración de recursos . Finalmente, no se requiere un bloque para cerrar los recursos declarados porque se maneja automáticamente y también es menos detallado:

try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("writePath", true)))) {
    out.println("the text");
} catch (IOException e) {
    System.err.println(e);
}

Editar : a partir de Apache Commons 2.1, la forma correcta de hacerlo es:

FileUtils.writeStringToFile(file, "String to append", true);

Adapté la solución de @ Kip para incluir el cierre correcto del archivo finalmente:

public static void appendToFile(String targetFile, String s) throws IOException {
    appendToFile(new File(targetFile), s);
}

public static void appendToFile(File targetFile, String s) throws IOException {
    PrintWriter out = null;
    try {
        out = new PrintWriter(new BufferedWriter(new FileWriter(targetFile, true)));
        out.println(s);
    } finally {
        if (out != null) {
            out.close();
        }
    }
}

Para ampliar ligeramente la respuesta de Kip , aquí hay un método simple de Java 7+ para agregar una nueva línea a un archivo, creándolo si aún no existe :

try {
    final Path path = Paths.get("path/to/filename.txt");
    Files.write(path, Arrays.asList("New line to append"), StandardCharsets.UTF_8,
        Files.exists(path) ? StandardOpenOption.APPEND : StandardOpenOption.CREATE);
} catch (final IOException ioe) {
    // Add your own exception handling...
}

Nota: Lo anterior utiliza Files.write sobrecarga que escribe líneas de texto en un archivo (es decir, similar a un comando println ). Para escribir texto hasta el final (es decir, similar a un comando print ), una alternativa Files.write , pasando una matriz de bytes (por ejemplo, " mytext " .getBytes (StandardCharsets.UTF_8) ).

Asegúrese de que la transmisión se cierra correctamente en todos los escenarios.

Es un poco alarmante cuántas de estas respuestas dejan el identificador de archivo abierto en caso de error. La respuesta https://stackoverflow.com/a/15053443/2498188 está en el dinero, pero solo porque BufferedWriter () no puede lanzar. Si pudiera, una excepción dejaría abierto el objeto FileWriter .

Una forma más general de hacerlo que no importa si BufferedWriter () puede lanzar:

  PrintWriter out = null;
  BufferedWriter bw = null;
  FileWriter fw = null;
  try{
     fw = new FileWriter("outfilename", true);
     bw = new BufferedWriter(fw);
     out = new PrintWriter(bw);
     out.println("the text");
  }
  catch( IOException e ){
     // File writing/opening failed at some stage.
  }
  finally{
     try{
        if( out != null ){
           out.close(); // Will close bw and fw too
        }
        else if( bw != null ){
           bw.close(); // Will close fw too
        }
        else if( fw != null ){
           fw.close();
        }
        else{
           // Oh boy did it fail hard! :3
        }
     }
     catch( IOException e ){
        // Closing the file writers failed for some obscure reason
     }
  }

Editar:

A partir de Java 7, la forma recomendada es usar " probar con recursos " y deje que la JVM se encargue de eso:

  try(    FileWriter fw = new FileWriter("outfilename", true);
          BufferedWriter bw = new BufferedWriter(fw);
          PrintWriter out = new PrintWriter(bw)){
     out.println("the text");
  }  
  catch( IOException e ){
      // File writing/opening failed at some stage.
  }

En Java-7 también se puede hacer de este tipo:

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

// ---------------------

Path filePath = Paths.get("someFile.txt");
if (!Files.exists(filePath)) {
    Files.createFile(filePath);
}
Files.write(filePath, "Text to be added".getBytes(), StandardOpenOption.APPEND);

java 7+

En mi humilde opinión, ya que soy fanático de Java simple, sugeriría algo que es una combinación de las respuestas antes mencionadas. Tal vez llego tarde a la fiesta. Aquí está el código:

 String sampleText = "test" +  System.getProperty("line.separator");
 Files.write(Paths.get(filePath), sampleText.getBytes(StandardCharsets.UTF_8), 
 StandardOpenOption.CREATE, StandardOpenOption.APPEND);

Si el archivo no existe, lo crea y si ya existe agrega el sampleText al archivo existente. Al usar esto, le ahorra agregar libs innecesarias a su classpath.

Esto se puede hacer en una línea de código. Espero que esto ayude :)

Files.write(Paths.get(fileName), msg.getBytes(), StandardOpenOption.APPEND);

Uso de java.nio. Archivos junto con java.nio.file. StandardOpenOption

    PrintWriter out = null;
    BufferedWriter bufWriter;

    try{
        bufWriter =
            Files.newBufferedWriter(
                Paths.get("log.txt"),
                Charset.forName("UTF8"),
                StandardOpenOption.WRITE, 
                StandardOpenOption.APPEND,
                StandardOpenOption.CREATE);
        out = new PrintWriter(bufWriter, true);
    }catch(IOException e){
        //Oh, no! Failed to create PrintWriter
    }

    //After successful creation of PrintWriter
    out.println("Text to be appended");

    //After done writing, remember to close!
    out.close();

Esto crea un BufferedWriter usando Archivos, que acepta los parámetros StandardOpenOption , y un PrintWriter de descarga automática a partir del BufferedWriter . El método PrintWriter println () se puede llamar para escribir en el archivo.

Los parámetros StandardOpenOption utilizados en este código: abre el archivo para escritura, solo se agrega al archivo y lo crea si no existe.

Paths.get (" ruta aquí ") se puede reemplazar con nuevo archivo (" ruta aquí "). toPath () . Y Charset.forName (" charset name ") se puede modificar para acomodar el Charset deseado.

Solo agrego pequeños detalles:

    new FileWriter("outfilename", true)

2.nd parámetro (verdadero) es una característica (o interfaz) llamada appendable ( http://docs.oracle.com/javase/7/docs/api/java/lang/Appendable.html ). Es responsable de poder agregar algún contenido al final de un archivo / secuencia en particular. Esta interfaz se implementa desde Java 1.5. Cada objeto (es decir, BufferedWriter, CharArrayWriter, CharBuffer, FileWriter, FilterWriter, LogStream, OutputStreamWriter, PipedWriter, PrintStream, PrintWriter, StringBuffer, StringBuilder, StringWriter, Writer ) con esta interfaz puede usarse para agregar contenido. p>

En otras palabras, puede agregar algún contenido a su archivo comprimido o algún proceso http

Muestra, usando guayaba:

File to = new File("C:/test/test.csv");

for (int i = 0; i < 42; i++) {
    CharSequence from = "some string" + i + "\n";
    Files.append(from, to, Charsets.UTF_8);
}

Prueba con bufferFileWriter.append, funciona conmigo.

FileWriter fileWriter;
try {
    fileWriter = new FileWriter(file,true);
    BufferedWriter bufferFileWriter = new BufferedWriter(fileWriter);
    bufferFileWriter.append(obj.toJSONString());
    bufferFileWriter.newLine();
    bufferFileWriter.close();
} catch (IOException ex) {
    Logger.getLogger(JsonTest.class.getName()).log(Level.SEVERE, null, ex);
}
    String str;
    String path = "C:/Users/...the path..../iin.txt"; // you can input also..i created this way :P

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    PrintWriter pw = new PrintWriter(new FileWriter(path, true));

    try 
    {
       while(true)
        {
            System.out.println("Enter the text : ");
            str = br.readLine();
            if(str.equalsIgnoreCase("exit"))
                break;
            else
                pw.println(str);
        }
    } 
    catch (Exception e) 
    {
        //oh noes!
    }
    finally
    {
        pw.close();         
    }

esto hará lo que pretendes ..

Mejor usar try-with-resources que todo ese negocio anterior a Java 7 finalmente

static void appendStringToFile(Path file, String s) throws IOException  {
    try (BufferedWriter out = Files.newBufferedWriter(file, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
        out.append(s);
        out.newLine();
    }
}

Si estamos utilizando Java 7 y superior y también sabemos el contenido que se agregará (adjuntará) al archivo, podemos utilizar método newBufferedWriter en el paquete NIO.

public static void main(String[] args) {
    Path FILE_PATH = Paths.get("C:/temp", "temp.txt");
    String text = "\n Welcome to Java 8";

    //Writing to the file temp.txt
    try (BufferedWriter writer = Files.newBufferedWriter(FILE_PATH, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
        writer.write(text);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Hay algunos puntos a tener en cuenta:

  1. Siempre es un buen hábito especificar la codificación de juego de caracteres y para eso tenemos constantes en la clase StandardCharsets .
  2. El código utiliza la declaración try-with-resource en la que los recursos se cierran automáticamente después del intento.

Aunque OP no ha preguntado, pero en caso de que queramos buscar líneas que tengan alguna palabra clave específica, p. confidencial podemos hacer uso de las API de transmisión en Java:

//Reading from the file the first line which contains word "confidential"
try {
    Stream<String> lines = Files.lines(FILE_PATH);
    Optional<String> containsJava = lines.filter(l->l.contains("confidential")).findFirst();
    if(containsJava.isPresent()){
        System.out.println(containsJava.get());
    }
} catch (IOException e) {
    e.printStackTrace();
}
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class Writer {


    public static void main(String args[]){
        doWrite("output.txt","Content to be appended to file");
    }

    public static void doWrite(String filePath,String contentToBeAppended){

       try(
            FileWriter fw = new FileWriter(filePath, true);
            BufferedWriter bw = new BufferedWriter(fw);
            PrintWriter out = new PrintWriter(bw)
          )
          {
            out.println(contentToBeAppended);
          }  
        catch( IOException e ){
        // File writing/opening failed at some stage.
        }

    }

}
FileOutputStream stream = new FileOutputStream(path, true);
try {

    stream.write(

        string.getBytes("UTF-8") // Choose your encoding.

    );

} finally {
    stream.close();
}

Luego captura una IOException en algún lugar aguas arriba.

Cree una función en cualquier parte de su proyecto y simplemente llame a esa función donde la necesite.

Chicos, deben recordar que ustedes están llamando hilos activos que no están llamando de forma asincrónica y ya que probablemente sería un buen 5 a 10 páginas para hacerlo bien. ¿Por qué no dedicar más tiempo a su proyecto y olvidarse de escribir cualquier cosa ya escrita? Correctamente

    //Adding a static modifier would make this accessible anywhere in your app

    public Logger getLogger()
    {
       return java.util.logging.Logger.getLogger("MyLogFileName");
    }
    //call the method anywhere and append what you want to log 
    //Logger class will take care of putting timestamps for you
    //plus the are ansychronously done so more of the 
    //processing power will go into your application

    //from inside a function body in the same class ...{...

    getLogger().log(Level.INFO,"the text you want to append");

    ...}...
    /*********log file resides in server root log files********/

tres líneas de código dos realmente ya que la tercera realmente agrega texto. : P

  

Biblioteca

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
  

Código

public void append()
{
    try
    {
        String path = "D:/sample.txt";

        File file = new File(path);

        FileWriter fileWriter = new FileWriter(file,true);

        BufferedWriter bufferFileWriter  = new BufferedWriter(fileWriter);

        fileWriter.append("Sample text in the file to append");

        bufferFileWriter.close();

        System.out.println("User Registration Completed");

    }catch(Exception ex)
    {
        System.out.println(ex);
    }
}

También puedes probar esto:

JFileChooser c= new JFileChooser();
c.showOpenDialog(c);
File write_file = c.getSelectedFile();
String Content = "Writing into file"; //what u would like to append to the file



try 
{
    RandomAccessFile raf = new RandomAccessFile(write_file, "rw");
    long length = raf.length();
    //System.out.println(length);
    raf.setLength(length + 1); //+ (integer value) for spacing
    raf.seek(raf.length());
    raf.writeBytes(Content);
    raf.close();
} 
catch (Exception e) {
    //any exception handling method of ur choice
}
FileOutputStream fos = new FileOutputStream("File_Name", true);
fos.write(data);

el verdadero permite agregar los datos en el archivo existente. Si vamos a escribir

FileOutputStream fos = new FileOutputStream("File_Name");

Sobreescribirá el archivo existente. Así que ve por el primer enfoque.

Podría sugerir el proyecto apache commons . Este proyecto ya proporciona un marco para hacer lo que necesita (es decir, filtrado flexible de colecciones).

El siguiente método le permite agregar texto a algún archivo:

private void appendToFile(String filePath, String text)
{
    PrintWriter fileWriter = null;

    try
    {
        fileWriter = new PrintWriter(new BufferedWriter(new FileWriter(
                filePath, true)));

        fileWriter.println(text);
    } catch (IOException ioException)
    {
        ioException.printStackTrace();
    } finally
    {
        if (fileWriter != null)
        {
            fileWriter.close();
        }
    }
}

Alternativamente usando FileUtils :

public static void appendToFile(String filePath, String text) throws IOException
{
    File file = new File(filePath);

    if(!file.exists())
    {
        file.createNewFile();
    }

    String fileContents = FileUtils.readFileToString(file);

    if(file.length() != 0)
    {
        fileContents = fileContents.concat(System.lineSeparator());
    }

    fileContents = fileContents.concat(text);

    FileUtils.writeStringToFile(file, fileContents);
}

No es eficiente pero funciona bien. Los saltos de línea se manejan correctamente y se crea un nuevo archivo si aún no existía uno.

Este código satisfará su necesidad:

   FileWriter fw=new FileWriter("C:\\file.json",true);
   fw.write("ssssss");
   fw.close();

En caso de que desee AGREGAR ALGUNOS TEXTOS EN LÍNEAS ESPECÍFICAS , primero puede leer el archivo completo, agregar el texto donde desee y luego sobrescribir todo, como en el siguiente código:

public static void addDatatoFile(String data1, String data2){


    String fullPath = "/home/user/dir/file.csv";

    File dir = new File(fullPath);
    List<String> l = new LinkedList<String>();

    try (BufferedReader br = new BufferedReader(new FileReader(dir))) {
        String line;
        int count = 0;

        while ((line = br.readLine()) != null) {
            if(count == 1){
                //add data at the end of second line                    
                line += data1;
            }else if(count == 2){
                //add other data at the end of third line
                line += data2;
            }
            l.add(line);
            count++;
        }
        br.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }       
    createFileFromList(l, dir);
}

public static void createFileFromList(List<String> list, File f){

    PrintWriter writer;
    try {
        writer = new PrintWriter(f, "UTF-8");
        for (String d : list) {
            writer.println(d.toString());
        }
        writer.close();             
    } catch (FileNotFoundException | UnsupportedEncodingException e) {
        e.printStackTrace();
    }
}

Mi respuesta:

JFileChooser chooser= new JFileChooser();
chooser.showOpenDialog(chooser);
File file = chooser.getSelectedFile();
String Content = "What you want to append to file";

try 
{
    RandomAccessFile random = new RandomAccessFile(file, "rw");
    long length = random.length();
    random.setLength(length + 1);
    random.seek(random.length());
    random.writeBytes(Content);
    random.close();
} 
catch (Exception exception) {
    //exception handling
}
/**********************************************************************
 * it will write content to a specified  file
 * 
 * @param keyString
 * @throws IOException
 *********************************************************************/
public static void writeToFile(String keyString,String textFilePAth) throws IOException {
    // For output to file
    File a = new File(textFilePAth);

    if (!a.exists()) {
        a.createNewFile();
    }
    FileWriter fw = new FileWriter(a.getAbsoluteFile(), true);
    BufferedWriter bw = new BufferedWriter(fw);
    bw.append(keyString);
    bw.newLine();
    bw.close();
}// end of writeToFile()

Puede usar el siguiente código para agregar el contenido del archivo:

 String fileName="/home/shriram/Desktop/Images/"+"test.txt";
  FileWriter fw=new FileWriter(fileName,true);    
  fw.write("here will be you content to insert or append in file");    
  fw.close(); 
  FileWriter fw1=new FileWriter(fileName,true);    
 fw1.write("another content will be here to be append in the same file");    
 fw1.close(); 

1.7 Enfoque:

void appendToFile(String filePath, String content) throws IOException{

    Path path = Paths.get(filePath);

    try (BufferedWriter writer = 
            Files.newBufferedWriter(path, 
                    StandardOpenOption.APPEND)) {
        writer.newLine();
        writer.append(content);
    }

    /*
    //Alternative:
    try (BufferedWriter bWriter = 
            Files.newBufferedWriter(path, 
                    StandardOpenOption.WRITE, StandardOpenOption.APPEND);
            PrintWriter pWriter = new PrintWriter(bWriter)
            ) {
        pWriter.println();//to have println() style instead of newLine();   
        pWriter.append(content);//Also, bWriter.append(content);
    }*/
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top