DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

+ Reply to Thread
Results 1 to 2 of 2
  1. #1
    Join Date
    Feb 2005
    Posts
    24

    Question Either Overwrite or Rename file

    Coding Style: NetBeans IDE 4.0 Beta2 (Java)

    My goal is to edit a Text File (and I am having a real hard time).
    So far the only solution I have found is to OPEN the current Text File (FileReader to Chatter.txt) and create a new Text File (FileWriter to oChatter.txt), .readline all the lines that do not need changing (Catch the ones I do and edit them) and write
    each line into the new text file (as shown in the code below)

    [CODE]
    String incomming = "";

    File fSourceStore = new File("Chatter.txt");
    File fDestStore = new File("oChatter.txt");
    FileReader frStore = new FileReader(fSourceStore);
    FileWriter fwStore = new FileWriter(fDestStore);
    BufferedReader brStore = new BufferedReader(frStore);
    BufferedWriter bwStore = new BufferedWriter(fwStore);

    boolean bSearch = true;
    while (bSearch == true)
    {
    incomming = brStore.readLine();
    if (incomming == null)
    {
    // End of File
    bwStore.close();
    brStore.close();
    frStore.close();
    fwStore.close();
    bSearch = false;
    }
    else if (DETERMINE IF THIS LINE NEEDS TO BE EDITED)
    {
    // EDIT THE LINE //
    bwStore.write(newLine);
    bwStore.newLine();
    }
    else
    {
    // Keep information in file
    bwStore.write(incomming);
    bwStore.newLine();
    }
    }
    [CODE]

    Now this works good except that I can't seem to find a way (afterwards) to DELETE the old Chatter.txt and rename the new oChatter.txt -> Chatter.txt
    Also, isn't there a way to OVERWRITE or MODIFY the file and not have to create/rename a TEMP file (oChatter.txt) every time I want to make a slight change to the file?
    There has to be like a ReaderWriter or some .Overwrite or something?

    Any kind of help would be greatly appreciated.
    Thanks,

  2. #2
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560

    This is how to update safely

    Code:
    import java.io.*;
    import java.util.*;
    
    public class FileUpdater {
    
      private String filePath=null;
      public final static String BACKUP_PATH="c:\\tmp\\bcup.txt";
      //
      public FileUpdater(String filePath) {
        this.filePath=filePath;
      }
      public void updateFile () throws IOException {
        ArrayList recordList=new ArrayList();
    
        // get file buffer as an arraylist of records
        BufferedReader br=new BufferedReader(new FileReader(filePath));
        String line=null;
        while ((line=br.readLine())!=null) {
          recordList.add(line);
        }
        br.close();
    
        // scan file buffer's records and perform updates where required.
        // if no edit required then leave as is
        int edCount=0;
        for (int i=0; i<recordList.size(); i++) {
          String inLine=(String)recordList.get(i);
    
          /**
           * check edit conditions and return new line if edited
           */
          String newLine=checkForEdit(inLine);
    
          if (newLine!=null) {
            recordList.set(i,newLine); // replace line
            edCount++;
          }
        }
        System.out.println("\n\nIn file "+filePath+" "+
                           edCount+" lines of "+recordList.size()+" lines have been edited");
        /**
         * file buffer is prepared, backup the old version,  overwrite and exit
         */
        // backup
        br = new BufferedReader(new FileReader(filePath));
        BufferedWriter bw = new BufferedWriter(new FileWriter(BACKUP_PATH));
        while ( (line = br.readLine()) != null) {
          bw.write(line);
          bw.newLine();
        }
        br.close();
        bw.close();
        System.out.println("Backed up old version of " + filePath + " to " +
                           BACKUP_PATH);
        // store
        bw = new BufferedWriter(new FileWriter(filePath));
        for (int i = 0; i < recordList.size(); i++) {
          line = (String) recordList.get(i);
          bw.write(line);
          bw.newLine();
        }
        bw.close();
        System.out.println("Saved updates to: " + filePath + " records: " +
                           recordList.size());
    
      }
      /**
       * Stupid example but made just to have a runthrough
       * @param inLine
       * @return
       */
      private String checkForEdit (String inLine) {
        int pos=inLine.indexOf("text");
        if (pos > 0) {
          return inLine+" [text found at pos: "+pos+"]";
        } else {
          return null;
        }
    
      }
      
      /**
       * ************************ MAIN *********************
       * @param args
       */
      public static void main(String[] args) {
        FileUpdater fu = new FileUpdater("c:\\tmp\\test.txt");
        try {
          fu.updateFile();
          System.out.println("FileUpdater finished");
        }
        catch (IOException ex) {
          System.out.println("FileUpdater failed");
          ex.printStackTrace();
        }
      }
    
    }

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