Writing to an already existing file using FileWriter Java - java

Is there anyway I can write to an already existing file using Filewriter
For example when the user clicks a submit button:
FileWriter writer = new FileWriter("myfile.csv");
writer.append("LastName");
writer.append(',');
writer.append("FirstName");
writer.append('/n');
writer.append(LastNameTextField.getText());
writer.append(',');
writer.append(FirstNameTextField.getText());
I want to be able to write new data into the already existing myfile.csv without having to recreate a brand new one every time

Yeah. Use the constructor like this:
FileWriter writer = new FileWriter("myfile.csv",true);

FileWriter
public FileWriter(File file,
boolean append)
throws IOException
Constructs a FileWriter object given a File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.

Related

Jsoup java rewrites the file string which it should add

code that should read html file and write the result another file the buffered writer writes the file but when the code is run with different urlit doesn't appends but rewrites the file and the previous content disappears
the solution recuired is that when jsoup iterates new html the result should add to output file and not rewrite
changed different writer types other than buffered writer
public class WriteFile
{
public static void main(String args[]) throws IOException
{
String url = "http://www.someurl.com/registers";
Document doc = Jsoup.connect(url).get();
Elements es = doc.getElementsByClass("a_code");
for (Element clas : es)
{
System.out.println(clas.text());
BufferedWriter writer = new BufferedWriter(new FileWriter("D://Author.html"));
writer.append(clas.text());
writer.close();
}
}
}
Don't mistake the append-method of the BufferedWriter as appending content to the file. It actually appends to the given writer.
To actually append additional content to the file you need to specify that when opening the file writer. FileWriter has an additional constructor parameter allowing to specify that:
new FileWriter("D://Author.html", /* append = */ true)
You may even be interested in the Java Files API instead, so you can spare instantating your own BufferedWriter, etc.:
Files.write(Paths.get("D://Author.html"), clas.text().getBytes(), StandardOpenOption.CREATE, StandardOpenOption.APPEND);
Your loop and what you are writing may further be simplifiable to something as follows (you may then even omit the APPEND-open option again, if that makes sense):
Files.write(Paths.get("D://Author.html"),
String.join("" /* or new line? */,
doc.getElementsByClass("a_code")
.eachText()
).getBytes(),
StandardOpenOption.CREATE, StandardOpenOption.APPEND);

Java create a new file, or, override the existing file

What I want to achieve is to create a file regardless of whether the file exists or not.
I tried using File.createNewFile() but that will only create the file if it does not already exists. Should I use File.delete() and then File.createNewFile()?
Or is there a clearer way of doing it?
FileWriter has a constructor that takes 2 parameters too: The file name and a boolean. The boolean indicates whether to append or overwrite an existing file. Here are two Java FileWriter examples showing that:
Writer fileWriter = new FileWriter("c:\\data\\output.txt", true); //appends to file
Writer fileWriter = new FileWriter("c:\\data\\output.txt", false); //overwrites file
You can use a suitable Writer:
BufferedWriter br = new BufferedWriter(new FileWriter(new File("abc.txt")));
br.write("some text");
It will create a file abc.txt if it doesn't exist. If it does, it will overwrite the file.
You can also open the file in append mode by using another constructor of FileWriter:
BufferedWriter br = new BufferedWriter(new FileWriter(new File("abc.txt"), true));
br.write("some text");
The documentation for above constructor says:
Constructs a FileWriter object given a File object. If the second
argument is true, then bytes will be written to the end of the file
rather than the beginning.
Calling File#createNewFile is safe, assuming the path is valid and you have write permissions on it. If a file already exists with that name, it will just return false:
File f = new File("myfile.txt");
if (f.createNewFile()) {
// If there wasn't a file there beforehand, there is one now.
} else {
// If there was, no harm, no foul
}
// And now you can use it.

how can i add data in to json file in java?

i want to add data inside of an existing json file..
this is my code:
JsonWriterWithGui(){
if(ae.getSource() == btn_submit){
String lname = (String)lbl_name.getText().toString();
String ladd = (String)lbl_add.getText().toString();
String lcontact = (String)lbl_contact.getText().toString();
FileWriter jsonFileWriter = new FileWriter( "E:\\"+tsave+".json");
jsonFileWriter.write(jsonObject.toJSONString());
jsonFileWriter.flush();
jsonFileWriter.close();
this code is already working. but I am trying to update a json file that already exists.
This is a bit of a guess because the problem you're having isn't entirely clear from the question, but if you're finding that your writes are overwriting instead of appending then try changing this line:
FileWriter jsonFileWriter = new FileWriter( "E:\\"+tsave+".json");
...to this:
FileWriter jsonFileWriter = new FileWriter("E:\\"+tsave+".json", true);
You see, FileWriter is backed by FileOutputStream, which takes a boolean argument saying whether new content should be appended or not. This boolean is false by default so if you want to append then you need to explicitly say so.

Text File writing in Java

I am writing String content to text file in Java code but after writing saving file onto disk, I am getting Incorrect encoding exception, Please suggest me correct Java Code?
String content =fileContent;//fileContent.toString();
System.out.println("File Contt===>"+content);
File fileWrite = new File("/homeDesktop/NormalFile/"+filename);
// if file doesnt exists, then create it
if (!fileWrite.exists()) {
fileWrite.createNewFile();
}
FileWriter fw = new FileWriter(fileWrite.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(fileContent);
bw.close();
IOUtils.toString(String) Converts your coding.
String not encoded in UTF-8
NOTE:
You dont need this:
// if file doesnt exists, then create it
if (!fileWrite.exists()) {
fileWrite.createNewFile();
}
File create automatically a new file, if there isn't one.

Delete the content of csv file in Java

Every day I update a csv file using a FileWriter. When we step into a new month I have to delete the data from the previous month. My below code only updates a data in a csv file so, please help in deleting the previous month's data.
At least I need to know how to delete the data in csv file using FileWriter, so that I can manage to code for deleting previous month data.
private static void eventsUpdate(HttpServletRequest request,
HttpServletResponse response) {
String date=request.getParameter("date"); //getting from jsp page
String event=request.getParameter("event"); //getting from jsp page
File file = new File( "D:///events/events.csv");
if ( !file.exists() )
file.createNewFile();
FileWriter fw = new FileWriter(file,true);
BufferedWriter writer = new BufferedWriter( fw );
writer.write(date);
writer.write(",");
writer.write(event);
System.out.println("writing into excel");
writer.newLine();
writer.close();
fw.close();
}
Actually when you use the true argument in your FileWriter instantiation, you create a file writer object in append mode.
FileWriter fw = new FileWriter(file,false);
If you don't use the true option, the file will be overwritten by the new content. Therefore, I would suggest to follow this roadmap:
Read the file content as a whole, in a String
Remove the content you want to remove from the specific String
Overwrite the file
content using your new content in the specific String
Hope I helped!
I suggest you that you may create unique name file like march2014, january2013 instead of deleting it. Every month you need to read your target file which is named by your month strategy.
For ex:
When you reach april2014, create a new file april2014 etc. and read it for that month.

Categories

Resources