HELP On Reading and Writing into a file


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 2 of 2

Thread: HELP On Reading and Writing into a file

  1. #1
    Join Date
    Feb 2005
    Location
    USA
    Posts
    3

    Question HELP On Reading and Writing into a file

    HeY Fellow Programmers..

    I was wondering if anyone can help me with this java problem I have. It's about how to read to the end of a txt file and insert a line of text like "Hello World!"

    Thanks

  2. #2
    Join Date
    Dec 2004
    Posts
    34
    This is a sample code to append a string to the end of a file:

    --------------------------------------

    import java.io.*;

    public class TextWriter {

    public static void main(String[] args) {
    String textToAppend = "Hello World";
    File file = new File("C:\\folder\\file.txt"); // Note the double slashes (for windows-like folder separators only)
    try {
    // I put everything inside a try block to make it shorter
    Writer writer = new BufferedWriter(new FileWriter(file, true)); // this true means 'append'
    writer.write(textToAppend, 0, textToAppend.length()); // since we're already appending, the offset is zero
    writer.close();
    } catch (IOException e) {
    }
    }
    }

    --------------------------------------

    If the file doesn't exist it will be created.
    It's HORRIBLY written, but it can help so you get the point.

    Basically all you need is in the java.io API. It's confusing in the beginning, but after some tests you get the basics.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center