Java/File Input Output/File Commands

Материал из Java эксперт
Версия от 18:01, 31 мая 2010; (обсуждение)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

BGrep: a regular expression search utility, like Unix grep

   
/*
 * Copyright (c) 2004 David Flanagan.  All rights reserved.
 * This code is from the book Java Examples in a Nutshell, 3nd Edition.
 * It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
 * You may study, use, and modify it for any non-commercial purpose,
 * including teaching and use in open-source projects.
 * You may distribute it non-commercially as long as you retain this notice.
 * For a commercial use license, or to purchase the book, 
 * please visit http://www.davidflanagan.ru/javaexamples3.
 */
//package je3.nio;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
/**
 * BGrep: a regular expression search utility, like Unix grep, but
 * block-oriented instead of line-oriented. For any match found, the filename
 * and character position within the file (note: not the line number) are
 * printed along with the text that matched.
 * 
 * Usage: java je3.nio.BGrep [options] <pattern> <files>...
 * 
 * Options: -e <encoding> specifies and encoding. UTF-8 is the default -i
 * enables case-insensitive matching. Use -s also for non-ASCII text -s enables
 * strict (but slower) processing of non-ASCII characters
 * 
 * This program requires that each file to be searched fits into main memory,
 * and so does not work with extremely large files.
 */
public class BGrep {
  public static void main(String[] args) {
    String encodingName = "UTF-8"; // Default to UTF-8 encoding
    int flags = Pattern.MULTILINE; // Default regexp flags
    try { // Fatal exceptions are handled after this try block
      // First, process any options
      int nextarg = 0;
      while (args[nextarg].charAt(0) == "-") {
        String option = args[nextarg++];
        if (option.equals("-e")) {
          encodingName = args[nextarg++];
        } else if (option.equals("-i")) { // case-insensitive matching
          flags |= Pattern.CASE_INSENSITIVE;
        } else if (option.equals("-s")) { // Strict Unicode processing
          flags |= Pattern.UNICODE_CASE; // case-insensitive Unicode
          flags |= Pattern.CANON_EQ; // canonicalize Unicode
        } else {
          System.err.println("Unknown option: " + option);
          usage();
        }
      }
      // Get the Charset for converting bytes to chars
      Charset charset = Charset.forName(encodingName);
      // Next argument must be a regexp. Compile it to a Pattern object
      Pattern pattern = Pattern.rupile(args[nextarg++], flags);
      // Require that at least one file is specified
      if (nextarg == args.length)
        usage();
      // Loop through each of the specified filenames
      while (nextarg < args.length) {
        String filename = args[nextarg++];
        CharBuffer chars; // This will hold complete text of the file
        try { // Handle per-file errors locally
          // Open a FileChannel to the named file
          FileInputStream stream = new FileInputStream(filename);
          FileChannel f = stream.getChannel();
          // Memory-map the file into one big ByteBuffer. This is
          // easy but may be somewhat inefficient for short files.
          ByteBuffer bytes = f.map(FileChannel.MapMode.READ_ONLY, 0, f.size());
          // We can close the file once it is is mapped into memory.
          // Closing the stream closes the channel, too.
          stream.close();
          // Decode the entire ByteBuffer into one big CharBuffer
          chars = charset.decode(bytes);
        } catch (IOException e) { // File not found or other problem
          System.err.println(e); // Print error message
          continue; // and move on to the next file
        }
        // This is the basic regexp loop for finding all matches in a
        // CharSequence. Note that CharBuffer implements CharSequence.
        // A Matcher holds state for a given Pattern and text.
        Matcher matcher = pattern.matcher(chars);
        while (matcher.find()) { // While there are more matches
          // Print out details of the match
          System.out.println(filename + ":" + // file name
              matcher.start() + ": " + // character pos
              matcher.group()); // matching text
        }
      }
    }
    // These are the things that can go wrong in the code above
    catch (UnsupportedCharsetException e) { // Bad encoding name
      System.err.println("Unknown encoding: " + encodingName);
    } catch (PatternSyntaxException e) { // Bad pattern
      System.err.println("Syntax error in search pattern:\n" + e.getMessage());
    } catch (ArrayIndexOutOfBoundsException e) { // Wrong number of arguments
      usage();
    }
  }
  /** A utility method to display invocation syntax and exit. */
  public static void usage() {
    System.err.println("Usage: java BGrep [-e <encoding>] [-i] [-s]" + " <pattern> <filename>...");
    System.exit(1);
  }
}





Compress files using the Java ZIP API

   
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class Compress {
  public static void gzipFile(String from, String to) throws IOException {
    FileInputStream in = new FileInputStream(from);
    GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(to));
    byte[] buffer = new byte[4096];
    int bytesRead;
    while ((bytesRead = in.read(buffer)) != -1)
      out.write(buffer, 0, bytesRead);
    in.close();
    out.close();
  }
  /** Zip the contents of the directory, and save it in the zipfile */
  public static void zipDirectory(String dir, String zipfile)
      throws IOException, IllegalArgumentException {
    // Check that the directory is a directory, and get its contents
    File d = new File(dir);
    if (!d.isDirectory())
      throw new IllegalArgumentException("Not a directory:  "
          + dir);
    String[] entries = d.list();
    byte[] buffer = new byte[4096]; // Create a buffer for copying
    int bytesRead;
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));
    for (int i = 0; i < entries.length; i++) {
      File f = new File(d, entries[i]);
      if (f.isDirectory())
        continue;//Ignore directory
      FileInputStream in = new FileInputStream(f); // Stream to read file
      ZipEntry entry = new ZipEntry(f.getPath()); // Make a ZipEntry
      out.putNextEntry(entry); // Store entry
      while ((bytesRead = in.read(buffer)) != -1)
        out.write(buffer, 0, bytesRead);
      in.close(); 
    }
    out.close();
  }
  public static void main(String args[]) throws IOException {
    String from = ".";
    File f = new File(from);
    boolean directory = f.isDirectory(); // Is it a file or directory?
    Compress.zipDirectory(from, from + ".zip");
    Compress.gzipFile(from, from + ".gz");
  }
}





Copy files using Java IO API

   
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class FileCopy {
  public static void main(String[] args) {
    try {
      copy("fromFile.txt", "toFile.txt");
    } catch (IOException e) {
      System.err.println(e.getMessage());
    }
  }
  public static void copy(String fromFileName, String toFileName)
      throws IOException {
    File fromFile = new File(fromFileName);
    File toFile = new File(toFileName);
    if (!fromFile.exists())
      throw new IOException("FileCopy: " + "no such source file: "
          + fromFileName);
    if (!fromFile.isFile())
      throw new IOException("FileCopy: " + "can"t copy directory: "
          + fromFileName);
    if (!fromFile.canRead())
      throw new IOException("FileCopy: " + "source file is unreadable: "
          + fromFileName);
    if (toFile.isDirectory())
      toFile = new File(toFile, fromFile.getName());
    if (toFile.exists()) {
      if (!toFile.canWrite())
        throw new IOException("FileCopy: "
            + "destination file is unwriteable: " + toFileName);
      System.out.print("Overwrite existing file " + toFile.getName()
          + "? (Y/N): ");
      System.out.flush();
      BufferedReader in = new BufferedReader(new InputStreamReader(
          System.in));
      String response = in.readLine();
      if (!response.equals("Y") && !response.equals("y"))
        throw new IOException("FileCopy: "
            + "existing file was not overwritten.");
    } else {
      String parent = toFile.getParent();
      if (parent == null)
        parent = System.getProperty("user.dir");
      File dir = new File(parent);
      if (!dir.exists())
        throw new IOException("FileCopy: "
            + "destination directory doesn"t exist: " + parent);
      if (dir.isFile())
        throw new IOException("FileCopy: "
            + "destination is not a directory: " + parent);
      if (!dir.canWrite())
        throw new IOException("FileCopy: "
            + "destination directory is unwriteable: " + parent);
    }
    FileInputStream from = null;
    FileOutputStream to = null;
    try {
      from = new FileInputStream(fromFile);
      to = new FileOutputStream(toFile);
      byte[] buffer = new byte[4096];
      int bytesRead;
      while ((bytesRead = from.read(buffer)) != -1)
        to.write(buffer, 0, bytesRead); // write
    } finally {
      if (from != null)
        try {
          from.close();
        } catch (IOException e) {
          ;
        }
      if (to != null)
        try {
          to.close();
        } catch (IOException e) {
          ;
        }
    }
  }
}





Copying a file using channels and buffers

   
// : c12:ChannelCopy.java
// Copying a file using channels and buffers
// {Args: ChannelCopy.java test.txt}
// {Clean: test.txt}
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class ChannelCopy {
  private static final int BSIZE = 1024;
  public static void main(String[] args) throws Exception {
    if (args.length != 2) {
      System.out.println("arguments: sourcefile destfile");
      System.exit(1);
    }
    FileChannel in = new FileInputStream(args[0]).getChannel(), out = new FileOutputStream(
        args[1]).getChannel();
    ByteBuffer buffer = ByteBuffer.allocate(BSIZE);
    while (in.read(buffer) != -1) {
      buffer.flip(); // Prepare for writing
      out.write(buffer);
      buffer.clear(); // Prepare for reading
    }
  }
} ///:~





Count chars in a File

   
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
 * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *
 * -Redistribution in binary form must reproduce the above copyright notice,
 *  this list of conditions and the following disclaimer in the documentation
 *  and/or other materials provided with the distribution.
 *
 * Neither the name of Sun Microsystems, Inc. or the names of contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class Count {
  public static void countChars(InputStream in) throws IOException {
    int count = 0;
    while (in.read() != -1)
      count++;
    System.out.println("Counted " + count + " chars.");
  }
  public static void main(String[] args) throws Exception {
    if (args.length >= 1)
      countChars(new FileInputStream(args[0]));
    else
      System.err.println("Usage: Count filename");
  }
}





Counts words in a file, outputs results in sorted form

   
// : c12:WordCount.java
// Counts words in a file, outputs results in sorted form.
// {Args: WordCount.java}
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.StreamTokenizer;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;
class Counter {
  private int i = 1;
  public int read() {
    return i;
  }
  public void increment() {
    i++;
  }
}
public class WordCount1 {
  private static final String usage = "Usage: \nWordCount file\n"
      + "Counts the words in the file and "
      + "outputs results in sorted form.";
  private FileReader file;
  private StreamTokenizer st;
  // A TreeMap keeps keys in sorted order:
  private TreeMap counts = new TreeMap();
  public WordCount1(String filename) throws FileNotFoundException {
    try {
      file = new FileReader(filename);
      st = new StreamTokenizer(new BufferedReader(file));
      st.ordinaryChar(".");
      st.ordinaryChar("-");
    } catch (FileNotFoundException e) {
      throw new RuntimeException(e);
    }
  }
  public void dispose() {
    try {
      file.close();
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
  public void countWords() {
    try {
      while (st.nextToken() != StreamTokenizer.TT_EOF) {
        String s;
        switch (st.ttype) {
        case StreamTokenizer.TT_EOL:
          s = new String("EOL");
          break;
        case StreamTokenizer.TT_NUMBER:
          s = Double.toString(st.nval);
          break;
        case StreamTokenizer.TT_WORD:
          s = st.sval; // Already a String
          break;
        default: // single character in ttype
          s = String.valueOf((char) st.ttype);
        }
        if (counts.containsKey(s))
          ((Counter) counts.get(s)).increment();
        else
          counts.put(s, new Counter());
      }
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
  public Collection values() {
    return counts.values();
  }
  public Set keySet() {
    return counts.keySet();
  }
  public Counter getCounter(String s) {
    return (Counter) counts.get(s);
  }
  public static void main(String[] args) throws FileNotFoundException {
    if (args.length == 0) {
      System.out.println(usage);
      System.exit(1);
    }
    WordCount1 wc = new WordCount1(args[0]);
    wc.countWords();
    Iterator keys = wc.keySet().iterator();
    while (keys.hasNext()) {
      String key = (String) keys.next();
      System.out.println(key + ": " + wc.getCounter(key).read());
    }
    wc.dispose();
  }
} ///:~





Delete a file from within Java, with error handling

   
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
import java.io.File;
/**
 * Delete a file from within Java, with error handling.
 * 
 * @author Ian F. Darwin, http://www.darwinsys.ru/
 * @version $Id: Delete2.java,v 1.5 2004/02/09 03:33:47 ian Exp $
 */
public class Delete2 {
  public static void main(String[] argv) {
    for (int i = 0; i < argv.length; i++)
      delete(argv[i]);
  }
  public static void delete(String fileName) {
    try {
      // Construct a File object for the file to be deleted.
      File target = new File(fileName);
      if (!target.exists()) {
        System.err.println("File " + fileName
            + " not present to begin with!");
        return;
      }
      // Quick, now, delete it immediately:
      if (target.delete())
        System.err.println("** Deleted " + fileName + " **");
      else
        System.err.println("Failed to delete " + fileName);
    } catch (SecurityException e) {
      System.err.println("Unable to delete " + fileName + "("
          + e.getMessage() + ")");
    }
  }
}





Delete file using Java IO API

   
import java.io.File;
public class Delete {
  public static void main(String[] args) {
    String fileName = "file.txt";
    // A File object to represent the filename
    File f = new File(fileName);
    // Make sure the file or directory exists and isn"t write protected
    if (!f.exists())
      throw new IllegalArgumentException(
          "Delete: no such file or directory: " + fileName);
    if (!f.canWrite())
      throw new IllegalArgumentException("Delete: write protected: "
          + fileName);
    // If it is a directory, make sure it is empty
    if (f.isDirectory()) {
      String[] files = f.list();
      if (files.length > 0)
        throw new IllegalArgumentException(
            "Delete: directory not empty: " + fileName);
    }
    // Attempt to delete it
    boolean success = f.delete();
    if (!success)
      throw new IllegalArgumentException("Delete: deletion failed");
  }
}





Diff: text file difference utility.

   
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
// Diff -- text file difference utility.
// See full docu-comment at beginning of Diff class.
// $Id: Diff.java,v 1.6 2004/02/09 03:34:05 ian Exp $
import java.io.*;
/** This is the info kept per-file.     */
class fileInfo {    
  static final int MAXLINECOUNT = 20000;
  DataInputStream file;  /* File handle that is open for read.  */
  public int maxLine;  /* After input done, # lines in file.  */
  node symbol[]; /* The symtab handle of each line. */
  int other[]; /* Map of line# to line# in other file */
                                /* ( -1 means don"t-know ).            */
        /* Allocated AFTER the lines are read. */
  /**
   * Normal constructor with one filename; file is opened and saved.
   */
  fileInfo( String filename ) {
    symbol = new node [ MAXLINECOUNT+2 ];
    other  = null;    // allocated later!
    try {
      file = new DataInputStream(
        new FileInputStream( filename));
    } catch (IOException e) {
        System.err.println("Diff can"t read file " +
        filename );
        System.err.println("Error Exception was:" + e );
        System.exit(1);
    }
  }
  // This is done late, to be same size as # lines in input file.
  void alloc() {
    other  = new int[symbol.length + 2];
  }
};
/**
 * diff         Text file difference utility.
 * ----         Copyright 1987, 1989 by Donald C. Lindsay,
 *              School of Computer Science,  Carnegie Mellon University.
 *              Copyright 1982 by Symbionics.
 *              Use without fee is permitted when not for direct commercial
 *              advantage, and when credit to the source is given. Other uses
 *              require specific permission.
 *
 * Converted from C to Java by Ian F. Darwin, http://www.darwinsys.ru/, January, 1997.
 * Copyright 1997, Ian F. Darwin.
 *
 * Conversion is NOT FULLY TESTED.
 *
 * USAGE:      diff oldfile newfile
 *
 * This program assumes that "oldfile" and "newfile" are text files.
 * The program writes to stdout a description of the changes which would
 * transform "oldfile" into "newfile".
 *
 * The printout is in the form of commands, each followed by a block of
 * text. The text is delimited by the commands, which are:
 *
 *    DELETE AT n
 *         ..deleted lines
 *
 *    INSERT BEFORE n
 *         ..inserted lines
 *
 *    n MOVED TO BEFORE n
 *         ..moved lines
 *
 *    n CHANGED FROM
 *         ..old lines
 *    CHANGED TO
 *         ..newer lines
 *
 * The line numbers all refer to the lines of the oldfile, as they are
 *    numbered before any commands are applied.
 * The text lines are printed as-is, without indentation or prefixing. The
 *    commands are printed in upper case, with a prefix of ">>>>", so that
 *    they will stand out. Other schemes may be preferred.
 * Files which contain more than MAXLINECOUNT lines cannot be processed.
 *    This can be fixed by changing "symbol" to a Vector.
 * The algorithm is taken from Communications of the ACM, Apr78 (21, 4, 264-),
 *    "A Technique for Isolating Differences Between Files."
 *    Ignoring I/O, and ignoring the symbol table, it should take O(N) time.
 *    This implementation takes fixed space, plus O(U) space for the symbol
 *    table (where U is the number of unique lines). Methods exist to change
 *    the fixed space to O(N) space.
 * Note that this is not the only interesting file-difference algorithm. In
 *    general, different algorithms draw different conclusions about the
 *    changes that have been made to the oldfile. This algorithm is sometimes
 *    "more right", particularly since it does not consider a block move to be 
 *    an insertion and a (separate) deletion. However, on some files it will be
 *    "less right". This is a consequence of the fact that files may contain
 *    many identical lines (particularly if they are program source). Each
 *    algorithm resolves the ambiguity in its own way, and the resolution
 *    is never guaranteed to be "right". However, it is often excellent.
 * This program is intended to be pedagogic.  Specifically, this program was
 *    the basis of the Literate Programming column which appeared in the
 *    Communications of the ACM (CACM), in the June 1989 issue (32, 6,
 *    740-755).
 * By "pedagogic", I do not mean that the program is gracefully worded, or
 *    that it showcases language features or its algorithm. I also do not mean
 *    that it is highly accessible to beginners, or that it is intended to be
 *    read in full, or in a particular order. Rather, this program is an
 *    example of one professional"s style of keeping things organized and
 *    maintainable.
 * The program would be better if the "print" variables were wrapped into
 *    a struct. In general, grouping related variables in this way improves
 *    documentation, and adds the ability to pass the group in argument lists.
 * This program is a de-engineered version of a program which uses less
 *    memory and less time.  The article points out that the "symbol" arrays
 *    can be implemented as arrays of pointers to arrays, with dynamic
 *    allocation of the subarrays.  (In C, macros are very useful for hiding 
 *    the two-level accesses.) In Java, a Vector would be used. This allows an
 *    extremely large value for MAXLINECOUNT, without dedicating fixed arrays.
 *    (The "other" array can be allocated after the input phase, when the exact
 *    sizes are known.) The only slow piece of code is the "strcmp" in the tree
 *    descent: it can be speeded up by keeping a hash in the tree node, and
 *    only using "strcmp" when two hashes happen to be equal.
 *
 * Change Log
 * ----------
 *  1Jan97 Ian F. Darwin: first working rewrite in Java, based entirely on
 *   D.C.Lindsay"s reasonable C version.
 *  Changed comments from /***************** to /**, shortened, added
 *  whitespace, used tabs more, etc.
 *  6jul89 D.C.Lindsay, CMU: fixed portability bug. Thanks, Gregg Wonderly.
 *         Just changed "char ch" to "int ch". 
 *         Also added comment about way to improve code.
 * 10jun89 D.C.Lindsay, CMU: posted version created.
 *         Copyright notice changed to ACM style, and Dept. is now School.
 *         ACM article referenced in docn.
 * 26sep87 D.C.Lindsay, CMU: publication version created.
 *         Condensed all 1982/83 change log entries.
 *         Removed all command line options, and supporting code. This 
 *         simplified the input code (no case reduction etc). It also
 *         simplified the symbol table, which was capable of remembering
 *         offsets into files (instead of strings), and trusting (!) hash
 *         values to be unique.
 *         Removed dynamic allocation of arrays: now fixed static arrays.
 *         Removed speed optimizations in symtab package.
 *         Removed string compression/decompression code.
 *         Recoded to Unix standards from old Lattice/MSDOS standards.
 *         (This affected only the #include"s and the IO.)
 *         Some renaming of variables, and rewording of comments.
 * 1982/83 D.C.Lindsay, Symbionics: created.
 *
 * @author  Ian F. Darwin, Java version
 * @version  Java version 0.9, 1997
 * @author  D. C. Lindsay, C version (1982-1987)
 *
 */
public class Diff {
  /** block len > any possible real block len */
  final int UNREAL=Integer.MAX_VALUE;
  /** Keeps track of information about file1 and file2 */
  fileInfo oldinfo, newinfo;
  /** blocklen is the info about found blocks. It will be set to 0, except
   * at the line#s where blocks start in the old file. At these places it
   * will be set to the # of lines in the block. During printout ,
   * this # will be reset to -1 if the block is printed as a MOVE block
   * (because the printout phase will encounter the block twice, but
   * must only print it once.)
   * The array declarations are to MAXLINECOUNT+2 so that we can have two
   * extra lines (pseudolines) at line# 0 and line# MAXLINECOUNT+1
   * (or less).
   */
  int blocklen[];
  /**
   * main - entry point when used standalone.
   * NOTE: no routines return error codes or throw any local
   * exceptions. Instead, any routine may complain
   * to stderr and then exit with error to the system.
   */
  public static void main(String argstrings[])
  {
    if ( argstrings.length != 2 ) {
      System.err.println("Usage: diff oldfile newfile" );
      System.exit(1);
    }
    Diff d = new Diff();
    d.doDiff(argstrings[0], argstrings[1]);
    return;
  }
  /** Construct a Diff object. */
  Diff() {
  }
  /** Do one file comparison. Called with both filenames. */
  public void doDiff(String oldFile, String newFile) {
    println( ">>>> Difference of file \"" + oldFile + 
      "\" and file \"" + newFile + "\".\n");
    oldinfo = new fileInfo(oldFile);
    newinfo = new fileInfo(newFile);
    /* we don"t process until we know both files really do exist. */
    try {
      inputscan( oldinfo );
      inputscan( newinfo );
    } catch (IOException e) {
      System.err.println("Read error: " + e);
    }
    /* Now that we"ve read all the lines, allocate some arrays.
     */
    blocklen = new int[ (oldinfo.maxLine>newinfo.maxLine?
      oldinfo.maxLine : newinfo.maxLine) + 2 ];
    oldinfo.alloc();
    newinfo.alloc();
    /* Now do the work, and print the results. */
    transform();
    printout();
  }
  /**
   * inputscan    Reads the file specified by pinfo.file.
   * ---------    Places the lines of that file in the symbol table.
   *              Sets pinfo.maxLine to the number of lines found.
   */
  void inputscan( fileInfo pinfo ) throws IOException
  {
       String linebuffer;
       pinfo.maxLine = 0;
       while ((linebuffer = pinfo.file.readLine()) != null) {
           storeline( linebuffer, pinfo );
       }
  }
  /**
   * storeline    Places line into symbol table.
   * ---------    Expects pinfo.maxLine initted: increments.
   *              Places symbol table handle in pinfo.ymbol.
   *              Expects pinfo is either oldinfo or newinfo.
   */
  void storeline( String linebuffer, fileInfo pinfo )
  {
       int linenum = ++pinfo.maxLine;    /* note, no line zero */
       if ( linenum > fileInfo.MAXLINECOUNT ) {
      System.err.println( "MAXLINECOUNT exceeded, must stop." );
      System.exit(1);
       }
       pinfo.symbol[ linenum ] =
      node.addSymbol( linebuffer, pinfo == oldinfo, linenum );
  }
  /*
   * transform    
   * Analyzes the file differences and leaves its findings in
   * the global arrays oldinfo.other, newinfo.other, and blocklen.
   * Expects both files in symtab.
   * Expects valid "maxLine" and "symbol" in oldinfo and newinfo.
   */
  void transform()
  {                                  
       int oldline, newline;
       int oldmax = oldinfo.maxLine + 2;  /* Count pseudolines at  */
       int newmax = newinfo.maxLine + 2;  /* ..front and rear of file */
       for (oldline=0; oldline < oldmax; oldline++ )
      oldinfo.other[oldline]= -1;
       for (newline=0; newline < newmax; newline++ )
      newinfo.other[newline]= -1;
       scanunique();  /* scan for lines used once in both files */
       scanafter();   /* scan past sure-matches for non-unique blocks */
       scanbefore();  /* scan backwards from sure-matches */
       scanblocks();  /* find the fronts and lengths of blocks */
  }
  /*
   * scanunique
   * Scans for lines which are used exactly once in each file.
   * Expects both files in symtab, and oldinfo and newinfo valid.
   * The appropriate "other" array entries are set to the line# in
   * the other file.
   * Claims pseudo-lines at 0 and XXXinfo.maxLine+1 are unique.
   */
  void scanunique()
  {
       int oldline, newline;
       node psymbol;
       for( newline = 1; newline <= newinfo.maxLine; newline++ ) {
      psymbol = newinfo.symbol[ newline ];
      if ( psymbol.symbolIsUnique()) {        // 1 use in each file
           oldline = psymbol.linenum;
           newinfo.other[ newline ] = oldline; // record 1-1 map
           oldinfo.other[ oldline ] = newline;
      }
       }
       newinfo.other[ 0 ] = 0;
       oldinfo.other[ 0 ] = 0;
       newinfo.other[ newinfo.maxLine + 1 ] = oldinfo.maxLine + 1;
       oldinfo.other[ oldinfo.maxLine + 1 ] = newinfo.maxLine + 1;
  }
  /*
   * scanafter
   * Expects both files in symtab, and oldinfo and newinfo valid.
   * Expects the "other" arrays contain positive #s to indicate
   * lines that are unique in both files.
   * For each such pair of places, scans past in each file.
   * Contiguous groups of lines that match non-uniquely are
   * taken to be good-enough matches, and so marked in "other".
   * Assumes each other[0] is 0.
   */
  void scanafter()
  {
       int oldline, newline;
       for( newline = 0; newline <= newinfo.maxLine; newline++ ) {
      oldline = newinfo.other[ newline ];
      if ( oldline >= 0 ) {  /* is unique in old & new */
           for(;;) {  /* scan after there in both files */
          if ( ++oldline > oldinfo.maxLine   ) break; 
          if ( oldinfo.other[ oldline ] >= 0 ) break;
          if ( ++newline > newinfo.maxLine   ) break; 
          if ( newinfo.other[ newline ] >= 0 ) break;
          /* oldline & newline exist, and 
        aren"t already matched */
          if ( newinfo.symbol[ newline ] !=
        oldinfo.symbol[ oldline ] ) break;  // not same
          newinfo.other[newline] = oldline; // record a match
          oldinfo.other[oldline] = newline;
           }
      }
       }
  }
  /**
   * scanbefore
   * As scanafter, except scans towards file fronts.
   * Assumes the off-end lines have been marked as a match.
   */
  void scanbefore()
  {
       int oldline, newline;
       for( newline = newinfo.maxLine + 1; newline > 0; newline-- ) {
      oldline = newinfo.other[ newline ];
      if ( oldline >= 0 ) {               /* unique in each */
           for(;;) {
          if ( --oldline <= 0                ) break;
          if ( oldinfo.other[ oldline ] >= 0 ) break;
          if ( --newline <= 0                ) break;
          if ( newinfo.other[ newline ] >= 0 ) break;
     
          /* oldline and newline exist,
        and aren"t marked yet */
          if ( newinfo.symbol[ newline ] !=
        oldinfo.symbol[ oldline ] ) break;  // not same
          newinfo.other[newline] = oldline; // record a match
          oldinfo.other[oldline] = newline;
           }
      }
       }
  }
  /**
   * scanblocks - Finds the beginnings and lengths of blocks of matches.
   * Sets the blocklen array (see definition).
   * Expects oldinfo valid.
   */
  void scanblocks()
  {
       int oldline, newline;
       int oldfront = 0;      // line# of front of a block in old, or 0 
       int newlast = -1;      // newline"s value during prev. iteration
       for( oldline = 1; oldline <= oldinfo.maxLine; oldline++ )
           blocklen[ oldline ] = 0;
       blocklen[ oldinfo.maxLine + 1 ] = UNREAL; // starts a mythical blk
       for( oldline = 1; oldline <= oldinfo.maxLine; oldline++ ) {
      newline = oldinfo.other[ oldline ];
      if ( newline < 0 ) oldfront = 0;  /* no match: not in block */
      else{                                   /* match. */
           if ( oldfront == 0 )         oldfront = oldline;
           if ( newline != (newlast+1)) oldfront = oldline;
           ++blocklen[ oldfront ];            
      }
      newlast = newline;
       }
  }
  /* The following are global to printout"s subsidiary routines */
  // enum{ idle, delete, insert, movenew, moveold,
  // same, change } printstatus;
  public static final int
    idle = 0, delete = 1, insert = 2, movenew = 3, moveold = 4,
    same = 5, change = 6;
  int printstatus;
  boolean anyprinted;
  int printoldline, printnewline;     // line numbers in old & new file
  /**
   * printout - Prints summary to stdout.
   * Expects all data structures have been filled out.
   */
  void printout()
  {
       printstatus = idle;
       anyprinted = false;
       for( printoldline = printnewline = 1; ; ) {
      if ( printoldline > oldinfo.maxLine ) { newconsume(); break;}
      if ( printnewline > newinfo.maxLine ) { oldconsume(); break;}
      if (      newinfo.other[ printnewline ] < 0 ) {
           if ( oldinfo.other[ printoldline ] < 0 )
        showchange();
           else
        showinsert();
      }
      else if ( oldinfo.other[ printoldline ] < 0 )
      showdelete();
      else if ( blocklen[ printoldline ] < 0 )
      skipold();
      else if ( oldinfo.other[ printoldline ] == printnewline )
      showsame();
      else
      showmove();
       }
       if ( anyprinted == true ) println( ">>>> End of differences."  );
       else                     println( ">>>> Files are identical." );
  }
  /*
   * newconsume        Part of printout. Have run out of old file. 
   * Print the rest of the new file, as inserts and/or moves.
   */
  void newconsume()
  {
       for(;;) {
      if ( printnewline > newinfo.maxLine )
      break;        /* end of file */
      if ( newinfo.other[ printnewline ] < 0 ) showinsert();
      else                                    showmove();
       }
  }
  /**
   * oldconsume        Part of printout. Have run out of new file.
   * Process the rest of the old file, printing any
   * parts which were deletes or moves.
   */
  void oldconsume()
  {
       for(;;) {
      if ( printoldline > oldinfo.maxLine )
      break;       /* end of file */
      printnewline = oldinfo.other[ printoldline ];
      if ( printnewline < 0 ) showdelete();
      else if ( blocklen[ printoldline ] < 0 ) skipold();
      else showmove();
       }
  }
  /**
   * showdelete        Part of printout.
   * Expects printoldline is at a deletion.
   */
  void showdelete()
  {
    if ( printstatus != delete )
      println( ">>>> DELETE AT " + printoldline);
    printstatus = delete;
    oldinfo.symbol[ printoldline ].showSymbol();
    anyprinted = true;
    printoldline++;
  }
  /*
   * showinsert        Part of printout.
   * Expects printnewline is at an insertion.
   */
  void showinsert()
  {
       if ( printstatus == change ) println( ">>>>     CHANGED TO" );
       else if ( printstatus != insert ) 
      println( ">>>> INSERT BEFORE " + printoldline );
       printstatus = insert;
       newinfo.symbol[ printnewline ].showSymbol();
       anyprinted = true;
       printnewline++;
  }
  /**
   * showchange        Part of printout.
   * Expects printnewline is an insertion.
   *  Expects printoldline is a deletion.
   */
  void showchange()
  {
       if ( printstatus != change ) 
      println( ">>>> " + printoldline + " CHANGED FROM");
       printstatus = change;
       oldinfo.symbol[ printoldline ].showSymbol();
       anyprinted = true;
       printoldline++;
  }
  /**
   * skipold           Part of printout.
   * Expects printoldline at start of an old block that has 
   * already been announced as a move.
   * Skips over the old block.
   */
  void skipold()
  {
       printstatus = idle;
       for(;;) {
      if ( ++printoldline > oldinfo.maxLine )
      break;     /* end of file  */
      if ( oldinfo.other[ printoldline ] < 0 )
      break;    /* end of block */
      if ( blocklen[ printoldline ]!=0)
      break;          /* start of another */
       }
  }
  /**
   * skipnew           Part of printout.
   * Expects printnewline is at start of a new block that has
   * already been announced as a move.
   * Skips over the new block.
   */
  void skipnew()
  {
       int oldline;
       printstatus = idle;
       for(;;) {
      if ( ++printnewline > newinfo.maxLine )
      break;    /* end of file  */
      oldline = newinfo.other[ printnewline ];
      if ( oldline < 0 )
      break;                         /* end of block */
      if ( blocklen[ oldline ] != 0)
      break;              /* start of another */
       }
  }
  /**
   * showsame          Part of printout.
   * Expects printnewline and printoldline at start of
   * two blocks that aren"t to be displayed.
   */
  void showsame()
  {
       int count;
       printstatus = idle;
       if ( newinfo.other[ printnewline ] != printoldline ) {
      System.err.println("BUG IN LINE REFERENCING");
      System.exit(1);
       }
       count = blocklen[ printoldline ];
       printoldline += count;
       printnewline += count;
  }
  /**
   * showmove          Part of printout.
   * Expects printoldline, printnewline at start of
   * two different blocks ( a move was done).
   */
  void showmove()
  {
       int oldblock = blocklen[ printoldline ];
       int newother = newinfo.other[ printnewline ];
       int newblock = blocklen[ newother ];
       if ( newblock < 0 ) skipnew();         // already printed.
       else if ( oldblock >= newblock ) {     // assume new"s blk moved.
      blocklen[newother] = -1;         // stamp block as "printed".
      println( ">>>> " + newother + 
      " THRU " + (newother + newblock - 1) + 
      " MOVED TO BEFORE " + printoldline );
      for( ; newblock > 0; newblock--, printnewline++ )
           newinfo.symbol[ printnewline ].showSymbol();
      anyprinted = true;
      printstatus = idle;
       } else                /* assume old"s block moved */
      skipold();      /* target line# not known, display later */
  }
  /** Convenience wrapper for println */
  public void println(String s) {
    System.out.println(s);
  }
};        // end of main class!
/**
 * Class "node". The symbol table routines in this class all
 * understand the symbol table format, which is a binary tree.
 * The methods are: addSymbol, symbolIsUnique, showSymbol.
 */ 
class node{                       /* the tree is made up of these nodes */
  node pleft, pright;
  int linenum;
  static final int freshnode = 0,
  oldonce = 1, newonce = 2, bothonce = 3, other = 4;
  int /* enum linestates */ linestate;
  String line;
  static node panchor = null;    /* symtab is a tree hung from this */
  /**
   * Construct a new symbol table node and fill in its fields.
   * @param        string  A line of the text file
   */
  node( String pline)
  {
       pleft = pright = null;
       linestate = freshnode;
       /* linenum field is not always valid */     
       line = pline;
  }
  /**
   * matchsymbol       Searches tree for a match to the line.
   * @param  String  pline, a line of text
   * If node"s linestate == freshnode, then created the node.
   */
  static node matchsymbol( String pline )
  {
       int comparison;
       node pnode = panchor;
       if ( panchor == null ) return panchor = new node( pline);
       for(;;) {
      comparison = pnode.line.rupareTo(pline);
      if ( comparison == 0 ) return pnode;          /* found */
      if ( comparison < 0 ) {
           if ( pnode.pleft == null ) {
          pnode.pleft = new node( pline);
          return pnode.pleft;
           }
           pnode = pnode.pleft;
      }
      if ( comparison > 0 ) {
           if ( pnode.pright == null ) {
          pnode.pright = new node( pline);
          return pnode.pright;
           }
           pnode = pnode.pright;
      }
       }
       /* NOTE: There are return stmts, so control does not get here. */
  }
  /**
   * addSymbol(String pline) - Saves line into the symbol table.
   * Returns a handle to the symtab entry for that unique line.
   * If inoldfile nonzero, then linenum is remembered.
   */
  static node addSymbol( String pline, boolean inoldfile, int linenum )
  {
    node pnode;
    pnode = matchsymbol( pline );  /* find the node in the tree */
    if ( pnode.linestate == freshnode ) {
      pnode.linestate = inoldfile ? oldonce : newonce;
    } else {
      if (( pnode.linestate == oldonce && !inoldfile ) ||
          ( pnode.linestate == newonce &&  inoldfile )) 
           pnode.linestate = bothonce;
      else pnode.linestate = other;
    }
    if (inoldfile) pnode.linenum = linenum;
    return pnode;
  }
  /**
   * symbolIsUnique    Arg is a ptr previously returned by addSymbol.
   * --------------    Returns true if the line was added to the
   *                   symbol table exactly once with inoldfile true,
   *                   and exactly once with inoldfile false.
   */
  boolean symbolIsUnique()
  {
    return (linestate == bothonce );
  }
  /**
   * showSymbol        Prints the line to stdout.
   */
  void showSymbol()
  {
    System.out.println(line);
  }
}





DirTree - directory lister, like UNIX ls or DOS and VMS dir

   
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
import java.io.File;
/**
 * DirTree - directory lister, like UNIX ls or DOS and VMS dir
 * 
 * @author Ian Darwin, http://www.darwinsys.ru/
 * @version $Id: DirTree.java,v 1.4 2004/02/09 03:33:47 ian Exp $
 */
public class DirTree {
  /** Main program */
  public static void main(String[] argv) {
    DirTree dt = new DirTree();
    if (argv.length == 0)
      dt.doDir(".");
    else
      for (int i = 0; i < argv.length; i++)
        dt.doDir(argv[i]);
  }
  /** doDir - handle one filesystem object by name */
  private void doDir(String s) {
    File f = new File(s);
    if (!f.exists()) {
      System.out.println(s + " does not exist");
      return;
    }
    if (f.isFile())
      doFile(f);
    else if (f.isDirectory()) {
      System.out.println("d " + f.getPath());
      String objects[] = f.list();
      for (int i = 0; i < objects.length; i++)
        doDir(s + f.separator + objects[i]);
    } else
      System.err.println("Unknown: " + s);
  }
  /** doFile - process one regular file. */
  private static void doFile(File f) {
    System.out.println("f " + f.getPath());
  }
}





File concatenation

   
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class Cat {
  public static void concatenate(String fileName) {
    RandomAccessFile file = null;
    String line = null;
    try {
      file = new RandomAccessFile(fileName, "r");
      while ((line = file.readLine()) != null) {
        System.out.println(line);
      }
      return;
    } catch (FileNotFoundException fnf) {
      System.err.println("File: " + fileName + " not found.");
    } catch (Exception e) {
      System.err.println(e.toString());
    } finally {
      if (file != null) {
        try {
          file.close();
        } catch (IOException io) {
        }
      }
    }
  }
  public static void main(String[] args) {
    for (int i = 0; i < args.length; i++)
      Cat.concatenate(args[i]);
  }
}





File Copy in Java

   
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
 * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *
 * -Redistribution in binary form must reproduce the above copyright notice,
 *  this list of conditions and the following disclaimer in the documentation
 *  and/or other materials provided with the distribution.
 *
 * Neither the name of Sun Microsystems, Inc. or the names of contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Copy {
  public static void main(String[] args) throws IOException {
    File inputFile = new File("farrago.txt");
    File outputFile = new File("outagain.txt");
    FileReader in = new FileReader(inputFile);
    FileWriter out = new FileWriter(outputFile);
    int c;
    while ((c = in.read()) != -1)
      out.write(c);
    in.close();
    out.close();
  }
}





File Copy in Java with NIO

   
package com.jexp.tools.dev;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.channels.FileChannel;
class NioBenchmark1 {
  static int size = 60; // MB
  static int tests = 5;
  interface Copier {
    public void copy(File s, File t) throws IOException;
  }
  static class NioCopier implements Copier {
    public void copy(File s, File t) throws IOException {
      FileChannel in = (new FileInputStream(s)).getChannel();
      FileChannel out = (new FileOutputStream(t)).getChannel();
      in.transferTo(0, s.length(), out);
      in.close();
      out.close();
    }
  }
  static class IoCopier implements Copier {
    final int BUFF_SIZE = 5 * 1024 * 1024; // 5MB
    final byte[] buffer = new byte[BUFF_SIZE];
    public void copy(File s, File t) throws IOException {
      InputStream in = new FileInputStream(s);
      FileOutputStream out = new FileOutputStream(t);
      while (true) {
        int count = in.read(buffer);
        if (count == -1)
          break;
        out.write(buffer, 0, count);
      }
      out.close();
      in.close();
    }
  }
  public static void main(String[] arg) throws IOException {
    Copier io = new IoCopier();
    Copier nio = new NioCopier();
    nio.copy(new File("s"), new File("t"));
    io.copy(new File("s"), new File("t"));
  }

}





FNFilter - directory lister using FilenameFilter

   
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
import java.io.File;
import java.io.FilenameFilter;
/**
 * FNFilter - directory lister using FilenameFilter
 * 
 * @author Ian Darwin
 */
public class FNFilter2 implements FilenameFilter {
  public static void main(String[] av) {
    FNFilter2 ff = new FNFilter2();
    ff.process(".");
  }
  public void process(String dir) {
    String objects[] = (new File(dir)).list(this);
    for (int i = 0; i < objects.length; i++)
      System.out.println(objects[i]);
  }
  public boolean accept(File dir, String s) {
    if (s.endsWith(".java"))
      return true;
    // others?
    return false;
  }
}





Get file date and time

     
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
/*
 * IzPack - Copyright 2001-2008 Julien Ponge, All Rights Reserved.
 *
 * http://izpack.org/
 * http://izpack.codehaus.org/
 *
 * Copyright 2005 Marc Eppelmann
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Provides general global file utility methods
 *
 * @author marc.eppelmann
 */
class FileUtil
{
    //~ Constructors ***********************************************************************
    /**
     * Creates a new FileUtil object.
     */
    public FileUtil()
    {
    }
    //~ Methods ****************************************************************************
    /**
     * Gets the content from a File as StringArray List.
     *
     * @param fileName A file to read from.
     * @return List of individual line of the specified file. List may be empty but not
     *         null.
     * @throws IOException
     */
    public static ArrayList getFileContent(String fileName)
            throws IOException
    {
        ArrayList result = new ArrayList();
        File aFile = new File(fileName);
        if (!aFile.isFile())
        {
            //throw new IOException( fileName + " is not a regular File" );
            return result; // None
        }
        BufferedReader reader = null;
        try
        {
            reader = new BufferedReader(new FileReader(aFile));
        }
        catch (FileNotFoundException e1)
        {
            // TODO handle Exception
            e1.printStackTrace();
            return result;
        }
        String aLine = null;
        while ((aLine = reader.readLine()) != null)
        {
            result.add(aLine + "\n");
        }
        reader.close();
        return result;
    }
    /**
     * Searches case sensitively, and returns true if the given SearchString occurs in the
     * first File with the given Filename.
     *
     * @param aFileName     A files name
     * @param aSearchString the string search for
     * @return true if found in the file otherwise false
     */
    public static boolean fileContains(String aFileName, String aSearchString)
    {
        return (fileContains(aFileName, aSearchString, false));
    }
    /**
     * Tests if the given File contains the given Search String
     *
     * @param aFileName             A files name
     * @param aSearchString         the String to search for
     * @param caseInSensitiveSearch If false the Search is casesensitive
     * @return true if found in the file otherwise false
     */
    public static boolean fileContains(String aFileName, String aSearchString,
                                       boolean caseInSensitiveSearch)
    {
        boolean result = false;
        String searchString = caseInSensitiveSearch
                ? aSearchString.toLowerCase() : aSearchString;
        ArrayList fileContent = new ArrayList();
        try
        {
            fileContent = getFileContent(aFileName);
        }
        catch (IOException e)
        {
            // TODO handle Exception
            e.printStackTrace();
        }
        Iterator linesIter = fileContent.iterator();
        while (linesIter.hasNext())
        {
            String currentline = (String) linesIter.next();
            if (caseInSensitiveSearch)
            {
                currentline = currentline.toLowerCase();
            }
            if (currentline.indexOf(searchString) > -1)
            {
                result = true;
                break;
            }
        }
        return result;
    }
    /**
     * Gets file date and time.
     *
     * @param url The URL of the file for which date and time will be returned.
     * @return Returns long value which is the date and time of the file. If any error
     *         occures returns -1 (=no file date and time available).
     */
    public static long getFileDateTime(URL url)
    {
        if (url == null)
        {
            return -1;
        }
        String fileName = url.getFile();
        if (fileName.charAt(0) == "/" || fileName.charAt(0) == "\\")
        {
            fileName = fileName.substring(1, fileName.length());
        }
        try
        {
            File file = new File(fileName);
            // File name must be a file or a directory.
            if (!file.isDirectory() && !file.isFile())
            {
                return -1;
            }
            return file.lastModified();
        }
        catch (java.lang.Exception e)
        {   // Trap all Exception based exceptions and return -1.
            return -1;
        }
    }
    public static String[] getFileNames(String dirPath) throws Exception
    {
        return getFileNames(dirPath, null);
    }
    public static String[] getFileNames(String dirPath, FilenameFilter fileNameFilter) throws Exception
    {
        String fileNames[] = null;
        File dir = new File(dirPath);
        if (dir.isDirectory())
        {
            if (fileNameFilter != null)
            {
                fileNames = dir.list(fileNameFilter);
            }
            else
            {
                fileNames = dir.list();
            }
        }
        return fileNames;
    }
    /**
     * Test main
     *
     * @param args
     */
    public static void main(String[] args)
    {
    }
}





Grep tools

    
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Grep {
  public static void main(String args[]) throws Exception {
    String regex = "";
    InputStream in = System.in;
    regex = args[0];
    in = new BufferedInputStream(new FileInputStream(args[1]));
    Pattern p = null;
    p = Pattern.rupile(regex);
    BufferedReader buff = new BufferedReader(new InputStreamReader(in));
    String a;
    for (a = buff.readLine(); a != null; a = buff.readLine()) {
      Matcher m = p.matcher(a);
      if (m.find()) {
        System.out.println(a);
      }
    }
  }
}





List root directory

   

import java.io.File;
public class ListRoots {
  public static void main(String argh_my_aching_fingers[]) {
    File[] drives = File.listRoots(); // Get list of names
    for (int i = 0; i < drives.length; i++)
      System.out.println(drives[i]); // Print the list
  }
}





Ls directory lister modified to use FilenameFilter

   
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
import java.io.File;
import java.io.FilenameFilter;
/**
 * FNFilter - Ls directory lister modified to use FilenameFilter
 * 
 * @author Ian Darwin
 * @version $Id: FNFilter.java,v 1.3 2004/03/11 03:33:35 ian Exp $
 */
public class FNFilter {
  public static void main(String argh_my_aching_fingers[]) {
    // Generate the selective list, with a one-use File object.
    String[] dir = new java.io.File(".").list(new OnlyJava());
    java.util.Arrays.sort(dir); // Sort it (Data Structuring chapter))
    for (int i = 0; i < dir.length; i++)
      System.out.println(dir[i]); // Print the list
  }
}
/**
 * This class implements the FilenameFilter interface. The Accept method returns
 * true for .java, .class and .jar files.
 */
class OnlyJava implements FilenameFilter {
  public boolean accept(File dir, String s) {
    if (s.endsWith(".java") || s.endsWith(".class") || s.endsWith(".jar"))
      return true;
    // others: projects, ... ?
    return false;
  }
}





Mimic the Unix Grep command

   
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
public class GrepReader extends BufferedReader {
  String pattern;
  public GrepReader(Reader in, String pattern) {
    super(in);
    this.pattern = pattern;
  }
  public final String readLine() throws IOException {
    String line;
    do {
      line = super.readLine();
    } while ((line != null) && line.indexOf(pattern) == -1);
    return line;
  }
  public static void main(String args[]) {
    try {
      GrepReader in = new GrepReader(new FileReader("GrepReader.java"), "GrepReader");
      String line;
      while ((line = in.readLine()) != null)
        System.out.println(line);
      in.close();
    } catch (Exception e) {
      System.err.println(e);
    }
  }
}





mkdir examples

   
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
import java.io.File;
/**
 * The collected mkdir examples (JavaCook 2e, Recipe 11.9).
 */
public class MkDirExamples {
  public static void main(String[] args) {
    boolean status;
    status = new File("/home/ian/bin").mkdir();
    report(status);
    status = new File("/home/ian/src").mkdir();
    report(status);
    status = new File("/home/ian/once/twice/again").mkdir(); // should fail
    report(status);
    status = new File("/home/ian/once/twice/again").mkdirs(); // should
                                  // succeed
    report(status);
  }
  static void report(boolean b) {
    System.out.println(b ? "success" : "failure");
  }
}





Move a File

  
/*
 * Static File routines.
 * Copyright (C) 2002 Stephen Ostermiller
 * http://ostermiller.org/contact.pl?regarding=Java+Utilities
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * See COPYING.TXT for details.
 */

import java.io.*;
import java.text.MessageFormat;
import java.util.ResourceBundle;
import java.util.Locale;
/**
 * Utilities for File manipulation.
 * More information about this class is available from .
 *
 * @author Stephen Ostermiller http://ostermiller.org/contact.pl?regarding=Java+Utilities
 * @since ostermillerutils 1.00.00
 */
public class FileHelper {
  /**
   * Locale specific strings displayed to the user.
   *
   * @since ostermillerutils 1.00.00
   */
  protected static ResourceBundle labels = ResourceBundle.getBundle("com.Ostermiller.util.FileHelper",  Locale.getDefault());

  /**
   * Move a file from one location to another.  An attempt is made to rename
   * the file and if that fails, the file is copied and the old file deleted.
   *
   * If the destination file already exists, an exception will be thrown.
   *
   * @param from file which should be moved.
   * @param to desired destination of the file.
   * @throws IOException if an error occurs.
   *
   * @since ostermillerutils 1.00.00
   */
  public static void move(File from, File to) throws IOException {
    move(from, to, false);
  }
  /**
   * Move a file from one location to another.  An attempt is made to rename
   * the file and if that fails, the file is copied and the old file deleted.
   *
   * @param from file which should be moved.
   * @param to desired destination of the file.
   * @param overwrite If false, an exception will be thrown rather than overwrite a file.
   * @throws IOException if an error occurs.
   *
   * @since ostermillerutils 1.00.00
   */
  public static void move(File from, File to, boolean overwrite) throws IOException {
    if (to.exists()){
      if (overwrite){
        if (!to.delete()){
          throw new IOException(
            MessageFormat.format(
              labels.getString("deleteerror"),
              (Object[])new String[] {
                to.toString()
              }
            )
          );
        }
      } else {
        throw new IOException(
          MessageFormat.format(
            labels.getString("alreadyexistserror"),
            (Object[])new String[] {
              to.toString()
            }
          )
        );
      }
    }
    if (from.renameTo(to)) return;
    InputStream in = null;
    OutputStream out = null;
    try {
      in = new FileInputStream(from);
      out = new FileOutputStream(to);
      copy(in, out);
      in.close();
      in = null;
      out.flush();
      out.close();
      out = null;
      if (!from.delete()){
        throw new IOException(
          MessageFormat.format(
            labels.getString("deleteoriginalerror"),
            (Object[])new String[] {
              from.toString(),
              to.toString()
            }
          )
        );
      }
    } finally {
      if (in != null){
        in.close();
        in = null;
      }
      if (out != null){
        out.flush();
        out.close();
        out = null;
      }
    }
  }
  /**
   * Buffer size when reading from input stream.
   *
   * @since ostermillerutils 1.00.00
   */
  private final static int BUFFER_SIZE = 1024;
  /**
   * Copy the data from the input stream to the output stream.
   *
   * @param in data source
   * @param out data destination
   * @throws IOException in an input or output error occurs
   *
   * @since ostermillerutils 1.00.00
   */
  private static void copy(InputStream in, OutputStream out) throws IOException {
    byte[] buffer = new byte[BUFFER_SIZE];
    int read;
    while((read = in.read(buffer)) != -1){
      out.write(buffer, 0, read);
    }
  }
}





Move File

     
/**
 * Copyright (c) 2003 - 2007 OpenSubsystems s.r.o. Slovak Republic. All rights reserved.
 * 
 * Project: OpenSubsystems
 * 
 * $Id: FileUtils.java,v 1.12 2007/02/01 07:18:32 bastafidli Exp $
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 2 of the License. 
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 
 */

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.logging.Logger;

/**
 * Collection of methods to make work with files easier.
 * 
 * @version $Id: FileUtils.java,v 1.12 2007/02/01 07:18:32 bastafidli Exp $
 * @author Miro Halas
 * @code.reviewer Miro Halas
 * @code.reviewed 1.7 2006/05/21 03:45:37 bastafidli
 */
public class FileUtils
{
   // Configuration settings ///////////////////////////////////////////////////
   
   /**
    * Default 10 digit file storage distribution array. This means that if I 
    * want to name file as 10 digit number e.g. number 123 as 0000000123 or 
    * number 123456789 as 01234567890. Then the path constructed from number 
    * 1234567890 using distribution 2/2/2/4 would be 12/34/56/0123456789 
    */
   public static final int[] DEFAULT_STRORAGE_TREE_DISTRIBUTION = {2, 2, 2, 4};
   
   /**
    * How big buffer to use to process files.
    */
   public static final int BUFFER_SIZE = 65536;
   
   // Cached values ////////////////////////////////////////////////////////////
   
   /**
    * Temporary directory to use. It is guarantee that it ends with \ (or /)
    */
   protected static String s_strTempDirectory;
   
   // Constructors /////////////////////////////////////////////////////////////
   
  
   
   /**
    * Move file to a new location. If the destination is on different volume,
    * this file will be copied and then original file will be deleted.
    * If the destination already exists, this method renames it with different
    * name and leaves it in that directory and moves the new file along side 
    * the renamed one.
    * 
    * @param flCurrent - file to move
    * @param flDestination - destination file
    * @throws IOException - error message
    * @throws OSSException - error message
    */
   public static void moveFile(
      File flCurrent, 
      File flDestination
   ) throws IOException
   {
      // Make sure that the source exist, it might be already moved from 
      // a directory and we just don"t know about it
      if (flCurrent.exists())
      {
         // Next check if the destination file exists
         if (flDestination.exists())
         {
            // If the destination exists, that means something went wrong
            // Rename the destination file under temporaty name and try to  
            // move the new file instead of it
          
            renameToTemporaryName(flDestination, "old");
         }
      
         // Make sure the directory exists and if not create it
         File flFolder;
         
         flFolder = flDestination.getParentFile();
         if ((flFolder != null) && (!flFolder.exists()))
         {
            if (!flFolder.mkdirs())
            {
               // Do not throw the exception if the directory already exists
               // because it was created meanwhile for example by a different 
               // thread
               if (!flFolder.exists())
               {
                  throw new IOException("Cannot create directory " + flFolder);
               }
            }
         }
         
         // Now everything should exist so try to rename the file first
         // After testing, this renames files even between volumes C to H 
         // so we don"t have to do anything else on Windows but we still
         // have to handle erro on Unix 
         if (!flCurrent.renameTo(flDestination))
         {
            // Try to copy and delete since the rename doesn"t work on Solaris
            // between file systems
            copyFile(flCurrent, flDestination);
            
            // Now delete the file
            if (!flCurrent.delete())
            {
               // Delete the destination file first since we haven"t really moved
               // the file
               flDestination.delete();
               throw new IOException("Cannot delete already copied file " + flCurrent);
            }
         }
      }   
   }
 
   /**
    * Copy the current file to the destination file.
    * 
    * @param flCurrent - source file
    * @param flDestination - destination file
    * @throws IOException - error message
    * @throws OSSException - error message
    */  
   public static void copyFile(
      File flCurrent,
      File flDestination
   ) throws IOException
   {
     // Make sure the directory exists and if not create it
     File flFolder;
     
     flFolder = flDestination.getParentFile();
     if ((flFolder != null) && (!flFolder.exists()))
     {
        if (!flFolder.mkdirs())
        {
           // Do not throw the exception if the directory already exists
           // because it was created meanwhile for example by a different 
           // thread
           if (!flFolder.exists())
           {
              throw new IOException("Cannot create directory " + flFolder);
           }
        }
     }
      // FileChannel srcChannel = null;
      // FileChannel dstChannel = null;
      FileInputStream finInput = null;
      
      //MHALAS: This code is not working reliably on Solaris 8 with 1.4.1_01
      // Getting exceptions from native code
      /*
      // Create channel on the source
      srcChannel = new FileInputStream(flCurrent).getChannel();
      // Create channel on the destination
      dstChannel = new FileOutputStream(flDestination).getChannel();
 
      // Copy file contents from source to destination
      dstChannel.transferFrom(srcChannel, 0, srcChannel.size());   
         
      Don"t forget to close the channels if you enable this code again
      */
      try
      {
         finInput = new FileInputStream(flCurrent);
      }
      catch (IOException ioExec)
      {
         if (finInput != null)
         {
            try
            {
               finInput.close();
            }
            catch (Throwable thr)
            {
              
            }
         }
         throw ioExec;
      }
      FileUtils.copyStreamToFile(finInput, flDestination);
   }
   
   /**
    * Rename the file to temporaty name with given prefix
    * 
    * @param flFileToRename - file to rename
    * @param strPrefix - prefix to use
    * @throws IOException - error message
    */
   public static void renameToTemporaryName(
      File   flFileToRename,
      String strPrefix
   ) throws IOException
   {
      assert strPrefix != null : "Prefix cannot be null.";
      
      String       strParent;
      StringBuffer sbBuffer = new StringBuffer();
      File         flTemp;
      int          iIndex = 0;
      
      strParent = flFileToRename.getParent();
      // Generate new name for the file in a deterministic way
      do
      {
         iIndex++;
         sbBuffer.delete(0, sbBuffer.length());
         if (strParent != null) 
         {
            sbBuffer.append(strParent);
            sbBuffer.append(File.separatorChar);
         }
         
         sbBuffer.append(strPrefix);
         sbBuffer.append("_");
         sbBuffer.append(iIndex);
         sbBuffer.append("_");
         sbBuffer.append(flFileToRename.getName());
               
         flTemp = new File(sbBuffer.toString());
      }      
      while (flTemp.exists());
      
      // Now we should have unique name
      if (!flFileToRename.renameTo(flTemp))
      {
         throw new IOException("Cannot rename " + flFileToRename.getAbsolutePath()
                               + " to " + flTemp.getAbsolutePath());
      }
   }
   /** 
    * Delete all files and directories in directory but do not delete the
    * directory itself.
    * 
    * @param strDir - string that specifies directory to delete
    * @return boolean - sucess flag
    */
   public static boolean deleteDirectoryContent(
      String strDir
   )
   {
      return ((strDir != null) && (strDir.length() > 0)) 
              ? deleteDirectoryContent(new File(strDir)) : false;
   }
   /** 
    * Delete all files and directories in directory but do not delete the
    * directory itself.
    * 
    * @param fDir - directory to delete
    * @return boolean - sucess flag
    */
   public static boolean deleteDirectoryContent(
      File fDir
   )
   {
      boolean bRetval = false;
      if (fDir != null && fDir.isDirectory()) 
      {
         File[] files = fDir.listFiles();
   
         if (files != null)
         {
            bRetval = true;
            boolean dirDeleted;
            
            for (int index = 0; index < files.length; index++)
            {
               if (files[index].isDirectory())
               {
                  // TODO: Performance: Implement this as a queue where you add to
                  // the end and take from the beginning, it will be more efficient
                  // than the recursion
                  dirDeleted = deleteDirectoryContent(files[index]);
                  if (dirDeleted)
                  {
                     bRetval = bRetval && files[index].delete();
                  }
                  else
                  {
                     bRetval = false;
                  }
               }
               else
               {
                  bRetval = bRetval && files[index].delete();
               }
            }
         }
      }
      return bRetval;
   }
   /**
    * Deletes all files and subdirectories under the specified directory including 
    * the specified directory
    * 
    * @param strDir - string that specifies directory to be deleted
    * @return boolean - true if directory was successfully deleted
    */
   public static boolean deleteDir(
      String strDir
   ) 
   {
      return ((strDir != null) && (strDir.length() > 0)) 
                ? deleteDir(new File(strDir)) : false;
   }
   
   /**
    * Deletes all files and subdirectories under the specified directory including 
    * the specified directory
    * 
    * @param fDir - directory to be deleted
    * @return boolean - true if directory was successfully deleted
    */
   public static boolean deleteDir(
      File fDir
   ) 
   {
      boolean bRetval = false;
      if (fDir != null && fDir.exists())
      {
         bRetval = deleteDirectoryContent(fDir);
         if (bRetval)
         {
            bRetval = bRetval && fDir.delete();         
         }
      }
      return bRetval;
   }
   
   /**
    * Compare binary files. Both files must be files (not directories) and exist.
    * 
    * @param first  - first file
    * @param second - second file
    * @return boolean - true if files are binery equal
    * @throws IOException - error in function
    */
   public boolean isFileBinaryEqual(
      File first,
      File second
   ) throws IOException
   {
      // TODO: Test: Missing test
      boolean retval = false;
      
      if ((first.exists()) && (second.exists()) 
         && (first.isFile()) && (second.isFile()))
      {
         if (first.getCanonicalPath().equals(second.getCanonicalPath()))
         {
            retval = true;
         }
         else
         {
            FileInputStream firstInput = null;
            FileInputStream secondInput = null;
            BufferedInputStream bufFirstInput = null;
            BufferedInputStream bufSecondInput = null;
            try
            {            
               firstInput = new FileInputStream(first); 
               secondInput = new FileInputStream(second);
               bufFirstInput = new BufferedInputStream(firstInput, BUFFER_SIZE); 
               bufSecondInput = new BufferedInputStream(secondInput, BUFFER_SIZE);
   
               int firstByte;
               int secondByte;
               
               while (true)
               {
                  firstByte = bufFirstInput.read();
                  secondByte = bufSecondInput.read();
                  if (firstByte != secondByte)
                  {
                     break;
                  }
                  if ((firstByte < 0) && (secondByte < 0))
                  {
                     retval = true;
                     break;
                  }
               }
            }
            finally
            {
               try
               {
                  if (bufFirstInput != null)
                  {
                     bufFirstInput.close();
                  }
               }
               finally
               {
                  if (bufSecondInput != null)
                  {
                     bufSecondInput.close();
                  }
               }
            }
         }
      }
      
      return retval;
   }

      
   /**
    * Get path which represents temporary directory. It is guarantee that it 
    * ends with \ (or /).
    * 
    * @return String
    */
   public static String getTemporaryDirectory(
   )
   {
      return s_strTempDirectory;
   }
   
   /**
    * Copy any input stream to output file. Once the data will be copied
    * the stream will be closed.
    * 
    * @param input  - InputStream to copy from
    * @param output - File to copy to
    * @throws IOException - error in function
    * @throws OSSMultiException - double error in function
    */
   public static void copyStreamToFile(
      InputStream input,
      File        output
   ) throws IOException
   {
      FileOutputStream foutOutput = null;
      // open input file as stream safe - it can throw some IOException
      try
      {
         foutOutput = new FileOutputStream(output);
      }
      catch (IOException ioExec)
      {
         if (foutOutput != null)
         {
            try
            {
               foutOutput.close();
            }
            catch (IOException ioExec2)
            {
               
            }
         }            
         
         throw ioExec;
      }
      // all streams including os are closed in copyStreamToStream function 
      // in any case
      copyStreamToStream(input, foutOutput);
   }
   /**
    * Copy any input stream to output stream. Once the data will be copied
    * both streams will be closed.
    * 
    * @param input  - InputStream to copy from
    * @param output - OutputStream to copy to
    * @throws IOException - io error in function
    * @throws OSSMultiException - double error in function
    */
   public static void copyStreamToStream(
      InputStream input,
      OutputStream output
   ) throws IOException
   {
      InputStream is = null;
      OutputStream os = null;
      int                 ch;
      try
      {
         if (input instanceof BufferedInputStream)
         {
            is = input;
         }
         else
         {
            is = new BufferedInputStream(input);
         }
         if (output instanceof BufferedOutputStream)
         {
            os = output;
         }
         else
         {
            os = new BufferedOutputStream(output);
         }
   
         while ((ch = is.read()) != -1)
         {
            os.write(ch);
         }
         os.flush();
      }
      finally
      {
         IOException exec1 = null;
         IOException exec2 = null;
         try
         {
            // because this close can throw exception we do next close in 
            // finally statement
            if (os != null)
            {
               try
               {
                  os.close();
               }
               catch (IOException exec)
               {
                  exec1 = exec;
               }
            }
         }
         finally
         {
            if (is != null)
            {
               try
               {
                  is.close();
               }
               catch (IOException exec)
               {
                  exec2 = exec;
               }
            }
         }
         if ((exec1 != null) && (exec2 != null))
         {
           throw exec1;
         }
         else if (exec1 != null)
         {
            throw exec1;
         }
         else if (exec2 != null)
         {
            throw exec2;
         }
      }
   }
}





Program to empty a directory

   
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
import java.io.File;
/**
 * DANGEROUS Program to empty a directory.
 * 
 * @author Ian Darwin, Learning Tree, Course 471/478
 */
public class Empty {
  public static void main(String[] argv) {
    if (argv.length != 1) { // no progname in argv[0]
      System.err.println("usage: Empty dirname");
      System.exit(1);
    }
    File dir = new File(argv[0]);
    if (!dir.exists()) {
      System.out.println(argv[0] + " does not exist");
      return;
    }
    String[] info = dir.list();
    for (int i = 0; i < info.length; i++) {
      File n = new File(argv[0] + dir.separator + info[i]);
      if (!n.isFile()) // skip ., .., other directories too
        continue;
      System.out.println("removing " + n.getPath());
      if (!n.delete())
        System.err.println("Couldn"t remove " + n.getPath());
    }
  }
}





Program to remove files matching a name in a directory

   
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
import java.io.File;
/**
 * DANGEROUS Program to remove files matching a name in a directory
 * 
 * @author Ian Darwin, http://www.darwinsys.ru/
 */
public class KillFilesByName {
  public static void main(String[] argv) {
    if (argv.length != 2) {
      System.err.println("usage: KillFilesByName dirname pattern");
      System.exit(1);
    }
    File dir = new File(argv[0]);
    if (!dir.exists()) {
      System.out.println(argv[0] + " does not exist");
      return;
    }
    String patt = argv[1];
    String[] info = dir.list();
    for (int i = 0; i < info.length; i++) {
      File n = new File(argv[0] + dir.separator + info[i]);
      if (!n.isFile()) { // skip ., .., other directories, etc.
        continue;
      }
      if (info[i].indexOf(patt) == -1) { // name doesn"t match
        continue;
      }
      System.out.println("removing " + n.getPath());
      if (!n.delete())
        System.err.println("Couldn"t remove " + n.getPath());
    }
  }
}





Readonly Files

   
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002. All rights
 * reserved. Software written by Ian F. Darwin and others. $Id: LICENSE,v 1.8
 * 2004/02/09 03:33:38 ian Exp $
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer. 2. Redistributions in
 * binary form must reproduce the above copyright notice, this list of
 * conditions and the following disclaimer in the documentation and/or other
 * materials provided with the distribution.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS"" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee cup"
 * logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
import java.io.File;
import java.io.IOException;
public class ReadOnly {
  public static void main(String[] a) throws IOException {
    File f = new File("f");
    if (!f.createNewFile()) {
      System.out.println("Can"t create new file.");
      return;
    }
    if (!f.canWrite()) {
      System.out.println("Can"t write new file!");
      return;
    }
    if (!f.setReadOnly()) {
      System.out.println("Grrr! Can"t set file read-only.");
      return;
    }
    if (f.canWrite()) {
      System.out.println("Most immutable, captain!");
      System.out
          .println("But it still says canWrite() after setReadOnly");
      return;
    } else {
      System.out.println("Logical, captain!");
      System.out
          .println("canWrite() correctly returns false after setReadOnly");
    }
  }
}





Rename a file in Java

   
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
import java.io.File;
import java.io.IOException;
/**
 * Rename a file in Java
 * 
 * @author Ian F. Darwin, http://www.darwinsys.ru/
 * @version $Id: Rename.java,v 1.4 2004/02/09 03:33:47 ian Exp $
 */
public class Rename {
  public static void main(String[] argv) throws IOException {
    // Construct the file object. Does NOT create a file on disk!
    File f = new File("Rename.java~"); // backup of this source file.
    // Rename the backup file to "junk.dat"
    // Renaming requires a File object for the target.
    f.renameTo(new File("junk.dat"));
  }
}





Report on a file"s status in Java

   
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
import java.io.File;
import java.io.IOException;
import java.util.Date;
/**
 * Report on a file"s status in Java
 * 
 * @author Ian F. Darwin, http://www.darwinsys.ru/
 * @version $Id: FileStatus.java,v 1.6 2004/03/11 03:25:35 ian Exp $
 */
public class FileStatus {
  public static void main(String[] argv) throws IOException {
    // Ensure that a filename (or something) was given in argv[0]
    if (argv.length == 0) {
      System.err.println("Usage: FileStatus filename");
      System.exit(1);
    }
    for (int i = 0; i < argv.length; i++) {
      status(argv[i]);
    }
  }
  public static void status(String fileName) throws IOException {
    System.out.println("---" + fileName + "---");
    // Construct a File object for the given file.
    File f = new File(fileName);
    // See if it actually exists
    if (!f.exists()) {
      System.out.println("file not found");
      System.out.println(); // Blank line
      return;
    }
    // Print full name
    System.out.println("Canonical name " + f.getCanonicalPath());
    // Print parent directory if possible
    String p = f.getParent();
    if (p != null) {
      System.out.println("Parent directory: " + p);
    }
    // Check if the file is readable
    if (f.canRead()) {
      System.out.println("File is readable.");
    }
    // Check if the file is writable
    if (f.canWrite()) {
      System.out.println("File is writable.");
    }
    // Report on the modification time.
    Date d = new Date();
    d.setTime(f.lastModified());
    System.out.println("Last modified " + d);
    // See if file, directory, or other. If file, print size.
    if (f.isFile()) {
      // Report on the file"s size
      System.out.println("File size is " + f.length() + " bytes.");
    } else if (f.isDirectory()) {
      System.out.println("It"s a directory");
    } else {
      System.out.println("I dunno! Neither a file nor a directory!");
    }
    System.out.println(); // blank line between entries
  }
}





Return readable file size with selected value measure

 
/**
 * Methods for files and folders treatment.
 * 
 * @author Cyril JOUI
 */
public final class FileUtil {
  /**
   * @param fileSize
   *          file size to convert and format to string.
   * @return return readable file size with selected value measure
   */
  public static String getReadableFileSize(final long fileSize) {
    double l = fileSize * 1D;
    String s = "";
    if (l < 1000) {
      s = fileSize + " B";
    } else {
      l = l / 1024D;
      if (l < 1000) {
        s = l + " KB";
      } else {
        l = l / 1024D;
        if (l < 1000) {
          s = l + " MB";
        } else {
          l = l / 1024D;
          s = l + " GB";
        }
      }
    }
    return (s.length() - s.indexOf(".") <= 3 ? s : s.substring(0, s.indexOf(".") + 3))
        + s.substring(s.indexOf(" "), s.length());
  }
}





Simple directory lister

   
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
/**
 * Simple directory lister.
 * 
 * @author Ian Darwin, http://www.darwinsys.ru/
 * @version $Id: Ls.java,v 1.3 2004/02/09 03:33:47 ian Exp $
 */
public class Ls {
  public static void main(String argh_my_aching_fingers[]) {
    String[] dir = new java.io.File(".").list(); // Get list of names
    java.util.Arrays.sort(dir); // Sort it (Data Structuring chapter))
    for (int i = 0; i < dir.length; i++)
      System.out.println(dir[i]); // Print the list
  }
}





TeePrintStream tees all PrintStream operations into a file, rather like the UNIX tee(1) command

   
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
/**
 * TeePrintStream tees all PrintStream operations into a file, rather like the
 * UNIX tee(1) command. It is a PrintStream subclass. The expected usage would
 * be something like the following:
 * 
 * <PRE>
 * 
 * ... TeePrintStream ts = new TeePrintStream(System.err, "err.log");
 * System.setErr(ts); // ...lots of code that occasionally writes to
 * System.err... ts.close(); ...
 * 
 * <PRE>
 * 
 * <P>
 * I only override Constructors, the write(), check() and close() methods, since
 * any of the print() or println() methods must go through these. Thanks to
 * Svante Karlsson for help formulating this.
 * 
 * @author Ian F. Darwin, http://www.darwinsys.ru/
 * @version $Id: TeePrintStream.java,v 1.5 2004/02/08 23:57:29 ian Exp $
 */
public class TeePrintStream extends PrintStream {
  protected PrintStream parent;
  protected String fileName;
  /** A simple test case. */
  public static void main(String[] args) throws IOException {
    TeePrintStream ts = new TeePrintStream(System.err, "err.log", true);
    System.setErr(ts);
    System.err.println("An imitation error message");
    ts.close();
  }
  /**
   * Construct a TeePrintStream given an existing PrintStream, an opened
   * OutputStream, and a boolean to control auto-flush. This is the main
   * constructor, to which others delegate via "this".
   */
  public TeePrintStream(PrintStream orig, OutputStream os, boolean flush)
      throws IOException {
    super(os, true);
    fileName = "(opened Stream)";
    parent = orig;
  }
  /**
   * Construct a TeePrintStream given an existing PrintStream and an opened
   * OutputStream.
   */
  public TeePrintStream(PrintStream orig, OutputStream os) throws IOException {
    this(orig, os, true);
  }
  /*
   * Construct a TeePrintStream given an existing Stream and a filename.
   */
  public TeePrintStream(PrintStream os, String fn) throws IOException {
    this(os, fn, true);
  }
  /*
   * Construct a TeePrintStream given an existing Stream, a filename, and a
   * boolean to control the flush operation.
   */
  public TeePrintStream(PrintStream orig, String fn, boolean flush)
      throws IOException {
    this(orig, new FileOutputStream(fn), flush);
  }
  /** Return true if either stream has an error. */
  public boolean checkError() {
    return parent.checkError() || super.checkError();
  }
  /** override write(). This is the actual "tee" operation. */
  public void write(int x) {
    parent.write(x); // "write once;
    super.write(x); // write somewhere else."
  }
  /** override write(). This is the actual "tee" operation. */
  public void write(byte[] x, int o, int l) {
    parent.write(x, o, l); // "write once;
    super.write(x, o, l); // write somewhere else."
  }
  /** Close both streams. */
  public void close() {
    parent.close();
    super.close();
  }
  /** Flush both streams. */
  public void flush() {
    parent.flush();
    super.flush();
  }
}





Touch: set File Last Modified Time

   
import java.io.File;
import java.util.Date;
class Touch {
  public static void main(String[] args) {
    String[] names = new File(".").list();
    Date current = new Date();
    for (int i = 0; i < names.length; i++) {
      File f = new File(names[i]);
      f.setLastModified(current.getTime());
    }
  }
}





Undent - remove leading spaces

   
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
import java.io.*;
/** Undent - remove leading spaces
 * @author Ian F. Darwin, http://www.darwinsys.ru/
 * @version $Id: Undent.java,v 1.5 2004/02/08 23:57:09 ian Exp $
 */
public class Undent {
  //+
  /** the default number of spaces to remove. */
  int nSpaces = 2;
  //-
    public static void main(String[] av) {
        Undent c = new Undent();
        if (av.length == 0)
            c.process(new BufferedReader(
        new InputStreamReader(System.in)));
    else for (int i=0; i<av.length; i++) {
      try {
        c.process(new BufferedReader(new FileReader(av[i])));
      } catch (FileNotFoundException e) {
        System.err.println(e);
      }
        }
    }

    /** undent one file, given an open BufferedReader.
   * Undent by removing UP TO "nSpaces" leading spaces.
   */
    public void process(BufferedReader is) {
    //+
    // GRRR THIS DOES NOT QUITE WORK - FIX -- Ian
        try {
            String inputLine;
            while ((inputLine = is.readLine()) != null) {
        int i;
        for (i=0; i<nSpaces; i++) {
          if (!Character.isWhitespace(inputLine.charAt(i)))
            break;
        }
                System.out.println(inputLine.substring(i));
            }
            is.close();
    //-
        } catch (IOException e) {
            System.out.println("IOException: " + e);
        }
    }
  //-
}





Word Count

   
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Map;
import java.util.StringTokenizer;
public class WordCount {
  static final Integer ONE = new Integer(1);
  public static void main(String args[]) throws IOException {
    Hashtable map = new Hashtable();
    FileReader fr = new FileReader(args[0]);
    BufferedReader br = new BufferedReader(fr);
    String line;
    while ((line = br.readLine()) != null) {
      processLine(line, map);
    }
    Enumeration e = map.keys();
    while (e.hasMoreElements()) {
      String key = (String) e.nextElement();
      System.out.println(key + " : " + map.get(key));
    }
  }
  static void processLine(String line, Map map) {
    StringTokenizer st = new StringTokenizer(line);
    while (st.hasMoreTokens()) {
      addWord(map, st.nextToken());
    }
  }
  static void addWord(Map map, String word) {
    Object obj = map.get(word);
    if (obj == null) {
      map.put(word, ONE);
    } else {
      int i = ((Integer) obj).intValue() + 1;
      map.put(word, new Integer(i));
    }
  }
}