Java/File Input Output/Files
Содержание
- 1 Change a file attribute to read only
- 2 Change a file attribute to writable
- 3 Change last modified time of a file or directory
- 4 Choose a File
- 5 Compare File Dates
- 6 Compare two file paths
- 7 Construct file path
- 8 Copy File
- 9 Create a directory; all ancestor directories must exist
- 10 Create a directory; all non-existent ancestor directories are automatically created
- 11 Create a directory (or several directories)
- 12 Create a human-readable file size
- 13 Create a temporary file
- 14 Create file
- 15 Create new empty file
- 16 Create temporary file in specified directory
- 17 Create temporary file with specified extension suffix
- 18 Creating a Temporary File and delete it on exit
- 19 Data file
- 20 Delete a file
- 21 Delete a file from within Java
- 22 Delete file or directory
- 23 Delete file or directory when virtual machine terminates
- 24 Deleting a Directory (an empty directory)
- 25 Demonstrate File.
- 26 Determine File or Directory
- 27 Determine if a file can be read
- 28 Determine if a file can be written
- 29 Determine if file or directory exists
- 30 Determine if File or Directory is hidden
- 31 File.getCanonicalFile() converts a filename path to a unique canonical form suitable for comparisons.
- 32 Find out the directory
- 33 Forcing Updates to a File to the Disk
- 34 Format file length in string
- 35 Get Absolute path of the file
- 36 Get a file last modification date
- 37 Get a list of files, and check if any files are missing
- 38 Get all path information from java.io.File
- 39 Get all xml files by file extension
- 40 Get extension, path and file name
- 41 Get file extension name
- 42 Get file size
- 43 Get File size in bytes
- 44 Get icon for file type
- 45 Get parent directory as a File object
- 46 Get the parents of an absolute filename path
- 47 Getting an Absolute Filename Path from a Relative Filename parent Path
- 48 Getting an Absolute Filename Path from a Relative Filename Path
- 49 Getting an Absolute Filename Path from a Relative Filename with Path
- 50 Getting and Setting the Modification Time of a File or Directory
- 51 Getting the Current Working Directory
- 52 Getting the Parents of a Filename Path
- 53 List drives
- 54 List Filesystem roots
- 55 Listing the Directory Contents
- 56 Mark file or directory Read Only
- 57 Moving a File or Directory to Another Directory
- 58 Output to a text File
- 59 Querying a File for Information
- 60 Random File
- 61 Read data from text file
- 62 Read file contents to string using commons-io?
- 63 Rename file or directory
- 64 Return a file with the given filename creating the necessary directories if not present.
- 65 Search for files recursively
- 66 Set file attributes.
- 67 Sort files base on their last modified date
- 68 Strings -- extract printable strings from binary file
- 69 Working with RandomAccessFile
- 70 Work with temporary files in Java
Change a file attribute to read only
import java.io.File;
public class Main {
public static void main(String[] args) throws Exception {
File file = new File("ReadOnly.txt");
file.createNewFile();
file.setReadOnly();
if (file.canWrite()) {
System.out.println("writable!");
} else {
System.out.println("read only!");
}
}
}
Change a file attribute to writable
import java.io.File;
public class Main {
public static void main(String[] args) throws Exception {
File file = new File("Writable.txt");
file.createNewFile();
file.setReadOnly();
if (file.canWrite()) {
System.out.println("File is writable!");
} else {
System.out.println("File is in read only mode!");
}
file.setWritable(true);
if (file.canWrite()) {
System.out.println("File is writable!");
} else {
System.out.println("File is in read only mode!");
}
}
}
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());
}
}
Choose a File
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
public class FileFilterDemo {
public FileFilterDemo() {
}
public static void main(String[] args) {
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));
chooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
public boolean accept(File f) {
return f.getName().toLowerCase().endsWith(".gif")
|| f.isDirectory();
}
public String getDescription() {
return "GIF Images";
}
});
int r = chooser.showOpenDialog(new JFrame());
if (r == JFileChooser.APPROVE_OPTION) {
String name = chooser.getSelectedFile().getName();
System.out.println(name);
}
}
}
Compare File Dates
import java.io.File;
public class CompareFileDates {
public static void main(String[] args) {
// Get the timestamp from file 1
String f1 = "run.bat";
long d1 = new File(f1).lastModified();
// Get the timestamp from file 2
String f2 = "build.xml";
long d2 = new File(f2).lastModified();
String relation;
if (d1 == d2)
relation = "the same age as";
else if (d1 < d2)
relation = "older than";
else
relation = "newer than";
System.out.println(f1 + " is " + relation + " " + f2);
}
}
Compare two file paths
import java.io.File;
public class Main {
public static void main(String[] args) {
File file1 = new File("C:/File/demo1.txt");
File file2 = new File("C:/FileIO/demo1.txt");
if (file1.rupareTo(file2) == 0) {
System.out.println("Both paths are same!");
} else {
System.out.println("Paths are not same!");
}
}
}
Construct file path
import java.io.File;
public class Main {
public static void main(String[] args) {
String filePath = File.separator + "Java" + File.separator + "IO";
File file = new File(filePath);
System.out.println(file.getPath());
}
}
// \Java\IO
Copy File
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyBytes {
public static void main(String[] args) throws IOException {
File inputFile = new File("input.txt");
File outputFile = new File("output.txt");
FileInputStream in = new FileInputStream(inputFile);
FileOutputStream out = new FileOutputStream(outputFile);
int c;
while ((c = in.read()) != -1)
out.write(c);
in.close();
out.close();
}
}
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 a human-readable file size
import org.apache.rumons.io.FileUtils;
import java.io.File;
public class Main {
public static void main(String[] args) {
File file = new File("c:\\java.exe");
long size = file.length();
String display = FileUtils.byteCountToDisplaySize(size);
System.out.println("Name = " + file.getName());
System.out.println("size = " + size);
System.out.println("Display = " + display);
}
}
Create a temporary file
import java.io.File;
public class Main{
public static void main(String[] args) throws Exception{
File f = File.createTempFile("temp_", null);
System.out.println(f.getAbsolutePath());
f.deleteOnExit();
}
}
Create file
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
File file = new File("myfile.txt");
if (file.createNewFile())
System.out.println("Success!");
else
System.out.println("Error, file already exists.");
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
Create new empty file
import java.io.File;
public class Main {
public static void main(String[] args) throws Exception {
File file = new File("C://demo.txt");
boolean blnCreated = false;
blnCreated = file.createNewFile();
System.out.println(blnCreated);
}
}
Create temporary file in specified directory
import java.io.File;
public class Main {
public static void main(String[] args) throws Exception {
File file = null;
File dir = new File("C:/");
file = File.createTempFile("JavaTemp", ".javatemp", dir);
System.out.println(file.getPath());
}
}
//C:\JavaTemp5893283162648915021.javatemp
Create temporary file with specified extension suffix
import java.io.File;
public class Main {
public static void main(String[] args) throws Exception {
File file1 = null;
File file2 = null;
file1 = File.createTempFile("JavaTemp", null);
file2 = File.createTempFile("JavaTemp", ".java");
System.out.println(file1.getPath());
System.out.println(file2.getPath());
}
}
Creating a Temporary File and delete it on exit
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
public class Main {
public static void main(String[] argv) throws Exception {
File temp = File.createTempFile("pattern", ".dat");
temp.deleteOnExit();
BufferedWriter out = new BufferedWriter(new FileWriter(temp));
out.write("asdf");
out.close();
}
}
Data file
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class DataFileTest {
static void writeData(Employee e, PrintWriter out) throws IOException {
e.writeData(out);
}
static Employee readData(BufferedReader in) throws IOException {
Employee e = new Employee();
e.readData(in);
return e;
}
public static void main(String[] args) {
Employee staff = new Employee("Java Source", 35500);
staff.raiseSalary(5.25);
try {
PrintWriter out = new PrintWriter(new FileWriter("employee.dat"));
writeData(staff, out);
out.close();
} catch (IOException e) {
System.out.print("Error: " + e);
System.exit(1);
}
try {
BufferedReader in = new BufferedReader(new FileReader(
"employee.dat"));
Employee e = readData(in);
e.print();
in.close();
} catch (IOException e) {
System.out.print("Error: " + e);
System.exit(1);
}
}
}
class Employee {
private String name;
private double salary;
public Employee(String n, double s) {
name = n;
salary = s;
}
public Employee() {
}
public void print() {
System.out.println(name + " " + salary );
}
public void raiseSalary(double byPercent) {
salary *= 1 + byPercent / 100;
}
public void writeData(PrintWriter out) throws IOException {
out.println(name + "|" + salary);
}
public void readData(BufferedReader in) throws IOException {
String s = in.readLine();
StringTokenizer t = new StringTokenizer(s, "|");
name = t.nextToken();
salary = Double.parseDouble(t.nextToken());
}
}
Delete a file
import java.io.File;
public class Main {
public static void main(String[] args) {
File file = new File("yourFile.txt");
System.out.println(file.delete());
}
}
Delete a file from within Java
/*
* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java
* language and environment is gratefully acknowledged.
*
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/
import java.io.File;
import java.io.IOException;
/**
* Delete a file from within Java
*
* @author Ian F. Darwin, http://www.darwinsys.ru/
* @version $Id: Delete.java,v 1.5 2004/02/09 03:33:47 ian Exp $
*/
public class Delete {
public static void main(String[] argv) throws IOException {
// Construct a File object for the backup created by editing
// this source file. The file probably already exists.
// My editor creates backups by putting ~ at the end of the name.
File bkup = new File("Delete.java~");
// Quick, now, delete it immediately:
bkup.delete();
}
}
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");
}
}
}
Demonstrate File.
import java.io.File;
class FileDemo {
public static void main(String args[]) {
File f1 = new File("/java/COPYRIGHT");
System.out.println("File Name: " + f1.getName());
System.out.println("Path: " + f1.getPath());
System.out.println("Abs Path: " + f1.getAbsolutePath());
System.out.println("Parent: " + f1.getParent());
System.out.println(f1.exists() ? "exists" : "does not exist");
System.out.println(f1.canWrite() ? "is writeable" : "is not writeable");
System.out.println(f1.canRead() ? "is readable" : "is not readable");
System.out.println("is " + (f1.isDirectory() ? "" : "not" + " a directory"));
System.out.println(f1.isFile() ? "is normal file" : "might be a named pipe");
System.out.println(f1.isAbsolute() ? "is absolute" : "is not absolute");
System.out.println("File last modified: " + f1.lastModified());
System.out.println("File size: " + f1.length() + " Bytes");
}
}
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 a file can be read
import java.io.File;
public class Main {
public static void main(String[] args) {
String filePath = "C:/Text.txt";
File file = new File(filePath);
if (file.canRead()) {
System.out.println("readable");
} else {
System.out.println("not readable");
}
}
}
Determine if a file can be written
import java.io.File;
public class Main {
public static void main(String[] args) {
String filePath = "C:/Text.txt";
File file = new File(filePath);
if (file.canWrite()) {
System.out.println("writable");
} else {
System.out.println("not writable");
}
}
}
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());
}
}
File.getCanonicalFile() converts a filename path to a unique canonical form suitable for comparisons.
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));
}
}
Find out the directory
import java.io.File;
import java.io.IOException;
public class FindDirectories {
public static void main(String[] args) {
try {
File pathName = new File("c:\\");
String[] fileNames = pathName.list();
for (int i = 0; i < fileNames.length; i++) {
File tf = new File(pathName.getPath(), fileNames[i]);
if (tf.isDirectory()) {
System.out.println(tf.getCanonicalPath());
}
}
} catch (IOException e) {
System.out.println("Error: " + e);
}
}
}
Forcing Updates to a File to the Disk
import java.io.FileDescriptor;
import java.io.FileOutputStream;
public class Main {
public static void main(String[] argv) throws Exception {
FileOutputStream os = new FileOutputStream("outfilename");
FileDescriptor fd = os.getFD();
os.write(1);
os.flush();
fd.sync();
}
}
Format file length in string
public class Utils {
public static final String format(long l) {
String s = String.valueOf(l);
int digits = 0;
while (s.length() > 3) {
s = s.substring(0, s.length() - 3);
digits++;
}
StringBuffer buffer = new StringBuffer();
buffer.append(s);
if ((s.length() == 1) && (String.valueOf(l).length() >= 3)) {
buffer.append(".");
buffer.append(String.valueOf(l).substring(1, 3));
} else if ((s.length() == 2) && (String.valueOf(l).length() >= 3)) {
buffer.append(".");
buffer.append(String.valueOf(l).substring(2, 3));
}
if (digits == 0) {
buffer.append(" B");
} else if (digits == 1) {
buffer.append(" KB");
} else if (digits == 2) {
buffer.append(" MB");
} else if (digits == 3) {
buffer.append(" GB");
} else if (digits == 4) {
buffer.append(" TB");
}
return buffer.toString();
}
}
Get Absolute path of the file
import java.io.File;
public class Main {
public static void main(String[] args) {
File file = new File(File.separator + "Java" + File.separator + "folder");
System.out.println(file.getPath());
System.out.println(file.getAbsolutePath());
}
}
Get a file last modification date
import java.io.File;
import java.util.Date;
public class Main {
public static void main(String[] args) {
File file = new File("Main.java");
Long lastModified = file.lastModified();
Date date = new Date(lastModified);
System.out.println(date);
}
}
Get a list of files, and check if any files are missing
/*
* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java
* language and environment is gratefully acknowledged.
*
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
/**
* Get a list of files, and check if any files are missing.
*
* @author Ian F. Darwin, http://www.darwinsys.ru/
* @version $Id: CheckFiles.java,v 1.3 2004/02/09 03:33:46 ian Exp $
*/
public class CheckFiles {
public static void main(String[] argv) {
CheckFiles cf = new CheckFiles();
System.out.println("CheckFiles starting.");
cf.getListFromFile();
cf.getListFromDirectory();
cf.reportMissingFiles();
System.out.println("CheckFiles done.");
}
public String FILENAME = "filelist.txt";
protected ArrayList listFromFile;
protected ArrayList listFromDir = new ArrayList();
protected void getListFromFile() {
listFromFile = new ArrayList();
BufferedReader is;
try {
is = new BufferedReader(new FileReader(FILENAME));
String line;
while ((line = is.readLine()) != null)
listFromFile.add(line);
} catch (FileNotFoundException e) {
System.err.println("Can"t open file list file.");
return;
} catch (IOException e) {
System.err.println("Error reading file list");
return;
}
}
/** Get list of names from the directory */
protected void getListFromDirectory() {
listFromDir = new ArrayList();
String[] l = new java.io.File(".").list();
for (int i = 0; i < l.length; i++)
listFromDir.add(l[i]);
}
protected void reportMissingFiles() {
for (int i = 0; i < listFromFile.size(); i++)
if (!listFromDir.contains(listFromFile.get(i)))
System.err.println("File " + listFromFile.get(i) + " missing.");
}
}
Get all path information from java.io.File
import java.io.File;
import java.io.IOException;
class PathInfo {
public static void main(String[] args) throws IOException {
File f = new File(args[0]);
System.out.println("Absolute path = " + f.getAbsolutePath());
System.out.println("Canonical path = " + f.getCanonicalPath());
System.out.println("Name = " + f.getName());
System.out.println("Parent = " + f.getParent());
System.out.println("Path = " + f.getPath());
System.out.println("Absolute? = " + f.isAbsolute());
}
}
Get all xml files by file extension
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] argv) {
getXMLFiles(new File("c:\\a"));
}
public static File[] getXMLFiles(File folder) {
List<File> aList = new ArrayList<File>();
File[] files = folder.listFiles();
for (File pf : files) {
if (pf.isFile() && getFileExtensionName(pf).indexOf("xml") != -1) {
aList.add(pf);
}
}
return aList.toArray(new File[aList.size()]);
}
public static String getFileExtensionName(File f) {
if (f.getName().indexOf(".") == -1) {
return "";
} else {
return f.getName().substring(f.getName().length() - 3, f.getName().length());
}
}
}
Get extension, path and file name
/*
* Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - 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.
*
* - Neither the name of Sun Microsystems nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT OWNER 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.
*/
public class FilenameDemo {
public static void main(String[] args) {
final String FPATH = "/home/mem/index.html";
Filename myHomePage = new Filename(FPATH, "/", ".");
System.out.println("Extension = " + myHomePage.extension());
System.out.println("Filename = " + myHomePage.filename());
System.out.println("Path = " + myHomePage.path());
}
}
/*
* Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - 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.
* - Neither the name of Sun Microsystems nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT OWNER 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.
*/
/**
* This class assumes that the string used to initialize fullPath has a
* directory path, filename, and extension. The methods won"t work if it
* doesn"t.
*/
class Filename {
private String fullPath;
private char pathSeparator, extensionSeparator;
public Filename(String str, char sep, char ext) {
fullPath = str;
pathSeparator = sep;
extensionSeparator = ext;
}
public String extension() {
int dot = fullPath.lastIndexOf(extensionSeparator);
return fullPath.substring(dot + 1);
}
public String filename() { // gets filename without extension
int dot = fullPath.lastIndexOf(extensionSeparator);
int sep = fullPath.lastIndexOf(pathSeparator);
return fullPath.substring(sep + 1, dot);
}
public String path() {
int sep = fullPath.lastIndexOf(pathSeparator);
return fullPath.substring(0, sep);
}
}
Get file extension name
import java.io.File;
public class Main {
public static void main(String[] argv) {
getFileExtensionName(new File("a.txt"));
}
public static String getFileExtensionName(File f) {
if (f.getName().indexOf(".") == -1) {
return "";
} else {
return f.getName().substring(f.getName().length() - 3, f.getName().length());
}
}
}
Get file size
import java.io.File;
public class Main {
public static long getFileSize(String filename) {
File file = new File(filename);
if (!file.exists() || !file.isFile()) {
System.out.println("File doesn\"t exist");
return -1;
}
return file.length();
}
public static void main(String[] args) {
long size = getFileSize("c:/my.txt");
System.out.println("Filesize in bytes: " + size);
}
}
Get File size in bytes
import java.io.File;
public class Main {
public static void main(String[] args) {
File file = new File("C:/demo.txt");
long fileSize = file.length();
System.out.println(fileSize + " bytes");
System.out.println((double) fileSize / 1024 + " KB");
System.out.println((double) fileSize / (1024 * 1024) + "MB");
}
}
Get icon for file type
import java.io.File;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Main {
public static void main(String[] args) throws Exception {
File file = new File(args[0]);
sun.awt.shell.ShellFolder sf = sun.awt.shell.ShellFolder.getShellFolder(file);
Icon icon = new ImageIcon(sf.getIcon(true));
System.out.println("type = " + sf.getFolderType());
JLabel label = new JLabel(icon);
JFrame frame = new JFrame();
frame.getContentPane().add(label);
frame.pack();
frame.setVisible(true);
}
}
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 parents of an absolute filename path
import java.io.File;
public class Main {
public static void main(String[] argv) throws Exception {
File file = new File("D:\\test\\test.java");
String parentPath = file.getParent();
System.out.println(parentPath);
File parentDir = file.getParentFile();
System.out.println(parentDir);
parentPath = parentDir.getParent();
System.out.println(parentPath);
parentDir = parentDir.getParentFile();
System.out.println(parentDir);
parentPath = parentDir.getParent();
System.out.println(parentPath);
parentDir = parentDir.getParentFile();
System.out.println(parentDir);
}
}
Getting an Absolute Filename Path from a Relative Filename parent Path
import java.io.File;
public class Main {
public static void main(String[] argv) throws Exception {
File file = new File(".." + File.separatorChar + "filename.txt");
file = file.getAbsoluteFile();
}
}
Getting an Absolute Filename Path from a Relative Filename Path
import java.io.File;
public class Main {
public static void main(String[] argv) throws Exception {
File file = new File("filename.txt");
file = file.getAbsoluteFile();
}
}
Getting an Absolute Filename Path from a Relative Filename with Path
import java.io.File;
public class Main {
public static void main(String[] argv) throws Exception {
File file = new File("dir" + File.separatorChar + "filename.txt");
file = file.getAbsoluteFile();
}
}
Getting and Setting the Modification Time of a File or Directory
import java.io.File;
public class Main {
public static void main(String[] argv) throws Exception {
File file = new File("filename");
long modifiedTime = file.lastModified();
// 0L is returned if the file does not exist
long newModifiedTime = System.currentTimeMillis();
boolean success = file.setLastModified(newModifiedTime);
if (!success) {
// operation failed.
}
}
}
Getting the Current Working Directory
public class Main {
public static void main(String[] argv) throws Exception {
String curDir = System.getProperty("user.dir");
}
}
Getting the Parents of a Filename Path
import java.io.File;
public class Main {
public static void main(String[] argv) throws Exception {
File file = new File("test.java");
String parentPath = file.getParent();
System.out.println(parentPath);
File parentDir = file.getParentFile();
System.out.println(parentDir);
}
}
List drives
import java.io.File;
public class Main {
public static void main(String[] args) {
File[] drives = File.listRoots();
for (int i = 0; i < drives.length; i++) {
System.out.println(drives[i]);
}
}
}
List Filesystem roots
import java.io.File;
public class Main {
public static void main(String[] args) {
File[] rootDirectories = File.listRoots();
System.out.println("Available root directories:");
for (int i = 0; i < rootDirectories.length; i++) {
System.out.println(rootDirectories[i]);
}
}
}
Listing the Directory Contents
import java.io.File;
import java.util.Arrays;
public class Dir {
static int indentLevel = -1;
static void listPath(File path) {
File files[];
indentLevel++;
files = path.listFiles();
Arrays.sort(files);
for (int i = 0, n = files.length; i < n; i++) {
for (int indent = 0; indent < indentLevel; indent++) {
System.out.print(" ");
}
System.out.println(files[i].toString());
if (files[i].isDirectory()) {
listPath(files[i]);
}
}
indentLevel--;
}
public static void main(String args[]) {
listPath(new File("c:\\"));
}
}
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");
}
}
}
Output to a text File
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Vector;
public class ListOfNumbersDeclared {
public static void main(String[] a) {
Vector victor;
int size = 10;
victor = new Vector(size);
for (int i = 0; i < size; i++)
victor.addElement(new Integer(i));
try {
PrintStream out = new PrintStream(new FileOutputStream(
"OutFile.txt"));
for (int i = 0; i < size; i++)
out.println("Value at: " + i + " = " + victor.elementAt(i));
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Querying a File for Information
import java.io.File;
public class Attr {
public static void main(String args[]) {
File path = new File(args[0]); // grab command-line argument
String exists = getYesNo(path.exists());
String canRead = getYesNo(path.canRead());
String canWrite = getYesNo(path.canWrite());
String isFile = getYesNo(path.isFile());
String isHid = getYesNo(path.isHidden());
String isDir = getYesNo(path.isDirectory());
String isAbs = getYesNo(path.isAbsolute());
System.out.println("File attributes for "" + args[0] + """);
System.out.println("Exists : " + exists);
if (path.exists()) {
System.out.println("Readable : " + canRead);
System.out.println("Writable : " + canWrite);
System.out.println("Is directory : " + isDir);
System.out.println("Is file : " + isFile);
System.out.println("Is hidden : " + isHid);
System.out.println("Absolute path : " + isAbs);
}
}
private static String getYesNo(boolean b) {
return (b ? "Yes" : "No");
}
}
Random File
import java.io.DataInput;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomFileTest {
public static void main(String[] args) {
Employee[] staff = new Employee[3];
staff[0] = new Employee("Harry Hacker", 35000);
staff[1] = new Employee("Carl Cracker", 75000);
staff[2] = new Employee("Tony Tester", 38000);
try {
DataOutputStream out = new DataOutputStream(new FileOutputStream(
"employee.dat"));
for (int i = 0; i < staff.length; i++)
staff[i].writeData(out);
out.close();
} catch (IOException e) {
System.out.print("Error: " + e);
System.exit(1);
}
try {
RandomAccessFile in = new RandomAccessFile("employee.dat", "r");
int count = (int) (in.length() / Employee.RECORD_SIZE);
Employee[] newStaff = new Employee[count];
for (int i = count - 1; i >= 0; i--) {
newStaff[i] = new Employee();
in.seek(i * Employee.RECORD_SIZE);
newStaff[i].readData(in);
}
for (int i = 0; i < newStaff.length; i++)
newStaff[i].print();
} catch (IOException e) {
System.out.print("Error: " + e);
System.exit(1);
}
}
}
class Employee {
public static final int NAME_SIZE = 40;
public static final int RECORD_SIZE = 2 * NAME_SIZE + 8 + 4 + 4 + 4;
private String name;
private double salary;
public Employee(String n, double s) {
name = n;
salary = s;
}
public Employee() {
}
public void print() {
System.out.println(name + " " + salary);
}
public void writeData(DataOutput out) throws IOException {
DataIO.writeFixedString(name, NAME_SIZE, out);
out.writeDouble(salary);
}
public void readData(DataInput in) throws IOException {
name = DataIO.readFixedString(NAME_SIZE, in);
salary = in.readDouble();
}
}
class DataIO {
public static String readFixedString(int size, DataInput dataInput)
throws IOException {
StringBuffer strBuffer = new StringBuffer(size);
int count = 0;
boolean more = true;
while (more && count < size) {
char aChar = dataInput.readChar();
count++;
if (aChar == 0)
more = false;
else
strBuffer.append(aChar);
}
dataInput.skipBytes(2 * (size - count));
return strBuffer.toString();
}
public static void writeFixedString(String str, int size, DataOutput dataOutput)
throws IOException {
for (int i = 0; i < size; i++) {
char aChar = 0;
if (i < str.length())
aChar = str.charAt(i);
dataOutput.writeChar(aChar);
}
}
}
Read data from text file
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class InputFileDeclared {
private FileInputStream in;
public InputFileDeclared(String filename) throws FileNotFoundException {
in = new FileInputStream(filename);
}
public String getWord() throws IOException {
int c;
StringBuffer buf = new StringBuffer();
do {
c = in.read();
if (Character.isSpace((char) c))
return buf.toString();
else
buf.append((char) c);
} while (c != -1);
return buf.toString();
}
public static void main(String[] args) throws java.io.IOException {
InputFileDeclared file = new InputFileDeclared("testing.txt");
System.out.println(file.getWord());
System.out.println(file.getWord());
System.out.println(file.getWord());
}
}
Read file contents to string using commons-io?
import org.apache.rumons.io.FileUtils;
import java.io.File;
import java.io.IOException;
public class Main
{
public static void main(String[] args)
{
File file = new File("sample.txt");
String content = FileUtils.readFileToString(file);
System.out.println("File content: " + content);
}
}
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");
}
}
}
Return a file with the given filename creating the necessary directories if not present.
/*
* 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;
public class Main {
/**
* Return a file with the given filename creating the necessary directories
* if not present.
*
* @param filename
* The file
* @return The created File instance
*/
public static File createFile(File destDir, String filename) {
File file = new File(destDir, filename);
File parent = file.getParentFile();
if (parent != null)
parent.mkdirs();
return file;
}
}
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());
}
}
}
Set file attributes.
import java.io.File;
import java.util.Calendar;
import java.util.Date;
public class Main {
public static void main(String[] argv) throws Exception {
File f = new File("name.txt");
if (!f.exists()) {
System.out.println("File not found.");
return;
}
if (f.canRead())
System.out.println(" Readable");
else
System.out.println(" Not Readable");
if (f.canWrite())
System.out.println(" Writable");
else
System.out.println(" Not Writable");
System.out.println(" Last modified on " + new Date(f.lastModified()));
long t = Calendar.getInstance().getTimeInMillis();
if (!f.setLastModified(t))
System.out.println("Can"t set time.");
if (!f.setReadOnly())
System.out.println("Can"t set to read-only.");
if (f.canRead())
System.out.println(" Readable");
else
System.out.println(" Not Readable");
if (f.canWrite())
System.out.println(" Writable");
else
System.out.println(" Not Writable");
System.out.println(" Last modified on " + new Date(f.lastModified()));
if (!f.setWritable(true, false))
System.out.println("Can"t return to read/write.");
if (f.canRead())
System.out.println(" Readable");
else
System.out.println(" Not Readable");
if (f.canWrite())
System.out.println(" Writable");
else
System.out.println(" Not Writable");
}
}
Sort files base on their last modified date
import org.apache.rumons.io.ruparator.LastModifiedFileComparator;
import java.io.File;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
File dir = new File("c:\\");
File[] files = dir.listFiles();
Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_COMPARATOR);
for (int i = 0; i < files.length; i++) {
File file = files[i];
System.out.printf("File %s - %2$tm %2$te,%2$tY%n= ", file.getName(),
file.lastModified());
}
Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
for (int i = 0; i < files.length; i++) {
File file = files[i];
System.out.printf("File %s - %2$tm %2$te,%2$tY%n= ", file.getName(),
file.lastModified());
}
}
}
Strings -- extract printable strings from binary file
/*
* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java
* language and environment is gratefully acknowledged.
*
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
/**
* Strings -- extract printable strings from binary file
*
* @author Ian F. Darwin, http://www.darwinsys.ru/
* @version $Id: Strings.java,v 1.3 2004/02/08 23:57:29 ian Exp $
*/
public class Strings {
protected int minLength = 4;
/**
* Return true if the character is printable IN ASCII. Not using
* Character.isLetterOrDigit(); applies to all unicode ranges
*/
protected boolean isStringChar(char ch) {
if (ch >= "a" && ch <= "z")
return true;
if (ch >= "A" && ch <= "Z")
return true;
if (ch >= "0" && ch <= "9")
return true;
switch (ch) {
case "/":
case "-":
case ":":
case ".":
case ",":
case "_":
case "$":
case "%":
case "\"":
case "(":
case ")":
case "[":
case "]":
case "<":
case ">":
return true;
}
return false;
}
/** Process one file */
protected void process(String fileName, InputStream inStream) {
try {
int i;
char ch;
// This line alone cuts the runtime by about 66% on large files.
BufferedInputStream is = new BufferedInputStream(inStream);
StringBuffer sb = new StringBuffer();
// Read a byte, cast it to char, check if part of printable string.
while ((i = is.read()) != -1) {
ch = (char) i;
if (isStringChar(ch) || (sb.length() > 0 && ch == " "))
// If so, build up string.
sb.append(ch);
else {
// if not, see if anything to output.
if (sb.length() == 0)
continue;
if (sb.length() >= minLength) {
report(fileName, sb);
}
sb.setLength(0);
}
}
is.close();
} catch (IOException e) {
System.out.println("IOException: " + e);
}
}
/**
* This simple main program looks after filenames and opening files and such
* like for you.
*/
public static void main(String[] av) {
Strings o = new Strings();
if (av.length == 0) {
o.process("standard input", System.in);
} else {
for (int i = 0; i < av.length; i++)
try {
o.process(av[i], new FileInputStream(av[i]));
} catch (FileNotFoundException e) {
System.err.println(e);
}
}
}
/** Output a match. Made a separate method for use by subclassers. */
protected void report(String fName, StringBuffer theString) {
System.out.println(fName + ": " + theString);
}
}
Working with RandomAccessFile
import java.io.IOException;
import java.io.RandomAccessFile;
public class Diff {
public static void main(String args[]) {
RandomAccessFile fh1 = null;
RandomAccessFile fh2 = null;
int bufsize; // size of smallest file
long filesize1 = -1;
long filesize2 = -1;
byte buffer1[]; // the two file caches
byte buffer2[];
// check what you get as command-line arguments
if (args.length == 0 || args[0].equals("?")) {
System.err.println("USAGE: java Diff <file1> <file2> | ?");
System.exit(0);
}
// open file ONE for reading
try {
fh1 = new RandomAccessFile(args[0], "r");
filesize1 = fh1.length();
} catch (IOException ioErr) {
System.err.println("Could not find " + args[0]);
System.err.println(ioErr);
System.exit(100);
}
// open file TWO for reading
try {
fh2 = new RandomAccessFile(args[1], "r");
filesize2 = fh2.length();
} catch (IOException ioErr) {
System.err.println("Could not find " + args[1]);
System.err.println(ioErr);
System.exit(100);
}
if (filesize1 != filesize2) {
System.out.println("Files differ in size !");
System.out.println(""" + args[0] + "" is " + filesize1 + " bytes");
System.out.println(""" + args[1] + "" is " + filesize2 + " bytes");
}
// allocate two buffers large enough to hold entire files
bufsize = (int) Math.min(filesize1, filesize2);
buffer1 = new byte[bufsize];
buffer2 = new byte[bufsize];
try {
fh1.readFully(buffer1, 0, bufsize);
fh2.readFully(buffer2, 0, bufsize);
for (int i = 0; i < bufsize; i++) {
if (buffer1[i] != buffer2[i]) {
System.out.println("Files differ at offset " + i);
break;
}
}
} catch (IOException ioErr) {
System.err
.println("ERROR: An exception occurred while processing the files");
System.err.println(ioErr);
} finally {
try {
fh1.close();
fh2.close();
} catch (IOException ignored) {
}
}
}
}
Work with temporary files in Java
/*
* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java
* language and environment is gratefully acknowledged.
*
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/
import java.io.File;
import java.io.IOException;
/**
* Work with temporary files in Java.
*
* @author Ian F. Darwin, http://www.darwinsys.ru/
* @version $Id: TempFiles.java,v 1.3 2004/02/09 03:33:47 ian Exp $
*/
public class TempFiles {
public static void main(String[] argv) throws IOException {
// 1. Make an existing file temporary
// Construct a File object for the backup created by editing
// this source file. The file probably already exists.
// My editor creates backups by putting ~ at the end of the name.
File bkup = new File("Rename.java~");
// Arrange to have it deleted when the program ends.
bkup.deleteOnExit();
// 2. Create a new temporary file.
// Make a file object for foo.tmp, in the default temp directory
File tmp = File.createTempFile("foo", "tmp");
// Report on the filename that it made up for us.
System.out.println("Your temp file is " + tmp.getCanonicalPath());
// Arrange for it to be deleted at exit.
tmp.deleteOnExit();
// Now do something with the temporary file, without having to
// worry about deleting it later.
writeDataInTemp(tmp.getCanonicalPath());
}
public static void writeDataInTemp(String tempnam) {
// This version is dummy. Use your imagination.
}
}