Search code examples
javafilewritetofile

Java, write to file with headings


I have this method that takes one String and writes it to a file. I set the PrintWriter to true because I want to save all the data that is written to it.

I want to have headings on this file. How can I write the headlines to the file and only do it one time?

My method looks like this:

public static void writeToFile(String text) {

    try {
        File f = new File("test.txt");
        FileWriter writer = new FileWriter("test", true); 
        writer.write(text);


        writer.close();
    } catch (IOException ex) {
        System.out.println(ex.getMessage());
    }
}

Solution

  • It's not clear whether your file has multiple heading or not. Assuming your file has only one heading we can do this as follow -

    1. Since your file contain heading only one time, you can check whether the file is accessing for the first time -

    File f = new File(//your file name);
    if(f.exists() && !f.isDirectory()) {
      //write heading
    }  
    

    2. If the file is first time accessed then you can add a header -

    String heading = "Some heading";
    

    The full code looks like -

    public static void writeToFile(String text) {
    
        String heading = "Some heading";
    
        try {
            File f = new File("test.txt");
            FileWriter writer = new FileWriter(f, true); 
    
            if(f.exists() && !f.isDirectory()) {
              writer.write(heading);
           } 
    
            writer.write(text);
    
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        }finally{
            writer.close();
        }
    }