|
| 1 | +package com.brianway.learning.java.io; |
| 2 | +//: io/MakeDirectories.java |
| 3 | +// Demonstrates the use of the File class to |
| 4 | +// create directories and manipulate files. |
| 5 | +// {Args: MakeDirectoriesTest} |
| 6 | + |
| 7 | +import java.io.File; |
| 8 | + |
| 9 | +public class MakeDirectories { |
| 10 | + private static void usage() { |
| 11 | + System.err.println( |
| 12 | + "Usage:MakeDirectories path1 ...\n" + |
| 13 | + "Creates each path\n" + |
| 14 | + "Usage:MakeDirectories -d path1 ...\n" + |
| 15 | + "Deletes each path\n" + |
| 16 | + "Usage:MakeDirectories -r path1 path2\n" + |
| 17 | + "Renames from path1 to path2"); |
| 18 | + System.exit(1); |
| 19 | + } |
| 20 | + |
| 21 | + private static void fileData(File f) { |
| 22 | + System.out.println( |
| 23 | + "Absolute path: " + f.getAbsolutePath() + |
| 24 | + "\n Can read: " + f.canRead() + |
| 25 | + "\n Can write: " + f.canWrite() + |
| 26 | + "\n getName: " + f.getName() + |
| 27 | + "\n getParent: " + f.getParent() + |
| 28 | + "\n getPath: " + f.getPath() + |
| 29 | + "\n length: " + f.length() + |
| 30 | + "\n lastModified: " + f.lastModified()); |
| 31 | + if (f.isFile()) { |
| 32 | + System.out.println("It's a file"); |
| 33 | + } else if (f.isDirectory()) { |
| 34 | + System.out.println("It's a directory"); |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + public static void main(String[] args) { |
| 39 | + if (args.length < 1) usage(); |
| 40 | + if (args[0].equals("-r")) { |
| 41 | + if (args.length != 3) usage(); |
| 42 | + File |
| 43 | + old = new File(args[1]), |
| 44 | + rname = new File(args[2]); |
| 45 | + old.renameTo(rname); |
| 46 | + fileData(old); |
| 47 | + fileData(rname); |
| 48 | + return; // Exit main |
| 49 | + } |
| 50 | + int count = 0; |
| 51 | + boolean del = false; |
| 52 | + if (args[0].equals("-d")) { |
| 53 | + count++; |
| 54 | + del = true; |
| 55 | + } |
| 56 | + count--; |
| 57 | + while (++count < args.length) { |
| 58 | + File f = new File(args[count]); |
| 59 | + if (f.exists()) { |
| 60 | + System.out.println(f + " exists"); |
| 61 | + if (del) { |
| 62 | + System.out.println("deleting..." + f); |
| 63 | + f.delete(); |
| 64 | + } |
| 65 | + } else { // Doesn't exist |
| 66 | + if (!del) { |
| 67 | + f.mkdirs(); |
| 68 | + System.out.println("created " + f); |
| 69 | + } |
| 70 | + } |
| 71 | + fileData(f); |
| 72 | + } |
| 73 | + } |
| 74 | +} |
| 75 | +/* Output: (80% match) |
| 76 | +created MakeDirectoriesTest |
| 77 | +Absolute path: d:\aaa-TIJ4\code\io\MakeDirectoriesTest |
| 78 | + Can read: true |
| 79 | + Can write: true |
| 80 | + getName: MakeDirectoriesTest |
| 81 | + getParent: null |
| 82 | + getPath: MakeDirectoriesTest |
| 83 | + length: 0 |
| 84 | + lastModified: 1101690308831 |
| 85 | +It's a directory |
| 86 | +*///:~ |
0 commit comments