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 IcedTea {
- /**
- * Program: IcedTea.java
- * Purpose: First run: save data.
- * Subsequent runs: recall data from disk; update; save new data.
- * Creator: Chris Clarke
- * Created: 11.07.2013
- */
- public static void main(String[] args) {
- // where to save your text file
- File tempDir=new File( File.separator+"temp");
- if (!tempDir.exists()) tempDir.mkdir(); // create new directory
- String filename = File.separator+"temp"+File.separator+"IcedTeaTextFile.txt";
- String strTimesMade="";
- int timesMade = 0;
- Scanner scan = new Scanner (System.in);
- System.out.print("Are you running this program for the first time? ");
- String firstTime = scan.nextLine();
- if (firstTime.toLowerCase().startsWith("y")) {
- saveText( filename, strTimesMade); // create new text file
- } else {
- strTimesMade = readText( filename); // read text from file
- timesMade = Integer.parseInt(strTimesMade); // convert to int
- }
- System.out.println("Hi! You've made iced tea "+timesMade+" times so far since 05.10.14.");
- System.out.println("Please enter a number to add to the current number\n"
- +"of times you've made iced tea.");
- int number = scan.nextInt();
- timesMade += number;
- System.out.println("Thanks. You've now made iced tea "+timesMade+" times so far since 05.10.14.");
- strTimesMade = "" +timesMade; // convert to String
- saveText( filename, strTimesMade); // save new text
- System.out.println("Now run this program again.");
- } // 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 readText(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 readText()
- } // end IcedTea
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement