Java/File Input Output/Directory
Содержание
- 1 A standalone program that deletes a specified file or directory
- 2 Calculate directory size
- 3 Check if a directory is not empty
- 4 Copying a Directory: Copies files under srcDir to dstDir, if dstDir does not exist, it will be created.
- 5 Count files in a directory (including files in all subdirectories)
- 6 Create a directories recursively
- 7 Create a unique directory within a directory "root"
- 8 Create directory
- 9 Create directory along with required nonexistent parent directories
- 10 Create directory tree (nested/cascade folders)
- 11 Creates and displays a window containing a list of files and sub-directories in a specified directory
- 12 Creates a new and empty directory in the default temp directory using the given prefix.
- 13 Creates a new empty temporary directory.
- 14 Delete a non-empty directory: Deletes all files and subdirectories under dir.
- 15 Delete directory recursively
- 16 Determining If Two Filename Paths Refer to the Same File
- 17 Directory Walker
- 18 Display a file system in a JTree view
- 19 File Table HTML
- 20 File Tree Demo
- 21 Get current directory
- 22 Get Files Recurse
- 23 Get Last modification time of a file or directory
- 24 Get name of parent directory
- 25 Get name of specified file or directory
- 26 List contents of a directory
- 27 Listing the Files or Subdirectories in a Directory
- 28 Listing the File System Roots
- 29 Reading and Printing a Directory Hierarchy
- 30 Recursive directory deletion
- 31 Recursively search a directory tree
- 32 Recursivly delete directory
- 33 Searches through the directory tree
- 34 Set last modified time of a file or directory
- 35 Starts at the directory given and tests to see whether it is empty
- 36 The Directory Listing Application
- 37 Traversing all files and directories under dir
- 38 Traversing only directories under dir
- 39 Traversing only files under dir
- 40 use list( ) to examine the contents of a directory:
- 41 Utility methods for handling files and directories
A standalone program that deletes a specified file or directory
/*
* 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.
*/
import java.io.File;
/**
* This class is a static method delete() and a standalone program that deletes
* a specified file or directory.
*/
public class Delete {
/**
* This is the main() method of the standalone program. After checking it
* arguments, it invokes the Delete.delete() method to do the deletion
*/
public static void main(String[] args) {
if (args.length != 1) { // Check command-line arguments
System.err.println("Usage: java Delete <file or directory>");
System.exit(0);
}
// Call delete() and display any error messages it throws.
try {
delete(args[0]);
} catch (IllegalArgumentException e) {
System.err.println(e.getMessage());
}
}
/**
* The static method that does the deletion. Invoked by main(), and designed
* for use by other programs as well. It first makes sure that the specified
* file or directory is deleteable before attempting to delete it. If there is
* a problem, it throws an IllegalArgumentException.
*/
public static void delete(String filename) {
// Create 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())
fail("Delete: no such file or directory: " + filename);
if (!f.canWrite())
fail("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)
fail("Delete: directory not empty: " + filename);
}
// If we passed all the tests, then attempt to delete it
boolean success = f.delete();
// And throw an exception if it didn"t work for some (unknown) reason.
// For example, because of a bug with Java 1.1.1 on Linux,
// directory deletion always fails
if (!success)
fail("Delete: deletion failed");
}
/** A convenience method to throw an exception */
protected static void fail(String msg) throws IllegalArgumentException {
throw new IllegalArgumentException(msg);
}
}
Calculate directory size
import java.io.File;
import org.apache.rumons.io.FileUtils;
public class Main {
public static void main(String[] args) {
long size = FileUtils.sizeOfDirectory(new File("C:/Windows"));
System.out.println("Size: " + size + " bytes");
}
}
Check if a directory is not empty
import java.io.File;
public class Main {
public static void main(String[] args) {
File file = new File("/data");
if (file.isDirectory()) {
String[] files = file.list();
if (files.length > 0) {
System.out.println("The " + file.getPath() + " is not empty!");
}
}
}
}
Copying a Directory: Copies files under srcDir to dstDir, if dstDir does not exist, it will be created.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class Main {
public static void main(String[] argv) throws Exception {
copyDirectory(new File("c:\\"), new File("d:\\")) ;
}
public static void copyDirectory(File srcDir, File dstDir) throws IOException {
if (srcDir.isDirectory()) {
if (!dstDir.exists()) {
dstDir.mkdir();
}
String[] children = srcDir.list();
for (int i = 0; i < children.length; i++) {
copyDirectory(new File(srcDir, children[i]), new File(dstDir, children[i]));
}
} else {
copyFile(srcDir, dstDir);
}
}
public static void copyFile(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
}
Count files in a directory (including files in all subdirectories)
import java.io.File;
import java.io.IOException;
public class Utils {
/**
* Count files in a directory (including files in all subdirectories)
* @param directory the directory to start in
* @return the total number of files
*/
public static int countFilesInDirectory(File directory) {
int count = 0;
for (File file : directory.listFiles()) {
if (file.isFile()) {
count++;
}
if (file.isDirectory()) {
count += countFilesInDirectory(file);
}
}
return count;
}
}
Create a directories recursively
import java.io.File;
public class Main {
public static void main(String[] args) {
String directories = "D:\\a\\b\\c\\d\\e\\f\\g\\h\\i";
File file = new File(directories);
boolean result = file.mkdirs();
System.out.println("Status = " + result);
}
}
Create a unique directory within a directory "root"
import java.io.File;
import java.io.IOException;
public class Utils {
/**
* Create a unique directory within a directory "root"
*
* @param rootDir
* @param seed
* @return unique directory
* @throws IOException
*/
public static synchronized File createUniqueDirectory(File rootDir, String seed) throws IOException {
int index = seed.lastIndexOf(".");
if (index > 0) {
seed = seed.substring(0, index);
}
File result = null;
int count = 0;
while (result == null) {
String name = seed + "." + count + ".tmp";
File file = new File(rootDir, name);
if (!file.exists()) {
file.mkdirs();
result = file;
}
count++;
}
return result;
}
}
Create directory
import java.io.File;
public class Main {
public static void main(String[] args) {
File dir = new File("C:/FileIO/DemoDirectory");
boolean isDirectoryCreated = dir.mkdir();
if (isDirectoryCreated) {
System.out.println("successfully");
} else {
System.out.println("not");
}
}
}
Create directory along with required nonexistent parent directories
import java.io.File;
public class Main {
public static void main(String[] args) {
File dir = new File("C:/1/Parent1/Parent2/DemoDir");
boolean isDirCreated = dir.mkdirs();
if (isDirCreated)
System.out.println("created");
else
System.out.println("Failed");
}
}
Create directory tree (nested/cascade folders)
import java.io.File;
public class MainClass{
public static void main(String[] a){
new File("c:\\a\\b\\c\\d\\e").mkdirs();
}
}
Creates and displays a window containing a list of files and sub-directories in a specified directory
/*
* 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.
*/
import java.awt.Button;
import java.awt.FileDialog;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.List;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.text.DateFormat;
/**
* This class creates and displays a window containing a list of files and
* sub-directories in a specified directory. Clicking on an entry in the list
* displays more information about it. Double-clicking on an entry displays it,
* if a file, or lists it if a directory. An optionally-specified FilenameFilter
* filters the displayed list.
*/
public class FileLister extends Frame implements ActionListener, ItemListener {
private List list; // To display the directory contents in
private TextField details; // To display detail info in.
private Panel buttons; // Holds the buttons
private Button up, close; // The Up and Close buttons
private File currentDir; // The directory currently listed
private FilenameFilter filter; // An optional filter for the directory
private String[] files; // The directory contents
private DateFormat dateFormatter = // To display dates and time correctly
DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
/**
* Constructor: create the GUI, and list the initial directory.
*/
public FileLister(String directory, FilenameFilter filter) {
super("File Lister"); // Create the window
this.filter = filter; // Save the filter, if any
// Destroy the window when the user requests it
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
}
});
list = new List(12, false); // Set up the list
list.setFont(new Font("MonoSpaced", Font.PLAIN, 14));
list.addActionListener(this);
list.addItemListener(this);
details = new TextField(); // Set up the details area
details.setFont(new Font("MonoSpaced", Font.PLAIN, 12));
details.setEditable(false);
buttons = new Panel(); // Set up the button box
buttons.setLayout(new FlowLayout(FlowLayout.RIGHT, 15, 5));
buttons.setFont(new Font("SansSerif", Font.BOLD, 14));
up = new Button("Up a Directory"); // Set up the two buttons
close = new Button("Close");
up.addActionListener(this);
close.addActionListener(this);
buttons.add(up); // Add buttons to button box
buttons.add(close);
this.add(list, "Center"); // Add stuff to the window
this.add(details, "North");
this.add(buttons, "South");
this.setSize(500, 350);
listDirectory(directory); // And now list initial directory.
}
/**
* This method uses the list() method to get all entries in a directory and
* then displays them in the List component.
*/
public void listDirectory(String directory) {
// Convert the string to a File object, and check that the dir exists
File dir = new File(directory);
if (!dir.isDirectory())
throw new IllegalArgumentException("FileLister: no such directory");
// Get the (filtered) directory entries
files = dir.list(filter);
// Sort the list of filenames.
java.util.Arrays.sort(files);
// Remove any old entries in the list, and add the new ones
list.removeAll();
list.add("[Up to Parent Directory]"); // A special case entry
for (int i = 0; i < files.length; i++)
list.add(files[i]);
// Display directory name in window titlebar and in the details box
this.setTitle(directory);
details.setText(directory);
// Remember this directory for later.
currentDir = dir;
}
/**
* This ItemListener method uses various File methods to obtain information
* about a file or directory. Then it displays that info.
*/
public void itemStateChanged(ItemEvent e) {
int i = list.getSelectedIndex() - 1; // minus 1 for Up To Parent entry
if (i < 0)
return;
String filename = files[i]; // Get the selected entry
File f = new File(currentDir, filename); // Convert to a File
if (!f.exists()) // Confirm that it exists
throw new IllegalArgumentException("FileLister: " + "no such file or directory");
// Get the details about the file or directory, concatenate to a string
String info = filename;
if (f.isDirectory())
info += File.separator;
info += " " + f.length() + " bytes ";
info += dateFormatter.format(new java.util.Date(f.lastModified()));
if (f.canRead())
info += " Read";
if (f.canWrite())
info += " Write";
// And display the details string
details.setText(info);
}
/**
* This ActionListener method is invoked when the user double-clicks on an
* entry or clicks on one of the buttons. If they double-click on a file,
* create a FileViewer to display that file. If they double-click on a
* directory, call the listDirectory() method to display that directory
*/
public void actionPerformed(ActionEvent e) {
if (e.getSource() == close)
this.dispose();
else if (e.getSource() == up) {
up();
} else if (e.getSource() == list) { // Double click on an item
int i = list.getSelectedIndex(); // Check which item
if (i == 0)
up(); // Handle first Up To Parent item
else { // Otherwise, get filename
String name = files[i - 1];
File f = new File(currentDir, name); // Convert to a File
String fullname = f.getAbsolutePath();
if (f.isDirectory())
listDirectory(fullname); // List dir
else
new FileViewer(fullname).show(); // display file
}
}
}
/** A convenience method to display the contents of the parent directory */
protected void up() {
String parent = currentDir.getParent();
if (parent == null)
return;
listDirectory(parent);
}
/** A convenience method used by main() */
public static void usage() {
System.out.println("Usage: java FileLister [directory_name] " + "[-e file_extension]");
System.exit(0);
}
/**
* A main() method so FileLister can be run standalone. Parse command line
* arguments and create the FileLister object. If an extension is specified,
* create a FilenameFilter for it. If no directory is specified, use the
* current directory.
*/
public static void main(String args[]) throws IOException {
FileLister f;
FilenameFilter filter = null; // The filter, if any
String directory = null; // The specified dir, or the current dir
// Loop through args array, parsing arguments
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-e")) {
if (++i >= args.length)
usage();
final String suffix = args[i]; // final for anon. class below
// This class is a simple FilenameFilter. It defines the
// accept() method required to determine whether a specified
// file should be listed. A file will be listed if its name
// ends with the specified extension, or if it is a directory.
filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
if (name.endsWith(suffix))
return true;
else
return (new File(dir, name)).isDirectory();
}
};
} else {
if (directory != null)
usage(); // If already specified, fail.
else
directory = args[i];
}
}
// if no directory specified, use the current directory
if (directory == null)
directory = System.getProperty("user.dir");
// Create the FileLister object, with directory and filter specified.
f = new FileLister(directory, filter);
// Arrange for the application to exit when the window is closed
f.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) {
System.exit(0);
}
});
// Finally, pop the window up up.
f.show();
}
}
class FileViewer extends Frame implements ActionListener {
String directory; // The default directory to display in the FileDialog
TextArea textarea; // The area to display the file contents into
/** Convenience constructor: file viewer starts out blank */
public FileViewer() {
this(null, null);
}
/** Convenience constructor: display file from current directory */
public FileViewer(String filename) {
this(null, filename);
}
/**
* The real constructor. Create a FileViewer object to display the specified
* file from the specified directory
*/
public FileViewer(String directory, String filename) {
super(); // Create the frame
// Destroy the window when the user requests it
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
}
});
// Create a TextArea to display the contents of the file in
textarea = new TextArea("", 24, 80);
textarea.setFont(new Font("MonoSpaced", Font.PLAIN, 12));
textarea.setEditable(false);
this.add("Center", textarea);
// Create a bottom panel to hold a couple of buttons in
Panel p = new Panel();
p.setLayout(new FlowLayout(FlowLayout.RIGHT, 10, 5));
this.add(p, "South");
// Create the buttons and arrange to handle button clicks
Font font = new Font("SansSerif", Font.BOLD, 14);
Button openfile = new Button("Open File");
Button close = new Button("Close");
openfile.addActionListener(this);
openfile.setActionCommand("open");
openfile.setFont(font);
close.addActionListener(this);
close.setActionCommand("close");
close.setFont(font);
p.add(openfile);
p.add(close);
this.pack();
// Figure out the directory, from filename or current dir, if necessary
if (directory == null) {
File f;
if ((filename != null) && (f = new File(filename)).isAbsolute()) {
directory = f.getParent();
filename = f.getName();
} else
directory = System.getProperty("user.dir");
}
this.directory = directory; // Remember the directory, for FileDialog
setFile(directory, filename); // Now load and display the file
}
/**
* Load and display the specified file from the specified directory
*/
public void setFile(String directory, String filename) {
if ((filename == null) || (filename.length() == 0))
return;
File f;
FileReader in = null;
// Read and display the file contents. Since we"re reading text, we
// use a FileReader instead of a FileInputStream.
try {
f = new File(directory, filename); // Create a file object
in = new FileReader(f); // And a char stream to read it
char[] buffer = new char[4096]; // Read 4K characters at a time
int len; // How many chars read each time
textarea.setText(""); // Clear the text area
while ((len = in.read(buffer)) != -1) { // Read a batch of chars
String s = new String(buffer, 0, len); // Convert to a string
textarea.append(s); // And display them
}
this.setTitle("FileViewer: " + filename); // Set the window title
textarea.setCaretPosition(0); // Go to start of file
}
// Display messages if something goes wrong
catch (IOException e) {
textarea.setText(e.getClass().getName() + ": " + e.getMessage());
this.setTitle("FileViewer: " + filename + ": I/O Exception");
}
// Always be sure to close the input stream!
finally {
try {
if (in != null)
in.close();
} catch (IOException e) {
}
}
}
/**
* Handle button clicks
*/
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if (cmd.equals("open")) { // If user clicked "Open" button
// Create a file dialog box to prompt for a new file to display
FileDialog f = new FileDialog(this, "Open File", FileDialog.LOAD);
f.setDirectory(directory); // Set the default directory
// Display the dialog and wait for the user"s response
f.show();
directory = f.getDirectory(); // Remember new default directory
setFile(directory, f.getFile()); // Load and display selection
f.dispose(); // Get rid of the dialog box
} else if (cmd.equals("close")) // If user clicked "Close" button
this.dispose(); // then close the window
}
/**
* The FileViewer can be used by other classes, or it can be used standalone
* with this main() method.
*/
static public void main(String[] args) throws IOException {
// Create a FileViewer object
Frame f = new FileViewer((args.length == 1) ? args[0] : null);
// Arrange to exit when the FileViewer window closes
f.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) {
System.exit(0);
}
});
// And pop the window up
f.show();
}
}
Creates a new and empty directory in the default temp directory using the given prefix.
/*
* Copyright Aduna (http://www.aduna-software.ru/) (c) 1997-2006.
*
* Licensed under the Aduna BSD-style license.
*/
import java.io.File;
import java.io.IOException;
public class Main {
/**
* Creates a new and empty directory in the default temp directory using the
* given prefix. This methods uses {@link File#createTempFile} to create a
* new tmp file, deletes it and creates a directory for it instead.
*
* @param prefix The prefix string to be used in generating the diretory"s
* name; must be at least three characters long.
* @return A newly-created empty directory.
* @throws IOException If no directory could be created.
*/
public static File createTempDir(String prefix)
throws IOException
{
String tmpDirStr = System.getProperty("java.io.tmpdir");
if (tmpDirStr == null) {
throw new IOException(
"System property "java.io.tmpdir" does not specify a tmp dir");
}
File tmpDir = new File(tmpDirStr);
if (!tmpDir.exists()) {
boolean created = tmpDir.mkdirs();
if (!created) {
throw new IOException("Unable to create tmp dir " + tmpDir);
}
}
File resultDir = null;
int suffix = (int)System.currentTimeMillis();
int failureCount = 0;
do {
resultDir = new File(tmpDir, prefix + suffix % 10000);
suffix++;
failureCount++;
}
while (resultDir.exists() && failureCount < 50);
if (resultDir.exists()) {
throw new IOException(failureCount +
" attempts to generate a non-existent directory name failed, giving up");
}
boolean created = resultDir.mkdir();
if (!created) {
throw new IOException("Failed to create tmp directory");
}
return resultDir;
}
}
Creates a new empty temporary directory.
import java.io.File;
import java.io.IOException;
public class Utils {
/**
* Creates a new empty temporary directory.
*/
public static File createTmpDir() throws IOException {
// create a temporary directory
File tmpFile = File.createTempFile("tmp","tmp",new File("."));
tmpFile.delete();
tmpFile.mkdir();
return tmpFile;
}
}
Delete a non-empty directory: Deletes all files and subdirectories under dir.
import java.io.File;
public class Main {
public static void main(String[] argv) throws Exception {
deleteDir(new File("c:\\temp"));
}
public static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
return dir.delete();
}
}
Delete directory recursively
import org.apache.rumons.io.FileUtils;
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws Exception {
File directory = new File("c:\\");
FileUtils.deleteDirectory(directory);
}
}
Determining If Two Filename Paths Refer to the Same File
import java.io.File;
public class Main {
public static void main(String[] argv) throws Exception {
File file1 = new File("./filename");
File file2 = new File("filename");
System.out.println(file1.equals(file2));
file1 = file1.getCanonicalFile();
file2 = file2.getCanonicalFile();
System.out.println(file1.equals(file2));
}
}
Directory Walker
/**
* Title: NoUnit - Identify Classes that are not being unit Tested
*
* Copyright (C) 2001 Paul Browne , FirstPartners.net
*
*
* 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.
*
* 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.
*
* @author Paul Browne
* @version 0.6
*/
import java.io.*;
import java.util.*;
/**
* "Walks" the directory structure and returns files found (including those in sub folders)
*/
public class DirectoryWalker {
/**
* Get all the files in the starting directory (and sub dirs)
* No filter
* @param startingDirectory
* @return filesFound (as HashSet)
* @exception java.io.IOException
*/
public static HashSet getFiles(String startingDirectory)
throws java.io.IOException {
return getFiles(startingDirectory,null);
}
/**
* Get all the files in the starting directory (but NOT sub dirs)
* returns only files ending this the filename
* @param startingDirectory
* @return filesFound (as HashSet)
* @exception java.io.IOException
*/
public static HashSet getFiles(String startingDirectory,String endFileName)
throws java.io.IOException{
//Local Variables
String tmpFullFile;
File startDir = new File(startingDirectory);
File tmpFile;
String[] thisDirContents;
HashSet filesFound = new HashSet();
//Check that this is a valid directory
if (!startDir.isDirectory()) {
throw new java.io.IOException(startingDirectory+" was not a valid directory");
}
//Get the contents of the current directory
thisDirContents = startDir.list();
if (thisDirContents!=null) {
//Now loop through , apply filter , or adding them to list of sub dirs
for (int a=0; a<thisDirContents.length;a++) {
//Get Handle to (full) file (inc path)
tmpFullFile=FileUtil.rubineFileAndDirectory(thisDirContents[a],
startingDirectory);
tmpFile = new File(tmpFullFile);
//Add to Output if file
if (tmpFile.isFile()) {
//Add if file
if ((endFileName==null)||
(tmpFullFile.endsWith(endFileName))){
filesFound.add(tmpFullFile);
}
}
}
}
return filesFound;
}
/**
* Get all the Directories in the starting directory (and sub dirs)
* returns only files ending this the filename
* @param startingDirectory
* @return filesFound (as HashSet)
* @exception java.io.IOException
*/
public static HashSet getDirs(String startingDirectory)
throws java.io.IOException{
//Local Variables
String tmpFullFile;
String tmpSubDir;
File startDir = new File(startingDirectory);
File tmpFile;
String[] thisDirContents;
HashSet dirsFound = new HashSet();
HashSet subDirFilesFound;
//Check that this is a valid directory
if (!startDir.isDirectory()) {
throw new java.io.IOException(startingDirectory+" was not a valid directory");
}
//Add the current directory to the output list
dirsFound.add(startingDirectory);
//Get the contents of the current directory
thisDirContents = startDir.list();
if (thisDirContents!=null) {
//Now loop through , apply filter , or adding them to list of sub dirs
for (int a=0; a<thisDirContents.length;a++) {
//Get Handle to (full) file (inc path)
tmpFullFile=FileUtil.rubineFileAndDirectory(thisDirContents[a],
startingDirectory);
tmpFile = new File(tmpFullFile);
//We"re only interested in directories
if (tmpFile.isDirectory()) {
//Add this to the directory list
dirsFound.add(tmpFullFile);
//Now Do Recursive Call (to this method)if Directory
tmpSubDir = FileUtil.rubineFileAndDirectory(thisDirContents[a],
startingDirectory);
subDirFilesFound = DirectoryWalker.getDirs(tmpSubDir);
dirsFound.addAll(subDirFilesFound);
}
}
}
return dirsFound;
}
}
/**
* Title: NoUnit - Identify Classes that are not being unit Tested
*
* Copyright (C) 2001 Paul Browne , FirstPartners.net
*
*
* 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.
*
* 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.
*
* @author Paul Browne
* @version 0.6
*/
/**
* Class to manage files within a directory structure<BR>
*/
class FileUtil {
/**
* Combines file and directory , using path delimeters
* @param fileName
* @param filePath
* @return combinedPath
*/
public static String combineFileAndDirectory (String fileName , String filePath) {
String combinedPath = null;
//Checking incoming values
if ((fileName==null)||(filePath==null)) {
return null;
}
if ((fileName.equals(""))||(filePath.equals(""))) {
return null;
}
//Add character to end of Directory if required
if ((filePath.endsWith("\\")||(filePath.endsWith("/")))) {
//nothing
} else {
//add character
filePath = filePath + String.valueOf(File.separatorChar);
}
//Add two together
combinedPath = filePath+fileName;
return combinedPath;
}
}
Display a file system in a JTree view
/*
* 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.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.io.File;
import java.util.Collections;
import java.util.Vector;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
/**
* Display a file system in a JTree view
*
* @version $Id: FileTree.java,v 1.9 2004/02/23 03:39:22 ian Exp $
* @author Ian Darwin
*/
public class FileTree extends JPanel {
/** Construct a FileTree */
public FileTree(File dir) {
setLayout(new BorderLayout());
// Make a tree list with all the nodes, and make it a JTree
JTree tree = new JTree(addNodes(null, dir));
// Add a listener
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) e
.getPath().getLastPathComponent();
System.out.println("You selected " + node);
}
});
// Lastly, put the JTree into a JScrollPane.
JScrollPane scrollpane = new JScrollPane();
scrollpane.getViewport().add(tree);
add(BorderLayout.CENTER, scrollpane);
}
/** Add nodes from under "dir" into curTop. Highly recursive. */
DefaultMutableTreeNode addNodes(DefaultMutableTreeNode curTop, File dir) {
String curPath = dir.getPath();
DefaultMutableTreeNode curDir = new DefaultMutableTreeNode(curPath);
if (curTop != null) { // should only be null at root
curTop.add(curDir);
}
Vector ol = new Vector();
String[] tmp = dir.list();
for (int i = 0; i < tmp.length; i++)
ol.addElement(tmp[i]);
Collections.sort(ol, String.CASE_INSENSITIVE_ORDER);
File f;
Vector files = new Vector();
// Make two passes, one for Dirs and one for Files. This is #1.
for (int i = 0; i < ol.size(); i++) {
String thisObject = (String) ol.elementAt(i);
String newPath;
if (curPath.equals("."))
newPath = thisObject;
else
newPath = curPath + File.separator + thisObject;
if ((f = new File(newPath)).isDirectory())
addNodes(curDir, f);
else
files.addElement(thisObject);
}
// Pass two: for files.
for (int fnum = 0; fnum < files.size(); fnum++)
curDir.add(new DefaultMutableTreeNode(files.elementAt(fnum)));
return curDir;
}
public Dimension getMinimumSize() {
return new Dimension(200, 400);
}
public Dimension getPreferredSize() {
return new Dimension(200, 400);
}
/** Main: make a Frame, add a FileTree */
public static void main(String[] av) {
JFrame frame = new JFrame("FileTree");
frame.setForeground(Color.black);
frame.setBackground(Color.lightGray);
Container cp = frame.getContentPane();
if (av.length == 0) {
cp.add(new FileTree(new File(".")));
} else {
cp.setLayout(new BoxLayout(cp, BoxLayout.X_AXIS));
for (int i = 0; i < av.length; i++)
cp.add(new FileTree(new File(av[i])));
}
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
File Table HTML
/*
* This example is from the book "Java Foundation Classes in a Nutshell".
* Written by David Flanagan. Copyright (c) 1999 by O"Reilly & Associates.
* You may distribute this source code for non-commercial purposes only.
* You may study, modify, and use this example for any purpose, as long as
* this notice is retained. Note that this example is provided "as is",
* WITHOUT WARRANTY of any kind either expressed or implied.
*/
import javax.swing.*;
import javax.swing.event.*;
import java.io.*;
import java.util.Date;
/**
* This class implements a simple directory browser using the HTML
* display capabilities of the JEditorPane component.
**/
public class FileTableHTML {
public static void main(String[] args) throws IOException {
// Get the name of the directory to display
String dirname = (args.length>0)?args[0]:System.getProperty("user.home");
// Create something to display it in.
final JEditorPane editor = new JEditorPane();
editor.setEditable(false); // we"re browsing not editing
editor.setContentType("text/html"); // must specify HTML text
editor.setText(makeHTMLTable(dirname)); // specify the text to display
// Set up the JEditorPane to handle clicks on hyperlinks
editor.addHyperlinkListener(new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent e) {
// Handle clicks; ignore mouseovers and other link-related events
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
// Get the HREF of the link and display it.
editor.setText(makeHTMLTable(e.getDescription()));
}
}
});
// Put the JEditorPane in a scrolling window and display it.
JFrame frame = new JFrame("FileTableHTML");
frame.getContentPane().add(new JScrollPane(editor));
frame.setSize(650, 500);
frame.setVisible(true);
}
// This method returns an HTML table representing the specified directory
public static String makeHTMLTable(String dirname) {
// Look up the contents of the directory
File dir = new File(dirname);
String[] entries = dir.list();
// Set up an output stream we can print the table to.
// This is easier than concatenating strings all the time.
StringWriter sout = new StringWriter();
PrintWriter out = new PrintWriter(sout);
// Print the directory name as the page title
out.println("<H1>" + dirname + "</H1>");
// Print an "up" link, unless we"re already at the root
String parent = dir.getParent();
if ((parent != null) && (parent.length() > 0))
out.println("" :
entries[i]) +
"</TD><TD>" + f.length() +
"</TD><TD>" + new Date(f.lastModified()) +
"</TD><TD align=center>" + (f.canRead()?"x":" ") +
"</TD><TD align=center>" + (f.canWrite()?"x":" ") +
"</TD></TR>");
}
out.println("</TABLE>");
out.close();
// Get the string of HTML from the StringWriter and return it.
return sout.toString();
}
}
File Tree Demo
/*
* This example is from the book "Java Foundation Classes in a Nutshell".
* Written by David Flanagan. Copyright (c) 1999 by O"Reilly & Associates.
* You may distribute this source code for non-commercial purposes only.
* You may study, modify, and use this example for any purpose, as long as
* this notice is retained. Note that this example is provided "as is",
* WITHOUT WARRANTY of any kind either expressed or implied.
*/
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;
import java.io.File;
public class FileTreeDemo {
public static void main(String[] args) {
// Figure out where in the filesystem to start displaying
File root;
if (args.length > 0) root = new File(args[0]);
else root = new File(System.getProperty("user.home"));
// Create a TreeModel object to represent our tree of files
FileTreeModel model = new FileTreeModel(root);
// Create a JTree and tell it to display our model
JTree tree = new JTree();
tree.setModel(model);
// The JTree can get big, so allow it to scroll.
JScrollPane scrollpane = new JScrollPane(tree);
// Display it all in a window and make the window appear
JFrame frame = new JFrame("FileTreeDemo");
frame.getContentPane().add(scrollpane, "Center");
frame.setSize(400,600);
frame.setVisible(true);
}
}
/**
* The methods in this class allow the JTree component to traverse
* the file system tree, and display the files and directories.
**/
class FileTreeModel implements TreeModel {
// We specify the root directory when we create the model.
protected File root;
public FileTreeModel(File root) { this.root = root; }
// The model knows how to return the root object of the tree
public Object getRoot() { return root; }
// Tell JTree whether an object in the tree is a leaf or not
public boolean isLeaf(Object node) { return ((File)node).isFile(); }
// Tell JTree how many children a node has
public int getChildCount(Object parent) {
String[] children = ((File)parent).list();
if (children == null) return 0;
return children.length;
}
// Fetch any numbered child of a node for the JTree.
// Our model returns File objects for all nodes in the tree. The
// JTree displays these by calling the File.toString() method.
public Object getChild(Object parent, int index) {
String[] children = ((File)parent).list();
if ((children == null) || (index >= children.length)) return null;
return new File((File) parent, children[index]);
}
// Figure out a child"s position in its parent node.
public int getIndexOfChild(Object parent, Object child) {
String[] children = ((File)parent).list();
if (children == null) return -1;
String childname = ((File)child).getName();
for(int i = 0; i < children.length; i++) {
if (childname.equals(children[i])) return i;
}
return -1;
}
// This method is only invoked by the JTree for editable trees.
// This TreeModel does not allow editing, so we do not implement
// this method. The JTree editable property is false by default.
public void valueForPathChanged(TreePath path, Object newvalue) {}
// Since this is not an editable tree model, we never fire any events,
// so we don"t actually have to keep track of interested listeners.
public void addTreeModelListener(TreeModelListener l) {}
public void removeTreeModelListener(TreeModelListener l) {}
}
Get current directory
public class Main {
public static void main(String[] args) {
System.out.println(System.getProperty("user.dir"));
}
}
Get Files Recurse
import java.io.File;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Utils {
private static List<File> getFilesRecurse(File dir, Pattern pattern, File exclude, boolean rec,
List<File> fileList) {
for (File file : dir.listFiles()) {
if (file.equals(exclude)) {
continue;
}
if (file.isDirectory() && rec) {
getFilesRecurse(file, pattern, exclude, rec, fileList);
} else {
Matcher m = pattern.matcher(file.getName());
if (m.matches()) {
fileList.add(file);
}
}
}
return fileList;
}
}
Get Last modification time of a file or directory
import java.io.File;
import java.util.Date;
public class Main {
public static void main(String[] args) {
File file = new File("C://FileIO//demo.txt");
System.out.println("last modifed:" + new Date(file.lastModified()));
}
}
Get name of parent directory
import java.io.File;
public class Main {
public static void main(String[] args) {
File file = new File("C:/File/demo.txt");
String strParentDirectory = file.getParent();
System.out.println("Parent directory is : " + strParentDirectory);
}
}
Get name of specified file or directory
import java.io.File;
public class Main {
public static void main(String[] args) {
File file = new File("C:/File/Demo.txt");
System.out.println(file.getName());
}
}
List contents of a directory
import java.io.File;
public class Main {
public static void main(String[] args) {
File file = new File("C:/");
String[] files = file.list();
System.out.println("contents of " + file.getPath());
for (int i = 0; i < files.length; i++) {
System.out.println(files[i]);
}
}
}
Listing the Files or Subdirectories in a Directory
import java.io.File;
public class Main {
public static void main(String[] argv) throws Exception {
File dir = new File("directoryName");
String[] children = dir.list();
if (children == null) {
System.out.println("does not exist or is not a directory");
} else {
for (int i = 0; i < children.length; i++) {
String filename = children[i];
System.out.println(filename);
}
}
}
}
Listing the File System Roots
import java.io.File;
public class Main {
public static void main(String[] argv) throws Exception {
File[] roots = File.listRoots();
for (int i = 0; i < roots.length; i++) {
System.out.println(roots[i]);
}
}
}
Reading and Printing a Directory Hierarchy
import java.io.File;
import java.io.IOException;
public class FileUtil {
public static void main(String[] a)throws IOException{
showDir(1, new File("d:\\Java_Dev"));
}
static void showDir(int indent, File file) throws IOException {
for (int i = 0; i < indent; i++)
System.out.print("-");
System.out.println(file.getName());
if (file.isDirectory()) {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++)
showDir(indent + 4, files[i]);
}
}
}
Recursive directory deletion
/**
*
* The ObjectStyle Group Software License, version 1.1
* ObjectStyle Group - http://objectstyle.org/
*
* Copyright (c) 2002-2005, Andrei (Andrus) Adamchik and individual authors
* of the software. All rights reserved.
*
* 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.
*
* 3. The end-user documentation included with the redistribution, if any,
* must include the following acknowlegement:
* "This product includes software developed by independent contributors
* and hosted on ObjectStyle Group web site (http://objectstyle.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "ObjectStyle Group" and "Cayenne" must not be used to endorse
* or promote products derived from this software without prior written
* permission. For written permission, email
* "andrus at objectstyle dot org".
*
* 5. Products derived from this software may not be called "ObjectStyle"
* or "Cayenne", nor may "ObjectStyle" or "Cayenne" appear in their
* names without prior written permission.
*
* THIS SOFTWARE IS PROVIDED ``AS IS"" AND ANY EXPRESSED 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 OBJECTSTYLE GROUP OR
* ITS 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.
*
*
* This software consists of voluntary contributions made by many
* individuals and hosted on ObjectStyle Group web site. For more
* information on the ObjectStyle Group, please see
* <http://objectstyle.org/>.
*/
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.lang.reflect.Member;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.ruparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
/**
* Contains various unorganized static utility methods used across Cayenne.
*
* @author Andrei Adamchik
*/
public class Util {
/**
* Deletes a file or directory, allowing recursive directory deletion. This is an
* improved version of File.delete() method.
*/
public static boolean delete(String filePath, boolean recursive) {
File file = new File(filePath);
if (!file.exists()) {
return true;
}
if (!recursive || !file.isDirectory())
return file.delete();
String[] list = file.list();
for (int i = 0; i < list.length; i++) {
if (!delete(filePath + File.separator + list[i], true))
return false;
}
return file.delete();
}
}
Recursively search a directory tree
/*
* Copyright 2007 Google Inc.
*
* 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.
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
/**
* Recursively search a directory tree, for each File found in it, call
* FileFinderListener.proceedFile. A filter can be set prior calling this
* method.
*
* @author ycoppel@google.ru (Yohann Coppel)
*
*/
public class FileLister {
/**
* Base directory to explore.
*/
private File classPath;
/**
* File listener for callbacks.
*/
private FileListerListener listener;
/**
* @param classPath
* path to the classFile (usually top level package as com in
* com.google.rumon)
*/
public FileLister(File classPath, FileListerListener depmk) {
this.classPath = classPath;
this.listener = depmk;
}
/**
* begin the search of class files in the classPath given to the constructor.
*/
public void start() {
listener.startProcessing();
for (File f : classPath.listFiles()) {
dfsFileSearch(f);
}
listener.endOfProcessing();
}
/**
* operate a recursive depth first search in the directory. If file is a
* directory, recursively search into for files. For each file found, check if
* it passes the filter of DepMaker, and if yes, call proceedFile with the
* file.
*
* @param file
* File where to start the dfsFileSearch
*/
private void dfsFileSearch(File file) {
boolean dirMatches = listener.directoryFilter(file.getPath());
if (file.isDirectory()) {
// call callback for entering the directory only if the directory matches
if (dirMatches) {
listener.enterDirectory(file.getPath().replaceFirst(classPath.getPath(), ""));
}
// look inside of the directory anyway (maybe sub directories matches...
for (File f : file.listFiles()) {
dfsFileSearch(f);
}
// get out of the directory, callback.
if (dirMatches) {
listener.outDirectory(file.getPath().replaceFirst(classPath.getPath(), ""));
}
} else { // dir.isFile() == true
if (listener.fileFilter(file.getPath()) && dirMatches) {
try {
listener.proceedFile(new FileInputStream(file), file.getPath().replaceFirst(
classPath.getPath(), ""));
} catch (FileNotFoundException e) {
// should not happen, cause we just seen it on the hard drive...
// but who knows...
e.printStackTrace();
}
}
}
}
}
/*
* Copyright 2007 Google Inc.
*
* 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.
*/
/**
* Listener for callbacks when directories and files are found when exploring a
* directory, or a jar file for example.
*
* @author ycoppel@google.ru (Yohann Coppel)
*
*/
interface FileListerListener {
/**
* Filter to apply to (normal - i.e not a directory) files found in the
* directory. May be a simple filename check as "end with .class"
*
* @param name
* filename
* @return true if the filename pass the filter, and that proceedFile should
* be called on this file later
*
*/
public boolean fileFilter(String name);
/**
* Filter to apply to directories. If this methods return false,
* subdirectories should not be traversed. May be a simple directory path
* check as "start with "directoryfilter""
*
* @param name
* filename to check
* @return true if the directory can contain interresting files.
*/
public boolean directoryFilter(String name);
/**
* method called when a file passing the fileFilter test is found.
*
* @param f
* file found.
*/
public void proceedFile(InputStream f, String name);
/**
* called when entering in the given directory
*
* @param directoryPath
*/
public void enterDirectory(String directoryPath);
/**
* called when we step out from the given directory
*
* @param directoryPath
*/
public void outDirectory(String directoryPath);
/**
* callback called at the begining of the processing
*/
public void startProcessing();
/**
* callback called at the end of the processing
*/
public void endOfProcessing();
}
Recursivly delete directory
import java.io.File;
public class DirectoryIO {
/**
*
* recursivly delete directory
*
* @param directory
*/
public static boolean delete(File directory) {
boolean result = false;
if (directory.isDirectory()) {
File[] files = directory.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
delete(files[i]);
}
files[i].delete();
}
result = directory.delete();
}
return result;
}
}
Searches through the directory tree
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*
*/
import java.io.File;
/**
*
* FileUtils is a collection of routines for common file system operations.
*
* @author Dan Jemiolo (danj)
*
*/
public final class FileUtils {
/**
*
* This is a convenience method that calls find(File, String, boolean) with
* the last parameter set to "false" (does not match directories).
*
* @see #find(File, String, boolean)
*
*/
public static File find(File contextRoot, String fileName) {
return find(contextRoot, fileName, false);
}
/**
*
* Searches through the directory tree under the given context directory and
* finds the first file that matches the file name. If the third parameter is
* true, the method will also try to match directories, not just "regular"
* files.
*
* @param contextRoot
* The directory to start the search from.
*
* @param fileName
* The name of the file (or directory) to search for.
*
* @param matchDirectories
* True if the method should try and match the name against directory
* names, not just file names.
*
* @return The java.io.File representing the <em>first</em> file or
* directory with the given name, or null if it was not found.
*
*/
public static File find(File contextRoot, String fileName, boolean matchDirectories) {
if (contextRoot == null)
throw new NullPointerException("NullContextRoot");
if (fileName == null)
throw new NullPointerException("NullFileName");
if (!contextRoot.isDirectory()) {
Object[] filler = { contextRoot.getAbsolutePath() };
String message = "NotDirectory";
throw new IllegalArgumentException(message);
}
File[] files = contextRoot.listFiles();
//
// for all children of the current directory...
//
for (int n = 0; n < files.length; ++n) {
String nextName = files[n].getName();
//
// if we find a directory, there are two possibilities:
//
// 1. the names match, AND we are told to match directories.
// in this case we"re done
//
// 2. not told to match directories, so recurse
//
if (files[n].isDirectory()) {
if (nextName.equals(fileName) && matchDirectories)
return files[n];
File match = find(files[n], fileName);
if (match != null)
return match;
}
//
// in the case of regular files, just check the names
//
else if (nextName.equals(fileName))
return files[n];
}
return null;
}
}
Set last modified time of a file or directory
import java.io.File;
import java.util.Date;
public class Main {
public static void main(String[] args) {
File file = new File("C:/ReadText.txt");
System.out.println(file.lastModified());
System.out.println(file.setLastModified(new Date().getTime()));
System.out.println(new Date(file.lastModified()));
}
}
Starts at the directory given and tests to see whether it is empty
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*
*/
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
*
* FileUtils is a collection of routines for common file system operations.
*
* @author Dan Jemiolo (danj)
*
*/
public final class FileUtils {
/**
*
* Starts at the directory given and tests to see whether it is empty; if so,
* it deletes it and moves up the directory tree, deleting empty directories
* until it finds a non-empty one.
*
* @param directory
* The first directory to test.
*
* @throws IOException
* <ul>
* <li>If the directory does not exist or the user does not have
* permission to delete it or its parents.</li>
* </ul>
*
*/
public static void pruneEmptyDirectories(File directory) throws IOException {
if (directory == null)
throw new NullPointerException("NullFile");
if (!directory.isDirectory()) {
Object[] filler = { directory.getAbsolutePath() };
String message = "NotDirectory";
throw new IllegalArgumentException(message);
}
//
// check to see if the directory is now empty and, if so, delete it
// too, moving up the tree until we find one with stuff in it
//
while (directory != null) {
File[] directoryFiles = directory.listFiles();
//
// if the directory has files, we"re done
//
if (directoryFiles.length > 0)
break;
if (!directory.delete()) {
Object[] filler = { directory.getAbsolutePath() };
String message = "DeleteFailed";
throw new IOException(message);
}
//
// go up the tree
//
directory = directory.getParentFile();
}
}
/**
*
* The application"s current working directory.
*
*/
public static final File CURRENT_DIR = new File(".");
/**
*
* This is a convenience method that calls remove(File, boolean) with the
* second parameter set to "false" (doesn"t prune empty directories).
*
* @see #remove(File, boolean)
*
*/
public static void remove(File file) throws IOException {
remove(file, false);
}
/**
*
* @param file
* The file or directory to delete.
*
* @param pruneEmptyDirectories
* True if the deletion results in an empty parent directory. If set
* to true, this method will traverse up the directory tree, deleting
* directories that are made empty by the deletion.
*
* @throws IOException
* <ul>
* <li>If there was an error trying to remove the file or
* directory. The file system may be in an inconsistent state when
* the exception is thrown (directories may be partially deleted,
* etc.).</li>
* </ul>
*
*/
public static void remove(File file, boolean pruneEmptyDirectories) throws IOException {
if (file == null)
throw new NullPointerException("NullFile");
if (file.isDirectory())
removeDirectory(file);
else
removeFile(file);
if (pruneEmptyDirectories)
pruneEmptyDirectories(file.getParentFile());
}
private static void removeDirectory(File directory) throws IOException {
File[] files = directory.listFiles();
//
// for all items in the directory...
//
for (int n = 0; n < files.length; ++n) {
File nextFile = files[n];
//
// if it"s a directory, delete sub-directories and files before
// removing the empty directory
//
if (nextFile.isDirectory())
removeDirectory(nextFile);
//
// otherwise just delete the file - do NOT prune the directory
// in advance
//
else
removeFile(nextFile);
}
//
// now that everything"s gone, delete the specified directory
//
if (!directory.delete()) {
Object[] filler = { directory.getAbsolutePath() };
String message = "DeleteFailed";
throw new IOException(message);
}
}
private static void removeFile(File file) throws IOException {
//
// make sure the file exists, then delete it
//
if (!file.exists())
throw new FileNotFoundException(file.getAbsolutePath());
if (!file.delete()) {
Object[] filler = { file.getAbsolutePath() };
String message = "DeleteFailed";
throw new IOException(message);
}
}
}
The Directory Listing Application
import java.io.File;
import java.util.Scanner;
public class DirList {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
System.out.print("\nEnter a path: ");
String path = sc.nextLine();
File dir = new File(path);
if (!dir.exists() || !dir.isDirectory())
System.out.println("\nThat directory doesn"t exist.");
else {
System.out.println("\nListing directory tree of:");
System.out.println(dir.getPath());
listDirectories(dir, " ");
}
}
private static void listDirectories(File dir, String indent) {
File[] dirs = dir.listFiles();
for (File f : dirs) {
if (f.isDirectory()) {
System.out.println(indent + f.getName());
listDirectories(f, indent + " ");
}
}
}
}
Traversing all files and directories under dir
import java.io.File;
public class Main {
public static void main(String[] argv) throws Exception {
}
public static void visitAllDirsAndFiles(File dir) {
System.out.println(dir);
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
visitAllDirsAndFiles(new File(dir, children[i]));
}
}
}
}
Traversing only directories under dir
import java.io.File;
public class Main {
public static void main(String[] argv) throws Exception {
}
// Process only directories under dir
public static void visitAllDirs(File dir) {
if (dir.isDirectory()) {
System.out.println(dir);
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
visitAllDirs(new File(dir, children[i]));
}
}
}
}
Traversing only files under dir
import java.io.File;
public class Main {
public static void main(String[] argv) throws Exception {
}
public static void visitAllFiles(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
visitAllFiles(new File(dir, children[i]));
}
} else {
System.out.println(dir);
}
}
}
use list( ) to examine the contents of a directory:
import java.io.File;
class DirList {
public static void main(String args[]) {
String dirname = "/java";
File f1 = new File(dirname);
if (f1.isDirectory()) {
System.out.println("Directory of " + dirname);
String s[] = f1.list();
for (int i=0; i < s.length; i++) {
File f = new File(dirname + "/" + s[i]);
if (f.isDirectory()) {
System.out.println(s[i] + " is a directory");
} else {
System.out.println(s[i] + " is a file");
}
}
} else {
System.out.println(dirname + " is not a directory");
}
}
}
Utility methods for handling files and directories
//The contents of this file are subject to the Mozilla Public License Version 1.1
//(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.mozilla.org/MPL/
//
//Software distributed under the License is distributed on an "AS IS" basis,
//WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
//for the specific language governing rights and
//limitations under the License.
//
//The Original Code is "The Columba Project"
//
//The Initial Developers of the Original Code are Frederik Dietz and Timo Stich.
//Portions created by Frederik Dietz and Timo Stich are Copyright (C) 2003.
//
//All Rights Reserved.
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.util.logging.Logger;
/**
* Utility methods for handling files and directories.
*/
public final class DiskIO {
private static final Logger LOG = Logger.getLogger("org.columba.core.io");
private static String resourceFolder = "";
/**
* Private constructor for utility class.
*/
private DiskIO() {
// don"t instantiate this
}
/**
* Ensures the existence of the directory specified by the parameter. If the
* directory does not exist, an attempt is performed to create it including
* all necessary parent directories that may be implied by the
* specification. ### HELPME : against what should a relative pathname be
* made absolute? ### ### We need to set the installation directory
* somewhere! ####
*
* @param dir
* File specifying the intended directory name; if the specified
* name is a relative path, it is always made absolute against
* the program"s <b>installationDirectory </b>.
* @return <b>true </b> if and only if the specified file exists and is a
* directory
*/
public static boolean ensureDirectory(File dir) {
if (dir == null) {
throw new IllegalArgumentException("dir = null");
}
boolean success = true;
if (!dir.isDirectory()) {
success = !dir.isFile() && dir.mkdirs();
if (success) {
LOG.info("Created directory: " + dir.toString());
} else {
LOG.severe("failed while trying to create directory: "
+ dir.toString());
}
}
return success;
}
// ensureDirectory
public static boolean ensureDirectory(String path) {
return ensureDirectory(new File(path));
}
public static void saveStringInFile(File toFile, String insertString)
throws IOException {
BufferedWriter out;
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(
toFile), "ISO-8859-1"));
out.write(insertString);
out.flush();
out.close();
}
// saveStringInFile
public static String readFileInString(File fromFile) throws IOException {
StringBuffer strbuf = new StringBuffer((int) fromFile.length());
BufferedReader in = new BufferedReader(new InputStreamReader(
new FileInputStream(fromFile), "ISO-8859-1"));
String str;
strbuf = new StringBuffer((int) fromFile.length());
while ((str = in.readLine()) != null) {
strbuf.append(str + "\n");
}
in.close();
return strbuf.toString();
/*
* int lineNumber = 0; byte[] buffer = new byte[1024]; int read;
* StringBuffer out = new StringBuffer((int)fromFile.length());
* FileInputStream in = new FileInputStream( fromFile );
*
* read = in.read(buffer); while ( read == 1024 ) { out.append(new
* String(buffer,"ISO-8859-1")); read = in.read(buffer); }
*
* out.append(new String(buffer,0,read,"ISO-8859-1")); in.close();
*
* return out.toString();
*/
}
// saveStringInFile
/**
* Deletes the directory specified by the parameter and all of its contents.
* This does recurse into subdirectories. Function reports errors. If the
* parameter does not denote a directory, <b>false </b> is always returned.
*
* @param dir
* a File representing the directory to be delete
* @return <b>true </b> if and only if the directory does not exist on
* termination; a return value <b>false </b> does not imply that
* there were no files deleted
* @throws IllegalArgumentException
* if the parameter is <b>null </b>
*/
public static boolean deleteDirectory(File dir) {
File[] files;
File f;
int i;
boolean success = true;
if (dir == null) {
throw new IllegalArgumentException("dir = null");
}
if (!dir.isDirectory()) {
return false;
}
files = dir.listFiles();
for (i = 0; i < files.length; i++) {
if ((f = files[i]).isDirectory()) {
deleteDirectory(f);
} else if (!f.delete()) {
LOG.severe("*** failed to delete file " + f.getAbsolutePath());
}
}
success = dir.delete();
if (!success) {
LOG.severe("*** failed to delete directory "
+ dir.getAbsolutePath());
}
return success;
}
// deleteDirectory
/**
* Deletes the contents of an existing directory. (May be applied to
* non-existing files without causing error.)
*
* @return <b>true </b> if and only if on termination the directory exists
* and is empty
*/
public static boolean emptyDirectory(File dir) {
boolean success;
if (dir == null) {
throw new IllegalArgumentException("dir = null");
}
if ((success = dir.exists() && deleteDirectory(dir))) {
dir.mkdirs();
}
return success && dir.exists();
}
// emptyDirectory
/**
* General use columba resource InputStream getter.
*
* @param path
* the full path and filename of the resource requested. If
* <code>path</code> begins with "#" it is resolved against the
* program"s standard resource folder after removing "#"
* @return an InputStream to read the resource data, or <b>null </b> if the
* resource could not be obtained
* @throws java.io.IOException
* if there was an error opening the input stream
*/
public static InputStream getResourceStream(String path)
throws java.io.IOException {
URL url;
if ((url = getResourceURL(path)) == null) {
return null;
}
return url.openStream();
}
// getResourceStream
/**
* General use columba resource URL getter.
*
* @param path
* the full path and filename of the resource requested. If
* <code>path</code> begins with "#" it is resolved against the
* program"s standard resource folder after removing "#"
* @return an URL instance, or <b>null </b> if the resource could not be
* obtained
* @throws java.io.IOException
* if there was an error opening the input stream
*/
public static URL getResourceURL(String path) // throws
// java.io.IOException
{
URL url;
if (path == null) {
throw new IllegalArgumentException("path = null");
}
if (path.startsWith("#")) {
path = resourceFolder + path.substring(1);
}
// url = ClassLoader.getSystemResource(path);
url = DiskIO.class.getResource("/" + path);
if (url == null) {
LOG.info("*** failed locating resource: " + path);
return null;
}
return url;
}
// getResourceURL
public static void setResourceRoot(String path) {
if (path == null) {
resourceFolder = "";
} else {
if (!path.endsWith("/")) {
path += "/";
}
resourceFolder = path;
}
}
// setResourceRoot
public static String getResourceRoot() {
return resourceFolder;
}
/**
* Copies the contents of any disk file to the specified output file. The
* output file will be overridden if it exist. Function reports errors.
*
* @param inputFile
* a File object
* @param outputFile
* a File object
* @throws java.io.IOException
* if the function could not be completed because of an IO error
*/
public static void copyFile(File inputFile, File outputFile)
throws java.io.IOException {
FileInputStream in;
FileOutputStream out;
byte[] buffer = new byte[512];
int len;
try {
out = new FileOutputStream(outputFile);
in = new FileInputStream(inputFile);
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
in.close();
out.close();
} catch (IOException e) {
LOG.info("*** error during file copy "
+ outputFile.getAbsolutePath() + ": " + e.getMessage());
throw e;
}
}
// copyFile
/**
* Copies a system resource to the specified output file. The output file
* will be overridden if it exist, so the calling routine has to take care
* about unwanted deletions of content. Function reports errors.
*
* @param resource
* a full resource path. If the value begins with "#", it is
* resolved against the program"s standard resource folder after
* removing "#"
* @return <b>true </b> if and only if the operation was successful,
* <b>false </b> if the resource was not found
* @throws java.io.IOException
* if there was an IO error
*/
public static boolean copyResource(String resource, File outputFile)
throws java.io.IOException {
InputStream in;
FileOutputStream out;
byte[] buffer = new byte[512];
int len;
// attempt
try {
if ((in = DiskIO.getResourceStream(resource)) == null) {
return false;
}
out = new FileOutputStream(outputFile);
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.close();
in.close();
LOG.fine("created : " + outputFile.getAbsolutePath());
} catch (IOException e) {
LOG.severe("*** error during resource file copy "
+ outputFile.getAbsolutePath() + ": " + e.getMessage());
throw e;
}
return true;
}
// copyResource
public static String readStringFromResource(String resource)
throws java.io.IOException {
InputStream in;
StringBuffer result = new StringBuffer();
// attempt
try {
if ((in = DiskIO.getResourceStream(resource)) == null) {
return "";
}
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
String nextLine = reader.readLine();
while (nextLine != null) {
result.append(nextLine);
result.append("\n");
nextLine = reader.readLine();
}
in.close();
} catch (IOException e) {
e.printStackTrace();
throw e;
}
return result.toString();
}
/**
* Results equal
* <code>copyResource ( String resource, new File (outputFile) )</code>.
*/
public static boolean copyResource(String resource, String outputFile)
throws java.io.IOException {
return copyResource(resource, new File(outputFile));
}
}