Jak dodać tekst do istniejącego pliku w Javie

Muszę wielokrotnie dodawać tekst do istniejącego pliku w Javie. Jak mam to zrobić?

Author: Jonik, 2009-10-26

30 answers

Czy robisz to dla celów logowania? Jeśli tak, Istnieje kilka bibliotek dla tego . Dwa z najbardziej popularnych to Log4j i Logback.

Java 7 +

Jeśli musisz zrobić to tylko raz, Klasa Files ułatwia to:

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

Uwaga : powyższe podejście rzuci NoSuchFileException, Jeśli plik jeszcze nie istnieje. Nie dołącza również automatycznie nowego wiersza (co często chcesz, gdy dołączanie do pliku tekstowego). odpowiedź Steve ' a Chambersa opisuje, jak można to zrobić z klasą Files.

Jednakże, jeśli będziesz zapisywać do tego samego pliku wiele razy, powyższe musi wielokrotnie otwierać i zamykać plik na dysku, co jest powolną operacją. W tym przypadku buforowany pisarz jest lepszy: {]}

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
}

Uwagi:

  • drugi parametr konstruktora FileWriter powie mu, aby dopisał do pliku, zamiast zapisywać nowy plik. (Jeśli plik nie istnieje, zostanie utworzony.)
  • używanie {[7] } jest zalecane dla drogiego pisarza(takiego jak FileWriter).
  • użycie PrintWriter daje dostęp do składni println, do której prawdopodobnie jesteś przyzwyczajony z System.out.
  • ale BufferedWriter i PrintWriter opakowania nie są bezwzględnie konieczne.

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

Obsługa Wyjątków

Jeśli potrzebujesz solidnej obsługi wyjątków dla starszej Javy, staje się ona bardzo wyrazista:]}
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
Author: Kip,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-03 20:20:48

Możesz użyć fileWriter z flagą ustawioną na true , do dodawania.

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
Author: northpole,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-24 08:39:44

Nie wszystkie odpowiedzi tutaj z try / catch bloków mają .close () kawałki zawarte w bloku finally?

Przykład zaznaczonej odpowiedzi:

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

Również, począwszy od Javy 7, możesz użyć instrukcji try-with-resources . Do zamknięcia zadeklarowanych zasobów nie jest wymagany żaden blok, ponieważ jest on obsługiwany automatycznie, a także jest mniej gadatliwy:

try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("writePath", true)))) {
    out.println("the text");
}catch (IOException e) {
    System.err.println(e);
}
 64
Author: etech,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-06-08 06:10:26

Edit - od Apache Commons 2.1, poprawnym sposobem jest:

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

dostosowałem rozwiązanie @Kip do poprawnego zamykania pliku na końcu:

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
Author: ripper234,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-12-07 10:19:47

Upewnij się, że strumień zostanie prawidłowo zamknięty we wszystkich scenariuszach.

To trochę niepokojące, ile z tych odpowiedzi pozostawia otwarty uchwyt pliku w przypadku błędu. Odpowiedź https://stackoverflow.com/a/15053443/2498188 jest na pieniądze, ale tylko dlatego, że BufferedWriter() nie może rzucać. Jeśli to możliwe, to wyjątek pozostawi obiekt FileWriter otwarty.

Bardziej ogólny sposób na to, że nie obchodzi mnie, czy BufferedWriter() może rzucać:

  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:

Od Java 7, the zalecanym sposobem jest użycie "try with resources" i pozwolić JVM sobie z tym poradzić:

  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
Author: Emily L.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:02:22

Aby nieco rozszerzyć odpowiedź Kipa , poniżej znajduje się prosta metoda Javy 7+, aby dodać nową linię do pliku, tworząc ją, jeśli jeszcze nie istnieje :

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

Uwaga: powyższe używa Files.write przeciążenie, które zapisuje linie tekstu do pliku (tzn. podobne do polecenia println). Aby po prostu napisać tekst do końca (tj. podobne do polecenia print), alternatywa Files.write można zastosować przeciążenie, przechodząc w tablicę bajtów (np. "mytext".getBytes(StandardCharsets.UTF_8)).

 18
Author: Steve Chambers,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-05 07:55:08

W Javie-7 również można to zrobić tego typu:

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
Author: Tsolak Barseghyan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-14 16:33:17

Próbka z użyciem guawy:

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
Author: dantuch,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-06-04 19:17:24

Można to zrobić w jednej linii kodu. Mam nadzieję, że to pomoże:)

Files.write(Paths.get(fileName), msg.getBytes(), StandardOpenOption.APPEND);
 6
Author: FlintOff,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-06 17:38:43

Java 7+

Moim skromnym zdaniem, ponieważ jestem fanem zwykłej Javy, sugerowałbym coś, że jest to kombinacja wyżej wymienionych odpowiedzi. Może jestem spóźniona na przyjęcie. Oto kod:

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

Jeśli plik nie istnieje, tworzy go i jeśli już istnieje, dopisuje sampleText do istniejącego pliku. Dzięki temu unikniesz dodawania niepotrzebnych bibliotek do ścieżki klasowej.

 6
Author: Lefteris Bab,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-09 06:59:04

Dodaję tylko mały szczegół:

    new FileWriter("outfilename", true)

2.parametr ND (true) jest funkcją (lub, interfejsem) o nazwie appendable (http://docs.oracle.com/javase/7/docs/api/java/lang/Appendable.html ). jest odpowiedzialny za możliwość dodania pewnej zawartości na końcu danego pliku / strumienia. Interfejs ten jest zaimplementowany od wersji Java 1.5. Każdy obiekt (np. BufferedWriter, CharArrayWriter, CharBuffer, FileWriter, FilterWriter, LogStream, OutputStreamWriter, PipedWriter, PrintStream, PrintWriter, StringBuffer, StringBuilder, StringWriter, Writer ) za pomocą tego interfejsu można dodawać treści

Innymi słowy, możesz dodać jakąś zawartość do pliku gzipped, lub jakiś proces http

 5
Author: xhudik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-12-13 10:56:43

Korzystanie z Javy.nio.Pliki wraz z Javą.nio.plik.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();

To tworzy BufferedWriter za pomocą Plików, które akceptują parametry StandardOpenOption oraz automatyczne spłukiwanie PrintWriter z wynikowego BufferedWriter. PrintWriter ' S println() metoda, może być wywołana do zapisu do pliku.

Parametry StandardOpenOption użyte w tym kodzie: otwierają plik do zapisu, tylko dołączają do pliku i tworzą plik, jeśli nie istnieje.

Paths.get("path here") można wymienić na new File("path here").toPath(). I Charset.forName("charset name") mogą być modyfikowane w celu dostosowania do żądanego Charset.

 4
Author: icasdri,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-25 20:16:37

Spróbuj z bufferFileWriter.append, to działa ze mną.

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
Author: Nadhir Titaouine,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
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();         
    }
To zrobi to, co zamierzacie..
 3
Author: Benjamin Varghese,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-01-07 14:56:48

Jeśli korzystamy z Javy 7 i nowszej oraz znamy zawartość dodaną (dołączoną) do pliku, możemy skorzystać z metody newBufferedWriter w pakiecie 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();
    }
}

Jest kilka punktów do odnotowania:

  1. dobrym nawykiem jest zawsze określanie kodowania znaków i do tego mamy stałą w klasie StandardCharsets.
  2. kod używa instrukcji try-with-resource, w której zasoby są automatycznie zamykane po próbie.

Choć OP nie zapytał, ale na wszelki wypadek chcemy wyszukać linie posiadające jakieś konkretne słowo kluczowe np. confidential możemy skorzystać z API stream w Javie:

//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
Author: i_am_zero,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
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();
}

Następnie złapać IOException gdzieś pod prąd.

 2
Author: SharkAlley,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-06-18 15:21:33

Utwórz funkcję w dowolnym miejscu w projekcie i po prostu wywołaj tę funkcję tam, gdzie jej potrzebujesz.

Chłopaki musicie pamiętać, że dzwonicie do aktywnych wątków, których nie nazywacie asynchronicznie, a ponieważ prawdopodobnie byłoby to dobre 5 do 10 stron, aby to zrobić dobrze. Dlaczego nie poświęcić więcej czasu na projekt i nie zapomnieć o pisaniu czegokolwiek już napisanego. Properly

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

Trzy linijki kodu dwa tak naprawdę, ponieważ trzecia faktycznie dołącza tekst. : P

 2
Author: Netcfmx,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-02 10:39:19

Biblioteka

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

Kod

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
Author: absiddiqueLive,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-24 12:36:55

Możesz również spróbować tego:

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
Author: aashima,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-29 12:35:17

Lepiej używać try-with-resources then all that pre-java 7 finally business

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
Author: mikeyreilly,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-21 10:35:31

Ten kod spełni Twoje potrzeby:

   FileWriter fw=new FileWriter("C:\\file.json",true);
   fw.write("ssssss");
   fw.close();
 2
Author: Shalini Baranwal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-27 09:31:10
FileOutputStream fos = new FileOutputStream("File_Name", true);
fos.write(data);

True pozwala na dołączenie danych do istniejącego pliku. Jeśli napiszemy

FileOutputStream fos = new FileOutputStream("File_Name");

Nadpisze istniejący plik. Więc idź do pierwszego podejścia.

 2
Author: shakti kumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
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
Author: David Charles,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-28 19:54:37

Mogę zaproponować projekt apache commons . Ten projekt już zapewnia ramy do robienia tego, czego potrzebujesz (tj. elastyczne filtrowanie kolekcji).

 1
Author: Tom Drake,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-06 04:58:35

Następująca metoda pozwala na dopisanie tekstu do jakiegoś pliku:

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

Alternatywnie używając 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);
}
Nie jest wydajny, ale działa dobrze. Podziały linii są obsługiwane poprawnie i tworzony jest nowy plik, jeśli jeszcze nie istniał.
 1
Author: BullyWiiPlaza,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-07 21:42:57

Moja odpowiedź:

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
Author: userAsh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-29 13:39:00

W przypadku, gdy chcesz Dodać tekst w określonych liniach możesz najpierw przeczytać cały plik, dołączyć tekst w dowolnym miejscu, a następnie nadpisać wszystko jak w poniższym kodzie:

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
Author: lfvv,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
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
Author: Mihir Patel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-13 12:23:46

Możesz użyć kodu follong do dodania zawartości w pliku:

 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
Author: shriram,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-04 12:58:07

1.7 podejście:

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
Author: Sawan Patwari,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-27 11:34:38