DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

+ Reply to Thread
Results 1 to 2 of 2
  1. #1
    Join Date
    Oct 2004
    Posts
    15

    text file to string and back to file again

    i need to read a text file to a string. Add a line to the string and then output back to the text file.

    The text file is a list of strings:

    eg:
    this is a test
    this is a second test
    this is what i need to add to the file

    Please help.

    I can read a single line from a text file to a string but i cant make it search through the whole text file!!

  2. #2
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560
    like this
    Code:
    import java.io.*;
    public class FileStuff  {
      String filePath=null;
      public FileStuff() {}
      public void setFile(String filePath) {
        this.filePath=filePath;
      }
      public void addLine(String aLine) {
        StringBuffer sb=new StringBuffer();
        try {
          BufferedReader br=new BufferedReader(new FileReader(filePath));
          String line=null;
          while ((line=br.readLine())!=null) {
            sb.append(line).append("\n");
          }
          br.close();
          sb.append(aLine);
          FileOutputStream fOut=new FileOutputStream(filePath);
          fOut.write(sb.toString().getBytes());
          fOut.close();
        } catch (IOException ioe) {
          System.err.println("File append for: ["+filePath+"] failed");
        }
      }
    
      public static void main(String[] args) {
         FileStuff fs=new FileStuff();
         fs.setFile("c:\\somefile.txt");
         fs.addLine("this is what i need to add to the file");
      }
    }
    eschew obfuscation

Bookmarks

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


Top DevX Stories

Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL


Sponsored Links