I am creating a csv file as follows:
public class check
{
public static void main(String [] args)
{
generateCsvFile("/RMT/test.csv");
}
private static void generateCsvFile(String sFileName)
{
try
{
FileWriter writer = new FileWriter(sFileName,false);
writer.write("DisplayName");
writer.write(',');
writer.write("Age");
writer.write('\n');
writer.write("MKYONG");
writer.write(',');
writer.write("26");
writer.write("YOUR NAME");
writer.write(',');
writer.write("29");
writer.flush();
writer.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
Here I am writing two lines in the file, but when I am writing the second line I want to replace the first line (the header) rather than append it. How can i do it? Can some help me?
I would read the csv data into memory and do the calculation, then write the result to the file.
if it won’t work for you somehow:
you could load the file you are gonna write to, and read the 1st line( header), then append new calculated datasets (in memory), overwrite the file.
if the header is fixed text, then save it as a variable then you don’t need to load the header from the file.
if you need operate the file precisely, check out java.io.RandomAccessFile