I want to create a .csv file. I am using the following code:

FileWriter fWriter = null;
BufferedWriter writer = null;
try {
        fWriter = new FileWriter("fileName.csv");
        writer = new BufferedWriter(fWriter);
        writer.write("This,line,is,written");
        writer.newLine();
        writer.close();
    } catch (Exception e) {
    }

Does it create a new file if it does not exist?
What if file already exists? Does it delete the original file and create a new one?

personally, I always added a check to see whether the file exists before starting to read or write, but, to answer your questions:

  1. if the file doesn't exist, a new file with the specified path and name will be created. it's trying to read from a non-existing file that 'll throw an exception.
  2. if the file already exists, by writing this stream, you will overwrite the previous file.
    the original contents will be lost and replaced by the new contents.

now, a recommendation from my part. never, EVER, do something like this:

catch (Exception e) {
    }

this kind of code leads to a lot of beginning developers to sigh:"it doesn't work, yet there is no error or error message, so there's nothing wrong .... "

actually, there might be, but you are 'hiding' the exception that's been thrown.
if you aren't working with logging yet, at the very least, write the code like this:

catch (Exception e) {
    e.printStackTrace();
}

this way, if an exception is thrown, you'll at least be informed of what goes wrong where. I can assure you, this way it'll be a lot easier to debug.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.