Java Tutorial/File/Directory — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 05:20, 1 июня 2010
Содержание
- 1 Calculate directory size
- 2 Change last modified time of a file or directory
- 3 Check if a directory is not empty
- 4 Checks, whether the child directory is a subdirectory of the base directory.
- 5 Copying a Directory
- 6 Create a directories recursively
- 7 Create a directory; all ancestor directories must exist
- 8 Create a directory; all non-existent ancestor directories are automatically created
- 9 Create a directory (or several directories)
- 10 Create directory
- 11 Create directory along with required nonexistent parent directories
- 12 Creates a new and empty directory in the default temp directory using the given prefix.
- 13 Delete directory recursively
- 14 Delete file or directory
- 15 Delete file or directory when virtual machine terminates
- 16 Deleting a Directory (an empty directory)
- 17 Determine File or Directory
- 18 Determine if file or directory exists
- 19 Determine if File or Directory is hidden
- 20 Get all files and folders under a certain folder and save them to a set
- 21 Get name of parent directory
- 22 Get name of specified file or directory
- 23 Get parent directory as a File object
- 24 Get the content of a directory
- 25 Getting the Current Working Directory
- 26 If a file or directory readable
- 27 Mark file or directory Read Only
- 28 Moving a File or Directory to Another Directory
- 29 Recursively search a directory tree
- 30 Rename file or directory
- 31 Searches through the directory tree
- 32 Search for files recursively
- 33 Traversing all files and directories under dir
- 34 Traversing only directories under dir
- 35 Traversing only files under dir
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");
}
}
Change 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) throws Exception {
File fileToChange = new File("C:/myfile.txt");
Date filetime = new Date(fileToChange.lastModified());
System.out.println(filetime.toString());
System.out.println(fileToChange.setLastModified(System.currentTimeMillis()));
filetime = new Date(fileToChange.lastModified());
System.out.println(filetime.toString());
}
}
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!");
}
}
}
}
Checks, whether the child directory is a subdirectory of the base directory.
import java.io.File;
import java.io.IOException;
/*
* JCommon : a free general purpose class library for the Java(tm) platform
*
*
* (C) Copyright 2000-2005, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jcommon/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library 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 Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Java is a trademark or registered trademark of Sun Microsystems, Inc.
* in the United States and other countries.]
*
* ------------
* IOUtils.java
* ------------
* (C)opyright 2002-2004, by Thomas Morgner and Contributors.
*
* Original Author: Thomas Morgner;
* Contributor(s): David Gilbert (for Object Refinery Limited);
*
* $Id: IOUtils.java,v 1.8 2009/01/22 08:34:58 taqua Exp $
*
* Changes
* -------
* 26-Jan-2003 : Initial version
* 23-Feb-2003 : Documentation
* 25-Feb-2003 : Fixed Checkstyle issues (DG);
* 29-Apr-2003 : Moved to jcommon
* 04-Jan-2004 : Fixed JDK 1.2.2 issues with createRelativeURL;
* added support for query strings within these urls (TM);
*/
/**
* The IOUtils provide some IO related helper methods.
*
* @author Thomas Morgner.
*/
public class Main {
/**
* Checks, whether the child directory is a subdirectory of the base
* directory.
*
* @param base the base directory.
* @param child the suspected child directory.
* @return true, if the child is a subdirectory of the base directory.
* @throws IOException if an IOError occured during the test.
*/
public boolean isSubDirectory(File base, File child)
throws IOException {
base = base.getCanonicalFile();
child = child.getCanonicalFile();
File parentFile = child;
while (parentFile != null) {
if (base.equals(parentFile)) {
return true;
}
parentFile = parentFile.getParentFile();
}
return false;
}
}
Copying a Directory
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("srcDir"), new File("dstDir"));
}
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);
}
}
static void copyFile(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
}
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 directory; all ancestor directories must exist
import java.io.File;
public class Main {
public static void main(String[] argv) throws Exception {
boolean success = (new File("directoryName")).mkdir();
if (!success) {
System.out.println("Directory creation failed");
}
}
}
Create a directory; all non-existent ancestor directories are automatically created
import java.io.File;
public class Main {
public static void main(String[] argv) throws Exception {
boolean success = (new File("directoryName")).mkdirs();
if (!success) {
System.out.println("Directory creation failed");
}
}
}
Create a directory (or several directories)
import java.io.File;
public class Main {
public static void main(String[] args) {
File directory = new File("C:/temp/temp1/temp2/temp3");
if (directory.mkdir()) {
System.out.println("Success mkdir");
} else {
if (directory.mkdirs()) {
System.out.println("Success mkdirs");
} else {
System.out.println("Failed");
}
}
}
}
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");
}
}
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;
}
}
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);
}
}
Delete file or directory
import java.io.File;
public class Main {
public static void main(String[] args) throws Exception {
File file = new File("C:/Demo.txt");
System.out.println(file.delete());
}
}
Delete file or directory when virtual machine terminates
import java.io.File;
public class Main {
public static void main(String[] args) {
File file = new File("C:/Demo.txt");
file.deleteOnExit();
}
}
Deleting a Directory (an empty directory)
import java.io.File;
public class Main {
public static void main(String[] argv) throws Exception {
boolean success = (new File("directoryName")).delete();
if (!success) {
System.out.println("Deletion failed");
}
}
}
Determine File or Directory
import java.io.File;
public class Main {
public static void main(String[] args) {
File file = new File("C://FileIO");
boolean isFile = file.isFile();
if (isFile){
System.out.println("a file.");
}else{
System.out.println("not a file.");
}
boolean isDirectory = file.isDirectory();
if (isDirectory){
System.out.println("a directory.");
}else{
System.out.println("not a directory.");
}
}
}
Determine if file or directory exists
import java.io.File;
public class Main {
public static void main(String[] args) {
File file = new File("C:/Demo.txt");
System.out.println(file.exists());
}
}
import java.io.File;
public class Main {
public static void main(String[] args) {
File file = new File("C:/Demo.txt");
System.out.println(file.isHidden());
}
}
Get all files and folders under a certain folder and save them to a set
import java.io.File;
import java.util.HashSet;
import java.util.Set;
public class Main {
public static void main(String[] argv) {
Set<File> all = new HashSet<File>();
getAllFileAndFolder(new File("c:\\"), all);
}
public static void getAllFileAndFolder(File folder, Set<File> all) {
all.add(folder);
if (folder.isFile()) {
return;
}
for (File file : folder.listFiles()) {
all.add(file);
if (file.isDirectory()) {
getAllFileAndFolder(file, all);
}
}
}
}
Get name of parent directory
import java.io.File;
public class Main {
public static void main(String[] args) {
File file = new File("C:/demo.txt");
System.out.println("Parent directory:" + file.getParent());
}
}
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:/Demo.txt");
System.out.println("File name is : " + file.getName());
}
}
Get parent directory as a File object
import java.io.File;
public class Main {
public static void main(String[] args) {
File file = new File("C:/demo.txt");
File fileParent = file.getParentFile();
System.out.println("Parent directory: " + fileParent.getPath());
}
}
Get the content of a directory
import java.io.File;
import java.io.FilenameFilter;
public class Main {
public static void main(String[] args) {
File games = new File("C:\\Test");
File[] files = games.listFiles();
for (File file : files) {
System.out.println(file + " is a " + (file.isDirectory() ? "directory" : "file"));
}
String[] xfiles = games.list();
for (String file : xfiles) {
System.out.println("File = " + file);
}
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
if (name.endsWith(".txt")) {
return true;
}
return false;
}
};
File[] yfiles = games.listFiles(filter);
for (File doc : yfiles) {
System.out.println("Doc file = " + doc);
}
}
}
Getting the Current Working Directory
public class Main {
public static void main(String[] argv) throws Exception {
String curDir = System.getProperty("user.dir");
}
}
If a file or directory readable
import java.io.File;
import java.io.File;
public class Main {
public static void main(String[] args) {
File file = new File(args[0]);
if (!file.exists()) {
System.out.println(args[0] + " does not exist.");
return;
}
if (file.isFile() && file.canRead()){
System.out.println(file.getName() + " can be read from.");
}
if (file.isDirectory()) {
System.out.println(file.getPath() + " is a directory containing...");
String[] files = file.list();
for (int i = 0; i < files.length; i++) {
System.out.println(files[i]);
}
}
}
}
Mark file or directory Read Only
import java.io.File;
public class Main {
public static void main(String[] args) {
File file = new File("C:/demo.txt");
System.out.println(file.setReadOnly());
System.out.println(file.canWrite());
}
}
Moving a File or Directory to Another Directory
import java.io.File;
public class Main {
public static void main(String[] argv) throws Exception {
File file = new File("filename");
File dir = new File("directoryname");
boolean success = file.renameTo(new File(dir, file.getName()));
if (!success) {
System.out.println("File was not successfully moved");
}
}
}
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();
}
Rename file or directory
import java.io.File;
public class Main {
public static void main(String[] args) {
File oldName = new File("C:/s.txt");
File newName = new File("C:/d.txt");
if (oldName.renameTo(newName)) {
System.out.println("renamed");
} else {
System.out.println("Error");
}
}
}
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;
}
}
Search for files recursively
import org.apache.rumons.io.FileUtils;
import java.io.File;
import java.util.Collection;
import java.util.Iterator;
public class Main {
public static void main(String[] args) throws Exception {
File root = new File("c:\\");
String[] extensions = { "xml", "java", "dat" };
boolean recursive = true;
Collection files = FileUtils.listFiles(root, extensions, recursive);
for (Iterator iterator = files.iterator(); iterator.hasNext();) {
File file = (File) iterator.next();
System.out.println("File = " + file.getAbsolutePath());
}
}
}
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);
}
}
}