Comment ajouter du texte à un fichier existant en Java

j'ai besoin d'ajouter du texte à plusieurs reprises à un fichier existant en Java. Comment dois-je faire?

599
demandé sur Jonik 2009-10-26 17:43:50

30 réponses

faites-vous cela à des fins de journalisation? Si oui, il y a plusieurs bibliothèques pour ce . Deux des plus populaires sont Log4j et Logback .

Java 7+

si vous avez juste besoin de le faire une fois, la classe de fichiers rend cela facile:

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

Prudent : Le l'approche ci-dessus lancera un NoSuchFileException si le fichier n'existe pas déjà. Il n'ajoute pas automatiquement une nouvelle ligne (ce que vous voulez souvent en ajoutant à un fichier texte). la réponse de Steve Chambers explique comment vous pouvez faire cela avec la classe Files .

Cependant, si vous allez écrire dans le même fichier plusieurs fois, le ci-dessus a pour ouvrir et fermer le fichier sur le disque plusieurs fois, ce qui est une opération lente. Dans ce cas, un l'écrivain tamponné est meilleur:

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
}

Notes:

  • le second paramètre du constructeur FileWriter lui dira d'ajouter au fichier, plutôt que d'écrire un nouveau fichier. (Si le fichier n'existe pas, il sera créé.)
  • utiliser un BufferedWriter est recommandé pour un auteur cher (comme FileWriter ).
  • en utilisant un PrintWriter vous donne accès à la syntaxe println à laquelle vous êtes probablement habitué à partir de System.out .
  • mais les emballages BufferedWriter et PrintWriter ne sont pas strictement nécessaires.

Vieux Java

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
}

Traitement D'Exception

si vous avez besoin d'une gestion d'exception robuste pour L'Ancien Java, il devient très verbeux:

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
    }
}
685
répondu Kip 2017-06-03 20:20:48

vous pouvez utiliser fileWriter avec un drapeau placé à true , pour l'ajout.

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());
}
150
répondu northpole 2017-04-24 08:39:44

ne devrait pas toutes les réponses ici avec les blocs essayer/attraper ont le .fermer() les pièces contenues dans un bloc final?

exemple de réponse marquée:

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

aussi, à partir de Java 7, vous pouvez utiliser un try-with-resources statement . Aucun bloc final n'est requis pour fermer la(Les) ressource (s) déclarée (s) car il est manipulé automatiquement et est aussi moins verbeux:

try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("writePath", true)))) {
    out.println("the text");
}catch (IOException e) {
    System.err.println(e);
}
64
répondu etech 2013-06-08 06:10:26

Edit - à partir de Apache Commons 2.1, la bonne façon de le faire est:

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

j'ai adapté la solution de @Kip pour inclure la fermeture correcte du dossier sur finalement:

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

39
répondu ripper234 2011-12-07 10:19:47

assurez-vous que le flux soit correctement fermé dans tous les scénarios.

C'est un peu alarmant combien de ces réponses quitter le descripteur de fichier ouvert en cas d'erreur. La réponse https://stackoverflow.com/a/15053443/2498188 est sur l'argent mais seulement parce que BufferedWriter() ne peut pas jeter. S'il le pouvait, une exception laisserait l'objet FileWriter ouvert.

une façon plus générale de faire cela qui ne se soucie pas si BufferedWriter() peut jeter:

  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
     }
  }

Edit:

depuis Java 7, Il est recommandé d'utiliser "try with resources" et de laisser la JVM s'en charger:

  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.
  }
19
répondu Emily L. 2017-05-23 12:02:22

légèrement augmenter sur de Kip réponse , voici une méthode Java 7+ simple pour ajouter une nouvelle ligne à un fichier, la créer si elle n'existe pas déjà :

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...
}

Note: ce qui précède utilise la Files.write surcharge qui écrit lignes du texte d'un fichier (c.-à-d. semblable à une commande println ). Juste Ecrivez le texte à la fin (c.-à-d. semblable à une commande print ), une alternative Files.write surcharge peut être utilisé, en passant dans un tableau d'octets (par exemple "mytext".getBytes(StandardCharsets.UTF_8) ).

18
répondu Steve Chambers 2017-06-05 07:55:08

en Java-7 Il peut aussi être fait de cette sorte:

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);
13
répondu Tsolak Barseghyan 2015-04-14 16:33:17

échantillon, en utilisant la goyave:

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);
}
6
répondu dantuch 2013-06-04 19:17:24

cela peut être fait dans une ligne de code. Espérons que cela aide :)

Files.write(Paths.get(fileName), msg.getBytes(), StandardOpenOption.APPEND);
6
répondu FlintOff 2015-08-06 17:38:43

java 7+

à mon humble avis puisque je suis fan de Java pur, je suggérerais quelque chose que c'est une combinaison des réponses mentionnées ci-dessus. Je suis peut-être en retard pour la fête. Voici le code:

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

Si le fichier n'existe pas, il le crée et si existe déjà, il ajoute le texte type pour le fichier existant. En utilisant ceci, vous sauve d'ajouter des libs inutiles à votre classpath.

6
répondu Lefteris Bab 2018-02-09 06:59:04

j'ajoute juste un petit détail:

    new FileWriter("outfilename", true)

2.le paramètre nd (true) est une caractéristique (ou interface) appelée ( ). http://docs.oracle.com/javase/7/docs/api/java/lang/Appendable.html ). Il est responsable de pouvoir ajouter du contenu à la fin d'un fichier/flux particulier. Cette interface est implémentée depuis Java 1.5. Chaque objet (i.e. BufferedWriter, CharArrayWriter, CharBuffer, FileWriter, FilterWriter, LogStream, OutputStreamWriter, PipedWriter, PrintStream, PrintWriter, StringBuffer, StringBuilder, StringWriter, Writer ) avec cette interface peut être utilisé pour ajouter du contenu

en d'autres termes, vous pouvez ajouter du contenu à votre fichier gzippé, ou un processus http

5
répondu xhudik 2012-12-13 10:56:43

utilisant java.nio. Fichiers avec java.nio.fichier. Optionstandard

    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();

cela crée un BufferedWriter en utilisant des fichiers, qui accepte StandardOpenOption paramètres, et un auto-rinçage PrintWriter de la résultante BufferedWriter . PrintWriter 's println() méthode, peut alors être appelé à écrire dans le fichier.

les paramètres StandardOpenOption utilisés dans ce code: ouvre le fichier pour l'écriture, ne fait qu'ajouter à la file, et crée le fichier s'il n'existe pas.

Paths.get("path here") peut être remplacé par new File("path here").toPath() . Et Charset.forName("charset name") peut être modifié pour accommoder le désiré Charset .

4
répondu icasdri 2013-07-25 20:16:37

essayez avec bufferFileWriter.ajouter, il travaille avec moi.

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);
}
4
répondu Nadhir Titaouine 2016-07-06 20:55:10
    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();         
    }

cela fera ce que vous avez l'intention de faire..

3
répondu Benjamin Varghese 2013-01-07 14:56:48

si nous utilisons Java 7 et au-dessus et que nous connaissons également le contenu à ajouter (en annexe) au fichier, nous pouvons utiliser la méthode newBufferedWriter dans le paquet 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();
    }
}

il y a peu de points à noter:

  1. c'est toujours une bonne habitude de spécifier l'encodage du jeu de caractères et pour cela nous avons constante dans la classe StandardCharsets .
  2. le code utilise try-with-resource déclaration dans laquelle les ressources sont automatiquement fermées après l'essai.

même si OP N'a pas demandé, mais juste au cas où nous voulons rechercher des lignes ayant un mot-clé spécifique par exemple confidential nous pouvons utiliser les API de flux 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();
}
3
répondu i_am_zero 2015-06-22 08:43:40
FileOutputStream stream = new FileOutputStream(path, true);
try {

    stream.write(

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

    );

} finally {
    stream.close();
}

puis attraper une IOException quelque part en amont.

2
répondu SharkAlley 2013-06-18 15:21:33

créez une fonction n'importe où dans votre projet et appelez simplement cette fonction où vous en avez besoin.

les gars, vous devez vous rappeler que vous les gars appellent des threads actifs que vous n'appelez pas asynchrone et depuis il serait probablement un bon 5 à 10 pages pour obtenir fait correctement. Pourquoi ne pas passer plus de temps sur votre projet et oublier d'écrire tout ce qui a déjà été écrit. Correctement

    //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********/

trois lignes de code deux vraiment depuis le le troisième ajoute du texte. : P

2
répondu Netcfmx 2014-01-02 10:39:19

Bibliothèque

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

Code

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);
    }
}
2
répondu absiddiqueLive 2014-03-24 12:36:55

vous pouvez aussi essayer ceci :

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
}
2
répondu aashima 2014-06-29 12:35:17

mieux utiliser try-with-resources puis tout ce pré-java 7 enfin affaires

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();
    }
}
2
répondu mikeyreilly 2014-08-21 10:35:31

ce code répondra à vos besoins:

   FileWriter fw=new FileWriter("C:\file.json",true);
   fw.write("ssssss");
   fw.close();
2
répondu Shalini Baranwal 2015-12-27 09:31:10
FileOutputStream fos = new FileOutputStream("File_Name", true);
fos.write(data);

le vrai permet d'ajouter les données dans le fichier existant. Si nous écrivons

FileOutputStream fos = new FileOutputStream("File_Name");

Il va écraser le fichier existant. Alors, allez pour une première approche.

2
répondu shakti kumar 2016-07-06 19:48:43
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.
        }

    }

}
2
répondu David Charles 2017-08-28 19:54:37

je pourrais suggérer le apache commons project . Ce projet fournit déjà un cadre pour faire ce dont vous avez besoin (c'est-à-dire un filtrage souple des collections).

1
répondu Tom Drake 2013-08-06 04:58:35

la méthode suivante ajoutons du texte à un fichier:

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

alternativement en utilisant 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);
}

il n'est pas efficace mais fonctionne très bien. Les ruptures de ligne sont gérées correctement et un nouveau fichier est créé si un fichier n'existe pas encore.

1
répondu BullyWiiPlaza 2015-06-07 21:42:57

ma réponse:

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
}
1
répondu userAsh 2015-07-29 13:39:00

dans le cas où vous voulez ajouter un peu de texte dans les lignes spécifiques vous pouvez d'abord lire le fichier entier, ajouter le texte où vous voulez et puis écraser tout comme dans le code ci-dessous:

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();
    }
}
1
répondu lfvv 2016-09-19 13:02:10
/**********************************************************************
 * 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()
0
répondu Mihir Patel 2016-07-13 12:23:46

vous pouvez utiliser le code suivant pour ajouter le contenu dans le fichier:

 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(); 
0
répondu shriram 2017-10-04 12:58:07

1.7 Approche:

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);
    }*/
}
-1
répondu Sawan Patwari 2018-05-27 11:34:38