Results 1 to 19 of 19
Like Tree3Likes
  • 1 Post By gimbal2
  • 1 Post By jim829
  • 1 Post By kkid

Thread: Writing a text file

  1. #1
    kkid is offline Senior Member
    Join Date
    Jul 2012
    Posts
    226
    Rep Power
    3

    Default Writing a text file

    I am writing a Java notepad at the moment and am just setting up the saving process.

    This is the code I have so far for a button in a JMenu (I am ignoring any selection of file location at the moment, I just want it to write a file) using code adapted from tutorials I have seen online. However, my output is only a blank .txt file (although the location and file name are correct).

    Can somebody please identify why?

    Thank you

    Java Code:
    JMenuItem Save = new JMenuItem("Save");
            File.add(Save);
            Save.addActionListener(new ActionListener(){
                @Override
                public void actionPerformed(ActionEvent e) {
                    try{
                        File textFile = new File("C:/Users/Mike/Desktop/JavaNotepadOutput.txt");
                        if (textFile.exists() == false) {
                            textFile.createNewFile();
                        }
                        
                        FileWriter fw = new FileWriter(textFile.getAbsoluteFile());
                        BufferedWriter bw = new BufferedWriter(fw);
                        bw.write(TextArea.getText());
                    }
                    
                    catch (IOException IOException){
                        IOException.printStackTrace();
                    }
                    }
                });

  2. #2
    kkid is offline Senior Member
    Join Date
    Jul 2012
    Posts
    226
    Rep Power
    3

    Default Re: Writing a text file

    I've also came across different methods such as this:

    Java Code:
    PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
    writer.println("The first line");
    writer.println("The second line");
    writer.close();
    Source: Java: how to create and write to a file - Stack Overflow


    To be perfectly honest, I have no idea what the difference between the two methods are. Honestly, I prefer the method in this post because of how simple it is - however I'm guessing that this simplicity has the downside of being a bad programming practice?

  3. #3
    jim829 is online now Senior Member
    Join Date
    Jan 2013
    Location
    United States
    Posts
    3,388
    Rep Power
    5

    Default Re: Writing a text file

    I would say you need to flush the output buffer. Or do a close which should flush it for you before it closes the output buffer.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  4. #4
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,188
    Rep Power
    19

    Default Re: Writing a text file

    Learn to follow Java coding conventions: Code Conventions for the Java Programming Language: Contents

    Variable names should start with a lowercase letter.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  5. #5
    kkid is offline Senior Member
    Join Date
    Jul 2012
    Posts
    226
    Rep Power
    3

    Default Re: Writing a text file

    Quote Originally Posted by DarrylBurke View Post
    Learn to follow Java coding conventions: Code Conventions for the Java Programming Language: Contents

    Variable names should start with a lowercase letter.

    db
    I actually changed all of these about a minute or so after posting lol.
    I forget to do this sometimes, thanks anyway.

  6. #6
    jim829 is online now Senior Member
    Join Date
    Jan 2013
    Location
    United States
    Posts
    3,388
    Rep Power
    5

    Default Re: Writing a text file

    PrintWriter simply does the flushing for you with some modicum of control on your part. For large files, any output class that is buffered or can be buffered should be. Output is expensive relative to processing so making as few calls as possible to write the data to disk is preferable. In your case it may not matter all that much. But it is information you should be aware of.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  7. #7
    kkid is offline Senior Member
    Join Date
    Jul 2012
    Posts
    226
    Rep Power
    3

    Default Re: Writing a text file

    Quote Originally Posted by jim829 View Post
    I would say you need to flush the output buffer. Or do a close which should flush it for you before it closes the output buffer.

    Regards,
    Jim
    I added bw.flush() like so:

    Java Code:
    FileWriter fw = new FileWriter(textFile.getAbsoluteFile());
                        BufferedWriter bw = new BufferedWriter(fw);
                        bw.write(textArea.getText());
                        bw.flush();
    And it works great (For a single line, I haven't bothered to make it work with multiple lines yet, will do this soon). It seems identical in both methods now.

    I have no idea what this flush thing does though and all I really did was stick that code in anywhere hoping it would work and using trial and error really. What does it do, briefly and why did it stop the save working last time?

    EDIT: we posted at near enough the same time, Jim. Reading your second post now. I think it answers this post.

  8. #8
    gimbal2 is online now Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    3,697
    Rep Power
    5

    Default Re: Writing a text file

    Imagine your sink. You plug it so it fills up with water. You effectively "buffered" the water so you have one large amount of it in one place. Then you take out the plug so the water FLUSHES down the drain to its final destination.

    Get it?
    kkid likes this.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  9. #9
    jim829 is online now Senior Member
    Join Date
    Jan 2013
    Location
    United States
    Posts
    3,388
    Rep Power
    5

    Default Re: Writing a text file

    Quote Originally Posted by kkid View Post
    And it works great (For a single line, I haven't bothered to make it work with multiple lines yet, will do this soon)..
    You don't need to take any action on your part for multiple lines. You can make as many calls to write() as you want. When the internal buffer fills up, it will be flushed internally to the class. The only time you need to do it is when you finish with the file. In your case, just closing the file will write any remaining data out to disk.

    Note: that if you were to flush the contents of the buffer after the user typed each line you would be defeating the purpose of using a buffer in the first place.

    Regards,
    Jim
    kkid likes this.
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  10. #10
    kkid is offline Senior Member
    Join Date
    Jul 2012
    Posts
    226
    Rep Power
    3

    Default Re: Writing a text file

    Oh, I think I get it now. So what is happening is that the file is not getting written to line-by-line?

    The text (water) in my textArea (The tap) is being read and stored in a buffer (The sink).

    Once the entire textArea has been read this is when the buffer is as full as it needs to be and flushing (pulling the plug) will write it all at once to the file (the drain).




    Is this all related to performance then, without a buffer there would be a lot of work reading and writing as it goes along - just like it is easier to carry everything you need in your car on a journey rather than going back multiple times to pick things up and having a half-empty car on each trip?


    (So many analogies lol)



    Is this why originally I was using the buffered writer yet nothing was happening?
    I was merely filling up the buffer but then not flushing it at the end to have the buffer written tot he file?
    The text was essentially just kept in storage.

  11. #11
    kkid is offline Senior Member
    Join Date
    Jul 2012
    Posts
    226
    Rep Power
    3

    Default Re: Writing a text file

    To get a multiple line output, do I need to manually add \n into the string that is read from getText()?

    Does getText() ignore all line breaks added in via the ENTER button in a JTextArea?

  12. #12
    ras_oscar is offline Member
    Join Date
    Jun 2013
    Posts
    55
    Rep Power
    0

    Default Re: Writing a text file

    Also the reason you need to" close" a memory stick before pulling it fro hte computer. The OS ( I believe) controls when the buffer actually gets written to the storage medium. Closing it forces the flush and ensures what you asked was actually done. As stated above, input output operations are resource intensive.

  13. #13
    kkid is offline Senior Member
    Join Date
    Jul 2012
    Posts
    226
    Rep Power
    3

    Default Re: Writing a text file

    Am I right in using a JTextArea?

    I want it to be like notepad so the reason I chose a JTextArea over a JTextPane was that I didn't want much formatting. However, I cannot find a way of saving the lines written. Whatever I do, it saves as one continuous line in the output file.

    It is as if it completely ignores the "\n"s that are placed by pressing spacebar. Does JTextPane keep in the "\n"s when getting the text from the component?

  14. #14
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,188
    Rep Power
    19

    Default Re: Writing a text file

    Quote Originally Posted by kkid View Post
    ... the "\n"s that are placed by pressing spacebar.
    Huh?

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  15. #15
    kkid is offline Senior Member
    Join Date
    Jul 2012
    Posts
    226
    Rep Power
    3

    Default Re: Writing a text file

    Quote Originally Posted by DarrylBurke View Post
    Huh?

    db
    Enter*

  16. #16
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,188
    Rep Power
    19

    Default Re: Writing a text file

    JTextArea has a write(...) method inherited from JTextComponent.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  17. #17
    kkid is offline Senior Member
    Join Date
    Jul 2012
    Posts
    226
    Rep Power
    3

    Default Re: Writing a text file

    Quote Originally Posted by DarrylBurke View Post
    JTextArea has a write(...) method inherited from JTextComponent.

    db
    Works perfectly, thank you. I was expecting to have had to write line by line using a while loop which would have been annoying. Why have I seen this done in example work when this method is far easier?


    This is my final code for the save function, have I made iny major mistakes?

    Java Code:
    JMenuItem save = new JMenuItem("Save (FileWriter)");
            file.add(save);
            save.addActionListener(new ActionListener(){
                @Override
                public void actionPerformed(ActionEvent e) {
                    try{
                        File textFile = new File("C:/Users/Mike/Desktop/JavaNotepadOutput.txt");
                        if (textFile.exists() == false) {
                            textFile.createNewFile();
                        }
                        
                        FileWriter fw = new FileWriter(textFile.getAbsoluteFile());
                        BufferedWriter bw = new BufferedWriter(fw);
                        textArea.write(bw);
                        bw.flush();
                    }
                    
                    catch (IOException IOException){
                        IOException.printStackTrace();
                    }
                    }
                });
    DarrylBurke likes this.

  18. #18
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,188
    Rep Power
    19

    Default Re: Writing a text file

    Quote Originally Posted by kkid View Post
    Java Code:
                        // if (textFile.exists() == false) {
                        if (!textFile.exists()) {
    It's unnecessary to compare boolean values to boolean literals. It can also be error prone.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  19. #19
    gimbal2 is online now Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    3,697
    Rep Power
    5

    Default Re: Writing a text file

    Why have I seen this done in example work when this method is far easier?
    Plenty of code is the result of trial & error rather than research and understanding; the internet is full of it. That's why it is better to work towards understanding things so you can produce the code yourself or verify code you find, rather than relying on code you find on the net to be correct.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

Similar Threads

  1. Replies: 8
    Last Post: 07-17-2011, 02:38 PM
  2. Writing Text To A File
    By loopsnhoops in forum New To Java
    Replies: 15
    Last Post: 06-01-2011, 03:27 AM
  3. Writing into a text file
    By africanhacker in forum New To Java
    Replies: 3
    Last Post: 03-31-2011, 10:44 PM
  4. Replies: 1
    Last Post: 02-27-2010, 01:29 AM
  5. writing text to file
    By notwist in forum New To Java
    Replies: 3
    Last Post: 04-25-2008, 04:20 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •