Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (7k points)

I want to write data into a csv file using java and when I open the file it is saying that the file is corrupted. I am using Filewriter class like this:

FileWriter writer = new FileWriter("test.csv");

writer.append("ID");
writer.append(',');
writer.append("name");
writer.append(',');
...
writer.append('\n');

writer.flush();
writer.close();

 Can someone tell me a correct way to do this?

1 Answer

0 votes
by (13.1k points)

You can do something like this:

import java.io.File;

import java.io.FileNotFoundException;

import java.io.PrintWriter;

public class WriteCsv {

  public static void main(String[] args) {

    try (PrintWriter writer = new PrintWriter(new File("file.csv"))) {

      StringBuilder stringbuilder = new StringBuilder();

      stringbuilder.append("id");

      stringbuilder.append(',');

      stringbuilder.append("Name");

      stringbuilder.append('\n');

      stringbuilder.append("1");

      stringbuilder.append(',');

      stringbuilder.append("Joe Root");

      stringbuilder.append('\n');

      writer.write(stringbuilder.toString());

      System.out.println("done!");

    } catch (FileNotFoundException exception) {

      System.out.println(exception.getMessage());

    }

  }

Here, you have to reduce file access by using fewer file objects.

Want to learn Java? Check out this Java certification from Intellipaat

 

Related questions

Browse Categories

...