Domanda

Devo aggiungere il testo ripetutamente a un file esistente in Java. Come posso farlo?

È stato utile?

Soluzione

Lo stai facendo a scopo di registrazione? In tal caso ci sono diverse librerie per questo . Due dei più popolari sono Log4j e Logback .

Java 7+

Se hai solo bisogno di farlo una volta, Classe di file rende tutto semplice:

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

Attento : l'approccio sopra genererà un NoSuchFileException se il file non esiste già. Inoltre, non aggiunge automaticamente una nuova riga (che spesso si desidera quando si aggiunge a un file di testo). La risposta di Steve Chambers illustra come è possibile farlo con la classe Files .

Tuttavia, se si scriverà sullo stesso file molte volte, quanto sopra deve aprire e chiudere il file sul disco molte volte, il che è un'operazione lenta. In questo caso, uno scrittore con buffer è migliore:

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
}

Note:

  • Il secondo parametro del costruttore FileWriter indica che verrà aggiunto al file anziché scrivere un nuovo file. (Se il file non esiste, verrà creato.)
  • L'uso di un BufferedWriter è consigliato per uno scrittore costoso (come FileWriter ).
  • L'uso di un PrintWriter ti dà accesso alla sintassi println a cui probabilmente sei abituato da System.out .
  • Ma i wrapper BufferedWriter e PrintWriter non sono strettamente necessari.

Java precedente

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
}

Gestione delle eccezioni

Se hai bisogno di una solida gestione delle eccezioni per Java precedente, diventa molto dettagliato:

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

Altri suggerimenti

Puoi usare fileWriter con un flag impostato su true , per aggiungere.

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

Tutte le risposte qui con i blocchi try / catch non dovrebbero contenere i pezzi .close () contenuti in un blocco finally?

Esempio di risposta contrassegnata:

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

Inoltre, a partire da Java 7, è possibile utilizzare un try- dichiarazione con risorse . Nessun blocco infine è richiesto per chiudere le risorse dichiarate perché viene gestito automaticamente ed è anche meno dettagliato:

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

Modifica - a partire da Apache Commons 2.1, il modo corretto per farlo è:

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

Ho adattato la soluzione di @ Kip per includere finalmente la chiusura corretta del file:

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

Per espandere leggermente su la risposta di Kip , ecco un semplice metodo Java 7+ per aggiungere una nuova linea a un file, creandolo se non esiste già :

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: quanto sopra utilizza Files.write sovraccarico che scrive righe di testo in un file (cioè simile a un comando println ). Per scrivere solo un testo alla fine (cioè simile a un comando print ), un'alternativa Files.write può essere utilizzato il sovraccarico, passando in un array di byte (ad es. " mytext " .getBytes (StandardCharsets.UTF_8) ).

Assicurati che il flusso venga chiuso correttamente in tutti gli scenari.

È un po 'allarmante quante di queste risposte lasciano aperto l'handle del file in caso di errore. La risposta https://stackoverflow.com/a/15053443/2498188 è valida ma solo perché BufferedWriter () non può essere lanciato. Se fosse possibile, un'eccezione lascerebbe aperto l'oggetto FileWriter .

Un modo più generale di fare ciò a cui non importa se BufferedWriter () può lanciare:

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

Modifica:

A partire da Java 7, il modo consigliato è usare " provare con risorse " e lasciare che la JVM lo gestisca:

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

In Java-7 si può fare anche questo 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+

Secondo la mia modesta opinione da quando sono fan della pianura Java, suggerirei che è una combinazione delle risposte di cui sopra. Forse sono in ritardo per la festa. Ecco il codice:

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

Se il file non esiste, lo crea e se esiste già aggiunge sampleText al file esistente. Usandolo, ti evita di aggiungere lib lib inutili al tuo percorso di classe.

Questo può essere fatto in una riga di codice. Spero che questo aiuti :)

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

Uso di java.nio. File insieme a 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();

Questo crea un BufferedWriter utilizzando Files, che accetta i parametri StandardOpenOption e un PrintWriter con scaricamento automatico dal risultante BufferedWriter . Il metodo println () di PrintWriter , può quindi essere chiamato per scrivere nel file.

I parametri StandardOpenOption utilizzati in questo codice: apre il file per la scrittura, aggiunge solo il file e crea il file se non esiste.

Paths.get (" percorso qui ") può essere sostituito con nuovo file (" percorso qui "). toPath () . E Charset.forName (" nome charset ") può essere modificato per adattarsi al Charset desiderato.

Aggiungo solo piccoli dettagli:

    new FileWriter("outfilename", true)

2.nd parametro (true) è una funzione (o interfaccia) chiamata appendable ( http://docs.oracle.com/javase/7/docs/api/java/lang/Appendable.html ). È responsabile della possibilità di aggiungere del contenuto alla fine di un determinato file / flusso. Questa interfaccia è implementata da Java 1.5. Ogni oggetto (cioè BufferedWriter, CharArrayWriter, CharBuffer, FileWriter, FilterWriter, LogStream, OutputStreamWriter, PipedWriter, PrintStream, PrintWriter, StringBuffer, StringBuilder, StringWriter, Writer ) con questa interfaccia può essere utilizzato per aggiungere contenuto

In altre parole, puoi aggiungere un po 'di contenuto al tuo file gzipped o un processo http

Esempio, usando Guava:

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

Prova con bufferFileWriter.append, funziona con me.

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

questo farà ciò per cui intendi ..

Meglio usare try-with-resources rispetto a tutte quelle attività pre-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();
    }
}

Se utilizziamo Java 7 e versioni successive e conosciamo anche il contenuto da aggiungere (aggiunto) al file, possiamo utilizzare metodo newBufferedWriter nel pacchetto 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();
    }
}

Vi sono alcuni punti da notare:

  1. È sempre una buona abitudine specificare la codifica del set di caratteri e per questo abbiamo una classe costante StandardCharsets .
  2. Il codice utilizza l'istruzione try-with-resource in cui le risorse vengono automaticamente chiuse dopo il tentativo.

Sebbene OP non l'abbia chiesto, ma nel caso in cui desideriamo cercare righe con una parola chiave specifica, ad es. confidenziale possiamo utilizzare le API di streaming in 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();
}

Quindi cattura una IOException da qualche parte a monte.

Crea una funzione ovunque nel tuo progetto e chiama semplicemente quella funzione dove mai ne hai bisogno.

Ragazzi, dovete ricordare che voi ragazzi state chiamando thread attivi che non state chiamando in modo asincrono e dal momento che sarebbe probabilmente un buon 5-10 pagine per farlo bene. Perché non dedicare più tempo al tuo progetto e dimenticare di scrivere qualcosa di già scritto. Correttamente

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

tre righe di codice due in realtà dal momento che il terzo aggiunge effettivamente del testo. : P

  

Libreria

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

Codice

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

Puoi anche provare questo:

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

il vero consente di aggiungere i dati nel file esistente. Se scriveremo

FileOutputStream fos = new FileOutputStream("File_Name");

Sovrascriverà il file esistente. Quindi vai per il primo approccio.

Potrei suggerire il progetto apache commons . Questo progetto fornisce già un framework per fare ciò di cui hai bisogno (ovvero filtraggio flessibile delle raccolte).

Il seguente metodo consente di aggiungere del testo ad alcuni file:

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

In alternativa, utilizzando 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);
}

Non è efficiente ma funziona bene. Le interruzioni di riga vengono gestite correttamente e viene creato un nuovo file se non ne esiste ancora uno.

Questo codice soddisferà le tue necessità:

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

Nel caso in cui desideri AGGIUNGERE ALCUNI TESTI IN LINEE SPECIFICHE puoi prima leggere l'intero file, aggiungere il testo dove vuoi e quindi sovrascrivere tutto come nel codice qui sotto:

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

La mia risposta:

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

È possibile utilizzare il seguente codice per aggiungere il contenuto nel file:

 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 Approccio:

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);
    }*/
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top