I'm working on an assignment for school, and am trying something beyond for extra credit. The program is to demonstrate the efficiency differences between a linear & binary search for a given array size of integers. I have a loop set up that creates an int[size] array, searches for a random number, then creates a new array of int[size*2].
The results are then written to a text file. The output writes fine, but after compiling & running the program several times, the output file has that many sections of data.
This is my code that is nested inside a try/catch block:
File output= new File("c:\\BigOhResults.txt");
int counter=2;
if (output.canWrite() && output.exists()) {
BufferedWriter out= new BufferedWriter(new FileWriter(output, true));
out.write(type+" \n\n"); //writes the search type
out.write(type+"Search Results\n\n");
while (counter <= data.size()) {
out.write(data.get(counter-1)+" millisecond runtime " +
"for a "+ data.get(counter-2)+" random number " +"sample size\n");
counter=counter+2;
}
}
Is there any way I can erase the text within that output file upon each time the program is run?
the reason I'm doing this is the professor requires the result printout with the data graphed. I have already completed the graphing requirement, and it works fine. I just want to have the file printout match the graph printout.
Clear a Text File Using the open() Function in write Mode Opening a file in write mode will automatically delete the file's contents. The open() function takes two arguments, the text file we'd like to open and the mode we're opening it in. Opening a file in write mode clears its data.
Another way to create a text file is to right-click an empty area on the desktop, and in the pop-up menu, select New, and then select Text Document. Creating a text file this way opens your default text editor with a blank text file on your desktop. You can change the name of the file to anything you want.
Empty or delete the contents of a large file using the truncate command in the Linux/Unix system. The truncate command is used to shrink or extend the size of a file to a specified size in the Linux system. It is also used to empty large file contents by using the -s option followed by 0 (zero) specified size.
Run the truncate command for a reasonable larger normal size of 10K. Open the file with your text editor and press End. Highlight and PgUp to delete the remaining bytes that don't belong (usually recognizable by ASCII garbage characters).
The second argument to the FileWriter constructor, which you're passing in "true", is "append". I.e. because you've set it to true, it will append your new output to the end of the file. If you pass in false instead, it will wipe the data that's there already and write it new.
Read the documentation for FileWriter. You do not want to append.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With