24

I am trying to write a method that makes a "log.txt file" if one does not already exist and then writes to the file. The problem that I am encountering is every time I call the method, it overwrites the existing log. How do I change the method so that instead of overwriting the data it just updates the file?

My Write File Method:

    File log = new File("log.txt")
    try{
    if(log.exists()==false){
            System.out.println("We had to make a new file.");
            log.createNewFile();
    }
    PrintWriter out = new PrintWriter(log);
    out.append("******* " + timeStamp.toString() +"******* " + "\n");
    out.close();
    }catch(IOException e){
        System.out.println("COULD NOT LOG!!");
    }
rmp2150
  • 777
  • 1
  • 11
  • 22
  • 4
    PrintWriter pw = new PrintWriter(new FileWriter(New File(), true)); –  Apr 01 '12 at 01:52

9 Answers9

43

Just change PrintWriter out = new PrintWriter(log); to

PrintWriter out = new PrintWriter(new FileWriter(log, true));
Zach Saucier
  • 24,871
  • 12
  • 85
  • 147
Qiang Jin
  • 4,427
  • 19
  • 16
13

use a FileWriter instead.

FileWriter(File file, boolean append)

the second argument in the constructor tells the FileWriter to append any given input to the file rather than overwriting it.

here is some code for your example:

File log = new File("log.txt")

try{
    if(!log.exists()){
        System.out.println("We had to make a new file.");
        log.createNewFile();
    }

    FileWriter fileWriter = new FileWriter(log, true);

    BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
    bufferedWriter.write("******* " + timeStamp.toString() +"******* " + "\n");
    bufferedWriter.close();

    System.out.println("Done");
} catch(IOException e) {
    System.out.println("COULD NOT LOG!!");
}
thrau
  • 2,915
  • 3
  • 25
  • 32
  • It's not necessary to include the `if (!log.exists()) { log.createNewFile(); }` block, as writing to the file will create it if it doesn't already exist. – Greg Kopff Apr 01 '12 at 02:15
  • 2
    It is not necessary, as FileWriter will try to create the file inherently if it does not exist. If the file can not be created, an IOException will be thrown. However adding an additional check helps understandability and also creates a defensive spot in the code to extend error handling. – thrau Apr 01 '12 at 02:21
3

For some reason, none of the other methods worked for me...So i tried this and worked. Hope it helps..

JFileChooser c= new JFileChooser();
c.showOpenDialog(c);
File write_file = c.getSelectedFile();
String Content = "Writing into file\n hi \n hello \n hola";
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) {
    System.out.println(e);
}
userAsh
  • 147
  • 10
2
JFileChooser c= new JFileChooser();
c.showOpenDialog(c);
File write_file = c.getSelectedFile();
String Content = "put here the data to be wriiten";
try
    {
    FileWriter fw = new FileWriter(write_file);
    BufferedWriter bw = new BufferedWriter(fw);
    bw.append(Content);
    bw.append("hiiiii");
    bw.close();
    fw.close();
    }
catch(Exception e)
   {
    System.out.println(e);
   `}
Rohit ZP
  • 212
  • 2
  • 7
1

You can even use FileOutputStream to get what you need. This is how it can be done,

File file = new File(Environment.getExternalStorageDirectory(), "abc.txt");
FileOutputStream fOut = new FileOutputStream(file, true);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write("whatever you need to write");
osw.flush();
osw.close();
Shruti Dasgopal
  • 551
  • 4
  • 10
1

You can change your PrintWriter and use method getAbsoluteFile(), this function returns the absolute File object of the given abstract pathname.

PrintWriter out = new PrintWriter(new FileWriter(log.getAbsoluteFile(), true));

Chris
  • 806
  • 1
  • 10
  • 17
0

try this one

public void writeFile(String arg1,String arg2) {
  try {
   if (!dir.exists()) {

    if (dir.mkdirs()) {

     Toast.makeText(getBaseContext(), "Directory created",
       Toast.LENGTH_SHORT).show();
    } else {
     Toast.makeText(getBaseContext(),
       "Error writng file " + filename, Toast.LENGTH_LONG)
       .show();
    }
   }

   else {

    File file = new File(dir, filename);
    if (!file.exists()) {
     file.createNewFile();
    }
    
    FileWriter fileWritter = new FileWriter(file, true);
    BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
    bufferWritter.write(arg1 + "\n");
    bufferWritter.close();

            } catch (Exception e) {
   e.printStackTrace();
   Toast.makeText(getBaseContext(),
     "Error writng file " + e.toString(), Toast.LENGTH_LONG)
     .show();
  }

 }
Ameen Maheen
  • 2,719
  • 1
  • 28
  • 28
0

Here is a simple example of how it works, best practice to put a try\catch into it but for basic use this should do the trick. For this you have a string and file path and apply thus to the FileWriter and the BufferedWriter. This will write "Hello World"(Data variable) and then make a new line. each time this is run it will add the Data variable to the next line.

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


String Data = "Hello World";
File file = new File("C:/Users/stuff.txt");
FileWriter fw = new FileWriter(file,true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(Data);
bw.newLine();
bw.close();
Grbe1l
  • 489
  • 4
  • 16
0
BufferedWriter login = new BufferedWriter(new FileWriter("login.txt"));

is an example if you want to create a file in one line.

Ralf Stubner
  • 26,263
  • 3
  • 40
  • 75