Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

Problems with IO

  Asked By: Sunil    Date: Apr 01    Category: Java    Views: 584
  

I have this method:

private void openFileWrite(String fileName) {
File myFile = new File(fileName);

if (myFile == null || myFile.getName().equals("")) {
System.out.println("Err w1");
}
else {
// Open the file
try {
output = new PrintWriter(new BufferedWriter(
new FileWriter(fileName+"a")));
System.out.println("Success!");
}
catch (IOException e) {
System.out.println("Err w2");
}
}
}

But when I open the file, I always reset the file.
I want to add new registers in the file without reseting the file.

The method to add new registers:
public boolean addRecord() {
try {
for (int i=0; i<20; i++)
output.println(i); // save the value of i
output.flush();
}
catch (Exception io) {
System.out.println("err2");
closeFile();
return false;
}
return true;
}

Share: 

 

2 Answers Found

 
Answer #1    Answered By: Fedde Bakker     Answered On: Apr 01

Well if i am not wrong then FileWriter has an overloaded constructor that
accepts a boolean value like this...

output = new PrintWriter(new BufferedWriter(
new FileWriter(fileName+"a", true)));

after setting it to true it will start adding new information from the end i
guess... for reference browse the API and find out...

 
Answer #2    Answered By: Taylor White     Answered On: Apr 01

Yes, by the given code the file  is always reset, because the FileWriter
constructor you use. You shoud change your code like this::

..... .... new FileWriter( filename  + "a", true);

This will append the file, i.e, open  and position the file pointer at the next
free line available.

You should also consult Java Documentation for help in constructors and IO
functions, or, you can better use an IDE like SUNONE Studio for auto code
completion and hints.

 
Didn't find what you were looking for? Find more on Problems with IO Or get search suggestion and latest updates.




Tagged: