Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie
Hi all,
Vanilla are planning an update to the site on April 24th (next Wednesday). It is a major PHP8 update which is expected to boost performance across the site. The site will be down from 7pm and it is expected to take about an hour to complete. We appreciate your patience during the update.
Thanks all.

(Java) Overwrite line in .txt file

  • 18-12-2013 3:38pm
    #1
    Registered Users Posts: 4,468 ✭✭✭


    Hi All.

    I'm trying to create a counter that will survive the program being closed and reopened.

    I need to start with a txt file that has one line in it with 2000 as the text

    On running the program, i need this to be overwritten with 1999.
    Running again will overwrite with 1998, etc etc.

    Any tips on how i could do this?

    CC.


Comments

  • Registered Users Posts: 2,815 ✭✭✭SimonTemplar


    I might be wrong but I know in other languages you can't simply change a part of a text file. You'll need to read the existing file and write it to a new file. You can include any logic to change the contents of a specific line while doing so. You can then delete the old file and rename the new file.

    Do you have to use a txt file. Could you not use XML. That means you can use an XML library to change the value without worrying about writing to new files like you do with txt.

    EDIT: I just noticed that the text file only contains one line. In that case, you can simply overwrite the existing file.
    Take a look at the FileWriter object, specifically the append parameter of the constructor:
    http://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html#FileWriter%28java.lang.String,%20boolean%29


  • Registered Users Posts: 4,468 ✭✭✭CruelCoin


    Hi Simon,

    My current attempt at the code is:

    Scanner questsLeft = new Scanner(new File("questionsRemaining.txt"));
    int q = questsLeft.nextInt();
    q--;
    JOptionPane.showMessageDialog(null, "The amount of questions you can still ask WolframAlpha before we reach the 2000 API calls limit is: " + q);
    questsLeft.close();

    I'm not sure on how to write the code using the example you gave me?


  • Registered Users Posts: 1,982 ✭✭✭lynchie


    Using commons.io
    String s = FileUtils.readFileToString(new File(....));
    int i = Integer.parseInt(s);
    i--;
    FileUtils.writeStringToFile(new File(...), String.valueOf(i));
    


  • Registered Users Posts: 2,781 ✭✭✭amen


    might be wrong but I know in other languages you can't simply change a part of a text file

    its been a while but I think you could use fseek in C to do this basically open a file and overwrite at a given location.
    Could you not use XML.

    but why add the overhead of using XML when you just want to open/write a simple txt file ?


  • Registered Users Posts: 2,021 ✭✭✭ChRoMe


    amen wrote: »



    but why add the overhead of using XML when you just want to open/write a simple txt file ?

    Agreed, the xml suggestion is bizarre.


  • Advertisement
  • Closed Accounts Posts: 8,016 ✭✭✭CreepingDeath


    Or you could use a property file
    package textfile;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.Properties;
    
    public class DecrementingCounter
    {
        final static String COUNTER_FILENAME="counter.properties";
        final static String USAGE_COUNTER_PROPERTY_KEY="usageCounter";
        final static int    DEFAULT_COUNTER_VALUE=2000;
        
        public static int decrementUsageCounter() throws FileNotFoundException, IOException
        {
            Properties counterProps = new Properties();
            
            // Step 1 : read the properties file
            File counterFile = new File("counter.properties");
            int usageCounterValue = DEFAULT_COUNTER_VALUE;
            
            if (counterFile.exists())
            {
                counterProps.load(new FileInputStream(counterFile));
                if (counterProps.containsKey(USAGE_COUNTER_PROPERTY_KEY))
                {
                    usageCounterValue = Integer.parseInt(counterProps.getProperty(USAGE_COUNTER_PROPERTY_KEY));
                }
            }
            
            // Step 2 : decrement the counter and write it back
            usageCounterValue--;        
            counterProps.put(USAGE_COUNTER_PROPERTY_KEY, Integer.toString(usageCounterValue));
            
            counterProps.store(new FileOutputStream(counterFile), "");
            
            return(usageCounterValue);
        }
        
        
        public static void main(String[] args)
        {
            try
            {
                int usageCounter = decrementUsageCounter();
                
                if (usageCounter<=0)
                {
                    System.out.println("Your demo trial has expired");
                }
                else
                {            
                    System.out.println("Usage Counter = " + usageCounter);
                }
            }
            catch (FileNotFoundException e)
            {
                e.printStackTrace();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
       
    }
    
    


  • Registered Users Posts: 2,815 ✭✭✭SimonTemplar


    ChRoMe wrote: »
    Agreed, the xml suggestion is bizarre.

    I assumed the data involved was some kind of config information, for which the XML format works well. I realised after I posted that it is much simplier than that. My misunderstanding.


  • Registered Users Posts: 2,815 ✭✭✭SimonTemplar


    amen wrote: »
    but why add the overhead of using XML when you just want to open/write a simple txt file ?

    I agree because I (quickly) misread the OP, but out of curiosity, does using XML add a significant overhead compared to a txt? I would have assumed the difference is negligable in terms of performace.


Advertisement