0

I am pretty new to Java and I came across this problem. I want the java code to make a txt file if it does not exist already, but if it does, I want PrintWriter to append to it using FileWriter. Here is my code:

Edit: I attempted to fix my code but now I am getting the IOException error. What am I doing wrong here? Edit 2: I think my code is unique since I am trying to make it create a new file if the file does not exist, and make it append to the existing file if it already exists.

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

/**
 * Created by FakeOwl96 on 3/28/2017.
 */
public class AreaOfCircle {
    private static double PI = Math.PI;
    private double radius;
    private static double area;
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        AreaOfCircle a = new AreaOfCircle();
        System.out.print("Type in the radius of circle: ");
        a.radius = keyboard.nextDouble();
        getArea(a.radius);
        System.out.print("Name of the txt file you want to create:");
        String fileName = keyboard.nextLine();
        keyboard.nextLine();
        try {
            File myFile = new File(fileName);
            if (!myFile.exists()) {
                myFile.createNewFile();
            }
            FileWriter fw = new FileWriter(myFile, true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write("The area of the circle is " + area + ".\n");
            bw.close();
        }
        catch (IOException e) {
            System.out.println("IOException Occured");
            e.printStackTrace();
        }
    }

    public static void getArea(double n) {
        area = n * PI;
    }
}
FakeOwl96
  • 5
  • 2
  • Possible duplicate of [How to append text to an existing file in Java](http://stackoverflow.com/questions/1625234/how-to-append-text-to-an-existing-file-in-java) – Lukas Körfer Mar 29 '17 at 21:26
  • Thank you but I did not think so since I am trying to make the code create the txt file if it does not exist already. – FakeOwl96 Mar 29 '17 at 21:43
  • The linked question provides a lot of answers, also containing the creation of missing files. If you look closely, you will see, that a lot of answers on this question equal the ones from the linked question. This is why I suggested this question as __possible__ duplicate. – Lukas Körfer Mar 29 '17 at 21:46
  • Ahhh gotcha. I will take a closer look. I did kinda skimmed through them lol – FakeOwl96 Mar 29 '17 at 22:09

5 Answers5

0

Add following line after initializing myFile:

myFile.createNewFile(); // if file already exists will do nothing
Pavlo Viazovskyy
  • 927
  • 5
  • 12
0

This is an example of file append line and create new file if file is not exists.

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class AppendFileDemo {

    public static void main(String[] args) {
        try {
            String content = "This is my content which would be appended "
                    + "at the end of the specified file";
            //Specify the file name and path here
            File file = new File("myfile.txt");

            /* This logic is to create the file if the
         * file is not already present
             */
            if (!file.exists()) {
                file.createNewFile();
            }

            //Here true is to append the content to file
            FileWriter fw = new FileWriter(file, true);
            //BufferedWriter writer give better performance
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(content);
            //Closing BufferedWriter Stream
            bw.close();

            System.out.println("Data successfully appended at the end of file");

        } catch (IOException ioe) {
            System.out.println("Exception occurred:");
            ioe.printStackTrace();
        }
    }
}
Pang
  • 9,564
  • 146
  • 81
  • 122
Shekhar
  • 54
  • 5
  • Thank you so much! By the way, is there a reason why BufferedWriter is better than PrintWriter? Should I start using BufferedWriter rather than using PrintWriter all the time? – FakeOwl96 Mar 29 '17 at 20:58
  • Also, I tried to fix my code by your solution, and now I'm getting the IOException. What am I doing wrong? – FakeOwl96 Mar 29 '17 at 21:07
0

This is another example of file append line and create new file if file is not exists.

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class AppendFileDemo2 {

    public static void main(String[] args) {
        try {
            File file = new File("myfile2.txt");
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter fw = new FileWriter(file, true);
            BufferedWriter bw = new BufferedWriter(fw);
            PrintWriter pw = new PrintWriter(bw);
            //This will add a new line to the file content
            pw.println("");
            /* Below three statements would add three 
           * mentioned Strings to the file in new lines.
             */
            pw.println("This is first line");
            pw.println("This is the second line");
            pw.println("This is third line");
            pw.close();

            System.out.println("Data successfully appended at the end of file");

        } catch (IOException ioe) {
            System.out.println("Exception occurred:");
            ioe.printStackTrace();
        }
    }
}
Shekhar
  • 54
  • 5
0
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class AreaOfCircle {
    private static double PI = Math.PI;
    private double radius;
    private static double area;
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        AreaOfCircle a = new AreaOfCircle();
        System.out.print("Type in the radius of circle: ");
        a.radius = keyboard.nextDouble();
        getArea(a.radius);
        System.out.print("Name of the txt file you want to create:");
        String fileName = keyboard.next();
        keyboard.nextLine();
        try {
            File myFile = new File(fileName);
            if (!myFile.exists()) {
                myFile.createNewFile();
            }
            FileWriter fw = new FileWriter(myFile, true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write("The area of the circle is " + area + ".\n");
            bw.close();
        }
        catch (IOException e) {
            System.out.println("IOException Occured");
            e.printStackTrace();
        }
    }

    public static void getArea(double n) {
        area = n * PI;
    }
}

The only change I made is String fileName = keyboard.next(); from //keyboard.nextLine() The above code worked for me . Hope this helps.

  • Thank you. After changing keyboard.nextLine() to keyboard.next() it worked for me as well. Could you provide a brief explanation why nextLine() triggers the IOException? – FakeOwl96 Apr 04 '17 at 19:35
  • nextLine() Advances this scanner past the current line and returns the input that was skipped. https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#nextLine-- Using keyboard.nextLine() makes the fileName empty and hence its trying to create an empty file if (!myFile.exists()) {myFile.createNewFile();} which is causing an IOException. – Anusha Dwivedula Apr 05 '17 at 21:02
  • @FakeOwl96 Do you have any other questions. If you are satisfied with my explanation, do you mind accepting my answer? – Anusha Dwivedula Jul 14 '17 at 19:39
  • I totally forgot xD I will! – FakeOwl96 Jul 14 '17 at 19:40
0

Yet, another example, this time with try-with-resources and using the Files class to create the BufferedWriter:

public void write(File file, String text) throws IOException {
    Path path = file.toPath();
    Charset charSet = StandardCharsets.UTF_8;
    OpenOption[] options = new OpenOption[]{
        StandardOpenOption.CREATE, // Create a new file if it does not exist
        StandardOpenOption.WRITE,  // Open for write access
        StandardOpenOption.APPEND  // Bytes will be written to the end of
                                   // the file rather than the beginning
    };
    try (BufferedWriter bw = Files.newBufferedWriter(path, charSet, options)) {
        bw.write(text);
    }
}

The above example is available on GitHub with tests.

You can also use the Files.write method:

public void write(File file, List<String> lines) throws IOException {
    Path path = file.toPath();
    Charset charSet = StandardCharsets.UTF_8;
    OpenOption[] options = new OpenOption[]{
        StandardOpenOption.CREATE, // Create a new file if it does not exist
        StandardOpenOption.WRITE,  // Open for write access
        StandardOpenOption.APPEND  // Bytes will be written to the end of
                                   // the file rather than the beginning
    };
    Files.write(path, lines, charSet, options);
}
Matruskan
  • 325
  • 3
  • 11