开发者

Files clearing themselves upon object creation

I am having an annoying problem that I cannot seem to fix. I have a class named DirFormMgmt which manages two files; directories.txt 开发者_StackOverflowand formats.txt. The problem is that when I instantiate an instance of this class when the program starts it clears everything that was in the files before it started, so for instance if I open the formats.txt file and type in ".avi" and run the program the text file will become blank. Here is the only code I have running in my class to isolate the issue and I am unsure of why this is happening:

At the top of my class I declare:

File dirFile = new File("directories.txt");
File formatFile = new File("formats.txt");
private BufferedReader dirReader;
private BufferedWriter dirWriter;
private BufferedReader formatReader;
private BufferedWriter formatWriter;

The constructor:

public DirFormMgmt() throws IOException {
     checkFileExistence();
     initReaderWriter();
}

The two methods called by the constructor:

public void checkFileExistence() throws IOException {
     if (!dirFile.exists()) {
         dirFile.createNewFile();
     }
     if (!formatFile.exists()) {
         formatFile.createNewFile();
     }   
}

and:

public void initReaderWriter() throws IOException {
     dirReader = new BufferedReader(new FileReader(dirFile));
     dirWriter = new BufferedWriter(new FileWriter(dirFile));

     formatReader = new BufferedReader(new FileReader(formatFile));
     formatWriter = new BufferedWriter(new FileWriter(formatFile));
}

I checked to see if the createNewFile() methods were being called but they were not, so the problem must be with my initReaderWriter() method, but I am unsure of what is wrong, any help is greatly appreciated!


Use new FileWriter(file, true) to append content to an existing file. Otherwise, the contents will be overwritten.


You can't read and write to the same file like this. The FileWriter constructor is used to write to a file and replace all its contents.

EIther read everything in memory, and then write to the file, or write to another temp file, and remove the original file and rename the temp file when you're done.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜