1

I want to append to the file and if its not empty; and want to write if its empty. Below is is my code. write function works, append is not. Can anyone guide here?

public class Filecreate {
public static void main(String args[]) throws IOException {
    File file = new File("newFileCreated.txt");
    System.out.println("file path "+file.getAbsolutePath() +" file length - "+file.length());
    FileWriter myWriter = new FileWriter(file);
    if((int)file.length() != 0){
        myWriter.append("appended text\n");
    }else{
        myWriter.write("Files in Java might be tricky, but it is fun enough!");
    }
    myWriter.close();
    System.out.println("file length after writing to file "+file.length());
}

}

learningIsFun
  • 142
  • 1
  • 9

2 Answers2

1

The issue occurs because you measure file's size after you open it. Thus, you have to check file's size before you open it. Also, I won't recommend to cast long to int, because your solution won't work on big files. To conclude, following code will work for you:

    public static void main(String[] args) throws IOException {
    File file = new File("newFileCreated.txt");
    long fileSize = file.length();
    System.out.println("file path "+file.getAbsolutePath() +" file length - "+file.length());
    FileWriter myWriter = new FileWriter(file);

    if(fileSize > 0L){
        myWriter.append("appended text\n");
    }else{
        myWriter.write("Files in Java might be tricky, but it is fun enough!");
    }
    myWriter.close();
    System.out.println("file length after writing to file "+file.length());
}
1

You don't need to worry about whether or not the file contains anything. Just apply the argument of true to the append parameter in the FileWriter constructor then always use the Writer#append() method, for example:

String ls = System.lineSeparator();
String file = "MyFile.txt";

FileWriter myWriter = new FileWriter(file, true)
myWriter.append("appended text" + ls);

/* Immediately write the stream to file. Only really 
   required if the writes are in a loop of some kind 
   and you want to see the write results right away. 
   The close() method also flushes the stream to file 
   before the close takes place.  */
myWriter.flush();   

System.out.println("File length after writing to file " + 
                   new File(file).length());
myWriter .close();
  • If the file doesn't already exist it will be automatically created and the line appended to it.
  • If the file is created but is empty then the line is appended to it.
  • If the file does contain content then the line is merely appended to that content.
DevilsHnd - 退職した
  • 8,739
  • 2
  • 19
  • 22