How to erase existing text in a file - java

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.

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.

As already mentioned, the [FileWriter][1] constructor allows you to specify to clear the existing text and start at the beginning of the file. Some other remarks about the code:
The check on output.exists() is redundant after a call to output.canWrite() and isn't needed. output.canWrite() will check if the file exists and that you can write to it.
Don't forget to close the BufferedWriter object.
Like so:
if (output.canWrite()) {
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter(output, false));
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;
}
} catch (IOException e) {
// Do what you want here, print a message or something
} finally {
if(out != null) {
try {
out.close();
} catch (IOException e) {
// Again, do what you want here
}
}
}
}
[1]: http://java.sun.com/j2se/1.4.2/docs/api/java/io/FileWriter.html#FileWriter(java.io.File, boolean)

Okay so I tried something and it worked. This is when you have a file that is intended to append any new text, but you want to reset/erase the contents of the file at the beginning of program execution. Hope I made sense.
PrintWriter pw1 = new PrintWriter(new BufferedWriter(new FileWriter("newfile.txt")));
pw1.close(); // Make sure the first PrintWriter object name is different from the second one.
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("newfile.txt", true))); // PrintWriter in append-mode. When you recreate the text file with the same name, the file contents are erased because the previous object was not in append mode.
pw.close();

Related

Append list of string to end of text file in Android external storage

I am trying to write an array of string into the external storage of Android emulator. Here is my code:
private void writeToFile(String[] data) {
File workingDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS + "/wordlist.txt");
try (BufferedWriter bw = new BufferedWriter(new FileWriter(workingDir))) {
for (String line : data) {
bw.write(line + "\n");
}
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
It did managed to write each of the item in string array into the text file. However, the next time when I execute this function again, it wipes all the previous existing strings in the text file and replaced them instead. Any ideas on how to keep append new strings to the end of the file?
Thanks!
I solved it already. Basically I need to read all the existing text from the text file, add them to a new list, then append the latest string onto the new list, then proceed to write to the text file.
You can use the append option to append to the existing file without overwriting it.
BufferedWriter bw = new BufferedWriter(new FileWriter(workingDir, true))
The optional true argument sets the file writer to append mode. Also see the answers here.

Unexpected extra characters in file written with RandomAccessFile.writeBytes()

I'm trying to write(and read) string to file using the "RandomAccessFile", but "fio.writeBytes(file1str)" adds the some garbage at the end of the string:
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.println("Enter the D of planets: ");
file1str = in.readLine();
fio = new RandomAccessFile(new File("file1"), "rw");
fio.writeBytes(file1str);
System.out.println("Your enter: ");
for (String retval: file1str.split(",")) {
System.out.println(retval);
}
fio.close();
System.out.println("Data saves to 'file1'!");
}
catch(FileNotFoundException e){
System.out.println("File not found");
}
catch(IOException e){
System.out.println("Error1");
}
}
....But if we are open the file, we see additional 10700 at the end:
Sorry for my bad english
When you create a RandomAccessFile with mode = "rw", the documentation says "If the file does not already exist then an attempt will be made to create it."
This means that if the file already exists, then no attempt will be made to create it, delete it, truncate it, etc.
So, what is happening is that for whatever reason, you already have a "file1" which has 9 characters in it, and what your code does is that it only overwrites the first 4 characters. (The "5,10" part.)
Try deleting the file before writing to it, and everything should be fine.
Alternatively, consider the possibility that choosing a RandomAccessFile was a bad idea to begin with, and instead try using new BufferedWriter(new FileWriter(file)), to write a normal text file the normal way that normal people normally use.

Java FileWriter not actually changing file at all

I have been looking for the past hour or so trying to find the reason for this, but have found nothing. It is a very small text file (only 4 characters at most), thus the reason I did not bother with a BufferedReader or BufferedWriter. The problem lies in the fact that while I have the writer put the variable into the file and even close the file, it does not actually keep the change in the file. I have tested this by checking the file immediately after running the method containing this code.
try {
int subtract = Integer.parseInt(secMessage[2]);
try {
String deaths = readFile("C:/Users/Samboni/Documents/Stuff For Streaming/deaths.txt", Charset.defaultCharset());
FileWriter write = new FileWriter("C:/Users/Samboni/Documents/Stuff For Streaming/deaths.txt");
int comb = Integer.parseInt(deaths) - subtract;
write.write(comb);
write.close();
sendMessage(channel, "Death count updated to " + comb);
} catch (IOException e) {
e.printStackTrace();
}
} catch (NumberFormatException e) {
e.printStackTrace();
sendMessage(channel, "Please use numbers to modify death count");
}
EDIT: Since it was asked, here is my readFile message:
static String readFile(String path, Charset encoding) throws IOException {
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
I have already tested it and it returns the contents without error.
EDIT2: Posting the readFile method made me think of something to try, so I removed the call to it (code above also updated) and tried it again. It now writes to the file, but does not write what I want. New question will be made for this.
FileWriter write = new FileWriter(readFile("C:/Users/Samboni/Documents/Stuff For Streaming/deaths.txt", Charset.defaultCharset()));
You're trying to write a file named after the contents of deaths.txt. It's possible that you intend to be writing to the file itself.
From http://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html
FileWriter(String fileName)
Constructs a FileWriter object given a file name.
FileWriter write = new FileWriter(readFile("C:/Users/Samboni/Documents/Stuff For Streaming/deaths.txt", Charset.defaultCharset()));
Currently you are using the contents of the file instead of the file name.

How to add a line in a text file without overwriting it (JAVA)?

My data is stored in an ArrayList whose size increases during program execution.
I managed to save all the data whenever the size increases, but this brings me to overwrite the data already stored.
The solution is to go directly to the bottom line and insert the contents of the last cell of ArrayList. Unfortunately I do not know how to implement it.
Thank you for helping me to do this.
Below is the method I used.
private void SaveLocationData(){
try {
FileOutputStream output = openFileOutput("latlngpoints.txt",Context.MODE_PRIVATE);
DataOutputStream dout = new DataOutputStream(output);
dout.writeInt(LocationList.size());
for (Location location : LocationList) {
dout.writeUTF(location.getLatitude() + "," + location.getLongitude());
}
dout.flush(); // Flush stream ...
dout.close(); // ... and close.
} catch (IOException exc) {
exc.printStackTrace();
}
}
Use MODE_APPEND:
FileOutputStream output = openFileOutput("latlngpoints.txt",Context.MODE_APPEND);
From the doc:
File creation mode: for use with openFileOutput(String, int), if the
file already exists then write data to the end of the existing file
instead of erasing it.
You can try this too
FileWriter fstream = new FileWriter("x.txt",true); //this will allow to append
BufferedWriter fbw = new BufferedWriter(fstream);
fbw.write("append txt...");
fbw.newLine();
fbw.close();

How to write or append string in loop in a file in java?

I'm having memory problem as working with very large dataset and getting memory leaks with char[] and Strings, don't know why! So I am thinking of writing some processed data in a file and not store in memory. So, I want to write texts from an arrayList in a file using a loop. First the program will check if the specific file already exist in the current working directory and if not then create a file with the specific name and start writing texts from the arrayList line by line using a loop; and if the file is already exist then open the file and append the 1st array value after the last line(in a new line) of the file and start writing other array values in a loop line by line.
Can any body suggest me how can I do this in Java? I'm not that good in Java so please provide some sample code if possible.
Thanks!
I'm not sure what parts of the process you are unsure of, so I'll start at the beginning.
The Serializable interface lets you write an object to a file. Any object that implemsents Serializable can be passed to an ObjectOutputStream and written to a file.
ObjectOutputStream accepts a FileOutputStream as argument, which can append to a file.
ObjectOutputstream outputStream = new ObjectOutputStream(new FileOutputStream("filename", true));
outputStream.writeObject(anObject);
There is some exception handling to take care of, but these are the basics. Note that anObject should implement Serializable.
Reading the file is very similar, except it uses the Input version of the classes I mentioned.
Try this
ArrayList<String> StringarrayList = new ArrayList<String>();
FileWriter writer = new FileWriter("output.txt", true);
for(String str: StringarrayList ) {
writer.write(str + "\n");
}
writer.close();
// in main
List<String> SarrayList = new ArrayList<String>();
.....
fill it with content
enter content to SarrayList here.....
write to file
appendToFile (SarrayList);
.....
public void appendToFile (List<String> SarrayList) {
BufferedWriter bw = null;
boolean myappend = true;
try {
bw = new BufferedWriter(new FileWriter("myContent.txt", myappend));
for(String line: SarrayList ) {
bw.write(line);
bw.newLine();
}
bw.flush();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
if (bw != null) try {
bw.close();
} catch (IOException ioe2) {
// ignore it or write notice
}
}
}

Categories

Resources