Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 7 of 7

Thread: Problem with overwriting a file using IO package

  1. #1
    Junior Member marksquall's Avatar
    Join Date
    Jan 2009
    Posts
    27
    My Mood
    Fine
    Thanks
    0
    Thanked 1 Time in 1 Post

    Unhappy 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:

    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


  2. #2
    Senile Half-Wit Freaky Chris's Avatar
    Join Date
    Mar 2009
    Posts
    834
    My Mood
    Cynical
    Thanks
    7
    Thanked 105 Times in 90 Posts

    Default 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

  3. #3
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 294 Times in 227 Posts
    Blog Entries
    4

    Default Re: A problem with overwriting a file, please help.

    Hello marksquall and welcome to the Java Programming Forums

    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.

    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!");
     
        }
     
    }
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

  4. #4
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 294 Times in 227 Posts
    Blog Entries
    4

    Default Re: A problem with overwriting a file, please help.

    I've also edited and fixed your original 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
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

  5. #5
    Junior Member marksquall's Avatar
    Join Date
    Jan 2009
    Posts
    27
    My Mood
    Fine
    Thanks
    0
    Thanked 1 Time in 1 Post

    Talking 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.

             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!

    Respectfully Yours,

    MarkSquall

  6. #6
    Senile Half-Wit Freaky Chris's Avatar
    Join Date
    Mar 2009
    Posts
    834
    My Mood
    Cynical
    Thanks
    7
    Thanked 105 Times in 90 Posts

    Default 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

    Chris

  7. #7
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 294 Times in 227 Posts
    Blog Entries
    4

    Default Re: A problem with overwriting a file, please help.

    Glad we could help MarkSquall,

    We're here any time
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

Similar Threads

  1. Problem on reading file in Java program
    By nathanernest in forum File I/O & Other I/O Streams
    Replies: 2
    Last Post: April 13th, 2009, 08:14 AM
  2. Uploaded file getting saved to Bin directory
    By jazz2k8 in forum JavaServer Pages: JSP & JSTL
    Replies: 1
    Last Post: July 13th, 2008, 01:59 PM

Tags for this Thread