Problem with overwriting a file using IO package
Dear moderators and members,
A greeting of peace.
Good day to everyone, I hope everyone is in good health upon reading this thread of mine. Well, I have this program created just a while ago:
Code :
import java.io.*;
public class FileWriteAndRead{
public static void main(String args[]) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bfw = new BufferedWriter(new FileWriter("sample.txt"));
BufferedReader bfr = new BufferedReader(new FileReader("sample.txt"));
String number="";
System.out.print("Please enter a number: ");
try{
number = br.readLine();
bfw.write(number);
}catch(Exception ioe){ }
System.out.println("The name was successfully written in a file.");
try{
name = bfr.readLine();
name = ((Integer.parseInt(name)) *100) + " ";
bfw.write(name);
}catch(FileNotFoundException fnfe){}
System.out.println("The new content of the file is: "+name);
bfw.close();
bfr.close();
}//end of main
}//end of class
My plan is to enter a number, write it in a text file, get it again so that it will be multiplied by 100, then the result will be written again on the file, thus I want to overwrite my file, but the sad thing part is, the result is just keep on adding on the file (Example, if I enter 2, the text file has a content of 2200 instead of 200 alone (the number 2 was not deleted/overwritten). What am I doing wrong in my program?Am I missing something? I hope everyone with a good heart will correct me in my program. By the way, I am using JDK6 update 12 (I guess it has nothing to do with it, right?). Thank you in advance and more power to everyone. God bless everyone.
Respectfully yours,
MarkSquall
Re: A problem with overwriting a file, please help.
Quick Solution, close and reopen in truncate mode.
Or you could try using the reset method on your stream.
Chris
Re: A problem with overwriting a file, please help.
Hello marksquall and welcome to the Java Programming Forums :D
I have re-wrote this code for you in a way that I would do it and added comments so you can see whats going on.
Code :
import java.io.*;
import java.util.Scanner;
public class FileWriteAndRead {
public static int myNumber;
public static int getNumber;
public static int endNumber;
public static void main(String args[]) {
// Read user input using the scanner class
System.out.println("Please enter a number: ");
Scanner sc = new Scanner(System.in);
myNumber = sc.nextInt();
// Call write file method
writeFile();
}
public static void writeFile() {
// Convert integer value to string for writing file
String myString = Integer.toString(myNumber);
// Write to file
try {
Writer output = null;
File file = new File("sample.txt");
output = new BufferedWriter(new FileWriter(file));
output.write(myString);
output.close();
System.out.println("File written");
// Call the read file method to get the saved number
readFile();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void readFile() {
System.out.println("Reading file");
// Read the number value from the saved file
try {
FileInputStream in = new FileInputStream("sample.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
getNumber = Integer.parseInt(strLine);
}
// Call calculations method
calculations();
} catch (Exception e) {
System.out.println(e);
}
}
public static void calculations() {
// Take our integer value and * by 100
endNumber = (getNumber * 100);
System.out.println(getNumber + " * 100 = " + endNumber);
// Call rewrite method
reWriteFile();
}
public static void reWriteFile() {
System.out.println("Saving to file");
// Convert integer value to string for writing file
String myString = Integer.toString(endNumber);
// Write to file
try {
Writer output = null;
File file = new File("sample.txt");
output = new BufferedWriter(new FileWriter(file));
output.write(myString);
output.close();
System.out.println("File written");
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("");
System.out.println("All done!");
}
}
Re: A problem with overwriting a file, please help.
I've also edited and fixed your original code.
Code :
import java.io.*;
public class FileWriteAndRead {
public static String name;
public static void main(String args[]) throws IOException {
//for reading user input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//for writing file
BufferedWriter bfw = new BufferedWriter(new FileWriter("sample.txt"));
//for writing file
BufferedWriter bfw2 = new BufferedWriter(new FileWriter("sample.txt"));
//for reading in file
FileInputStream in = new FileInputStream("sample.txt");
BufferedReader br2 = new BufferedReader(new InputStreamReader(in));
String number = "";
System.out.print("Please enter a number: ");
try {
number = br.readLine();
bfw.write(number);
bfw.close();
} catch (Exception ioe) {
}
System.out.println("The number was successfully written in a file.");
try {
name = br2.readLine();
name = ((Integer.parseInt(name))*100) + " ";
bfw2.write(name);
bfw2.close();
} catch (Exception e) {
System.out.println(e);
}
System.out.println("The new content of the file is: " + name);
br2.close();
}// end of main
}// end of class
Overwhelming thanks to Mr. JavaPF and Mr. Freaky Chris,
Dear Mr. JavaPF and Mr. Freaky Chris,
I want to extend my gratitude for giving suggestion on how to solve my problem. I never thought Mr. JavaPF would have time giving a new code plus editing mine, wow...hehehe.:">
I guess what Mr. F. Chris also reflect what Mr. JavaPF tried to do in his new program, i.e. to close and reopen in truncate mode, but I'm not quite sure about this though, but what I understand is that Mr. JavaPF created a new object for BufferedWriter and BufferedReader class.
Code :
BufferedWriter bfw2 = new BufferedWriter(new FileWriter("sample.txt"));
//for reading in file
FileInputStream in = new FileInputStream("sample.txt");
BufferedReader br2 = new BufferedReader(new InputStreamReader(in));
Anyway, I hope to hear and learn from you all, I guess I still have a long, long way in studying Java, but as long as javaprogrammingforums.com is here, learning Java will be fun and easy. Thank you and more power to you Mr. JavaPF and Mr. Freaky Chris. God bless you all!:o
Respectfully Yours,
MarkSquall
Re: A problem with overwriting a file, please help.
The reason for creating a second buffered reader is the same as opening and reclosing, here's a small example.
Writer || Position in file
BFW1 || 0
BFW2 || 0
...> write to file
BFW1 || 3
BFW2 || 0
....close BFW1
....BFW2 -> write to file
from position 0, so it overwrites.
Thats probably hard to understand, cause I'm useless at explaining things :P
Chris
Re: A problem with overwriting a file, please help.
Glad we could help MarkSquall,
We're here any time ;)