Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*; // for file input/output
- import java.util.*; // for Scanner
- public class InstantFile {
- /**
- * Program: InstantFile.java
- * Purpose: Type in text and save it to C:\temp as .txt notepad file
- * Creator: Chris Clarke
- * Created: 27-31.12.2012
- * Usage : Type "java InstantFile <directory>"
- * to make a new directory, or locate an existing directory.
- * Otherwise saves to C:\temp.
- */
- public static void main(String[] args) throws Exception {
- String saveDir = "temp";
- // creates new directory or opens an existing one.
- // name can be supplied as command line argument
- if (args.length > 0) saveDir = args[0];
- File theDir = new File(File.separator+saveDir);
- // if directory doesn't exist, make it
- if (!theDir.exists()) theDir.mkdir();
- String fileName; // doesn't include path
- Scanner scan = new Scanner (System.in);
- System.out.println("Create new file");
- System.out.println("Enter file name to Save As: ");
- fileName = scan.nextLine();
- if (!fileName.endsWith(".txt")) fileName += ".txt"; // append extension
- File theFile = new File(theDir + File.separator + fileName);
- if (theFile.exists()) {
- System.out.print("File "+theFile+" exists. Overwrite (y/n)? ");
- String ans = scan.nextLine();
- if (!ans.toLowerCase().startsWith("y")) {
- System.out.println("Exiting program...");
- System.exit(0);
- }// end if
- }// end if
- PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter (theFile)));
- String theString = "";
- System.out.println("Enter lines of text [exit: type \'x\' on a new line]");
- do {
- theString = scan.nextLine(); // reads line of text from keybd
- if (!theString.equalsIgnoreCase("x")) {
- out.println(theString); // outputs one line at a time
- }// end if
- } while (!theString.equalsIgnoreCase("x"));
- out.close();
- System.out.println("File "+theFile+" saved.");
- }// end main
- }// end class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement