Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner; // for user input
- import java.io.*; // for File handling
- public class CountUpdater {
- /**
- * Program: CountUpdater.java
- * Purpose: First run: save data.
- * Subsequent runs: recall data from disk; update; save new data.
- * Creator: Chris Clarke
- * Created: 14.12.2013
- */
- public static void main(String[] args) {
- // where to save your text file
- String filename = "file.txt";
- File f = new File(filename);
- String strTimesMade="";
- int count = 0;
- if ( !f.exists()) {
- saveText( filename, "1"); // create new text file
- } else {
- strTimesMade = getText( filename); // recall text
- count = Integer.parseInt( strTimesMade); // convert to int
- } // end if
- System.out.println("count = "+ ++count);
- strTimesMade = "" +count; // convert to String
- saveText( filename, strTimesMade); // save new text
- } // end main()
- public static void saveText(String filename, String text) {
- Writer writer = null;
- try {
- File file = new File(filename);
- writer = new BufferedWriter(new FileWriter(file));
- writer.write(text);
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- if (writer != null) {
- writer.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- } // end saveText()
- public static String getText(String filename) {
- File file = new File(filename);
- StringBuffer contents = new StringBuffer();
- BufferedReader reader = null;
- try {
- reader = new BufferedReader(new FileReader(file));
- String text = null;
- // repeat until all lines are read
- while ((text = reader.readLine()) != null) {
- contents.append(text);
- }
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- if (reader != null) {
- reader.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- // show file contents here
- //System.out.println(contents.toString());
- return contents.toString();
- } // end recallText()
- } // end CountUpdater
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement