Advertisement
brilliant_moves

InstantFile.java

Jan 18th, 2013
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.92 KB | None | 0 0
  1. import java.io.*;   // for file input/output
  2. import java.util.*; // for Scanner
  3.  
  4. public class InstantFile {
  5.  
  6.     /**
  7.     *   Program:    InstantFile.java
  8.     *   Purpose:    Type in text and save it to C:\temp as .txt notepad file
  9.     *   Creator:    Chris Clarke
  10.     *   Created:    27-31.12.2012
  11.     *   Usage  :    Type "java InstantFile <directory>"
  12.     *            to make a new directory, or locate an existing directory.
  13.     *            Otherwise saves to C:\temp.
  14.     */
  15.  
  16.     public static void main(String[] args) throws Exception {
  17.         String saveDir = "temp";
  18.  
  19.         // creates new directory or opens an existing one.
  20.         // name can be supplied as command line argument
  21.         if (args.length > 0) saveDir = args[0];
  22.  
  23.         File theDir = new File(File.separator+saveDir);
  24.  
  25.         // if directory doesn't exist, make it
  26.         if (!theDir.exists()) theDir.mkdir();
  27.  
  28.         String fileName; // doesn't include path
  29.         Scanner scan = new Scanner (System.in);
  30.  
  31.         System.out.println("Create new file");
  32.         System.out.println("Enter file name to Save As: ");
  33.         fileName = scan.nextLine();
  34.  
  35.         if (!fileName.endsWith(".txt")) fileName += ".txt"; // append extension
  36.  
  37.         File theFile = new File(theDir + File.separator + fileName);
  38.  
  39.         if (theFile.exists()) {
  40.             System.out.print("File "+theFile+" exists. Overwrite (y/n)? ");
  41.             String ans = scan.nextLine();
  42.             if (!ans.toLowerCase().startsWith("y")) {
  43.                 System.out.println("Exiting program...");
  44.                 System.exit(0);
  45.             }// end if
  46.         }// end if
  47.  
  48.         PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter (theFile)));
  49.         String theString = "";
  50.         System.out.println("Enter lines of text [exit: type \'x\' on a new line]");
  51.         do {
  52.             theString = scan.nextLine(); // reads line of text from keybd
  53.             if (!theString.equalsIgnoreCase("x")) {
  54.                 out.println(theString); // outputs one line at a time
  55.             }// end if
  56.         } while (!theString.equalsIgnoreCase("x"));
  57.  
  58.         out.close();
  59.         System.out.println("File "+theFile+" saved.");
  60.     }// end main
  61. }// end class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement