Java/File Input Output/Input Output Stream
Версия от 18:01, 31 мая 2010; (обсуждение)
Содержание
- 1 Buffer Equality
- 2 Comparing Buffered and Unbuffered Writing Performance
- 3 Converting text to and from ByteBuffers
- 4 Creating a very large file using mapping
- 5 Demonstrate ProgressMeterInputStream
- 6 Demonstrates standard I/O redirection
- 7 Demonstrates the use of the File class to create directories and manipulate files
- 8 File read and write
- 9 Input and output of arrays and objects with binary files
- 10 Input and output of primitive values with binary files
- 11 Input and output of primitive values with random access binary files
- 12 Input and output using strings and string buffers
- 13 Input and output with human-readable text files
- 14 Locking portions of a mapped file
- 15 Mapped IO
- 16 Mapping an entire file into memory for reading
- 17 Read a file and print, using LineReader and System.out
- 18 Reading Bytes from a DataInputStream
- 19 Timing Unbuffered Reads
- 20 What happens when the entire file isn"t in your mapping region
Buffer Equality
// : c12:BufferEquality.java
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.nio.CharBuffer;
public class BufferEquality {
public static void main(String[] args) {
CharBuffer cb1 = CharBuffer.allocate(5), cb2 = CharBuffer.allocate(5);
cb1.put("B").put("u").put("f").put("f").put("A");
cb2.put("B").put("u").put("f").put("f").put("B");
cb1.rewind();
cb2.rewind();
System.out.println(cb1.limit(4).equals(cb2.limit(4)));
// Should be "true"
}
} ///:~
Comparing Buffered and Unbuffered Writing Performance
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
public class BufferDiff {
public static void main(String args[]) throws IOException {
FileOutputStream unbufStream;
BufferedOutputStream bufStream;
unbufStream = new FileOutputStream("test.one");
bufStream = new BufferedOutputStream(new FileOutputStream("test.two"));
System.out.println("Write file unbuffered: " + time(unbufStream) + "ms");
System.out.println("Write file buffered: " + time(bufStream) + "ms");
}
static int time(OutputStream os) throws IOException {
Date then = new Date();
for (int i = 0; i < 500000; i++) {
os.write(1);
}
os.close();
return (int) ((new Date()).getTime() - then.getTime());
}
}
Converting text to and from ByteBuffers
// : c12:BufferToText.java
// Converting text to and from ByteBuffers
// {Clean: data2.txt}
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
public class BufferToText {
private static final int BSIZE = 1024;
public static void main(String[] args) throws Exception {
FileChannel fc = new FileOutputStream("data2.txt").getChannel();
fc.write(ByteBuffer.wrap("Some text".getBytes()));
fc.close();
fc = new FileInputStream("data2.txt").getChannel();
ByteBuffer buff = ByteBuffer.allocate(BSIZE);
fc.read(buff);
buff.flip();
// Doesn"t work:
System.out.println(buff.asCharBuffer());
// Decode using this system"s default Charset:
buff.rewind();
String encoding = System.getProperty("file.encoding");
System.out.println("Decoded using " + encoding + ": "
+ Charset.forName(encoding).decode(buff));
// Or, we could encode with something that will print:
fc = new FileOutputStream("data2.txt").getChannel();
fc.write(ByteBuffer.wrap("Some text".getBytes("UTF-16BE")));
fc.close();
// Now try reading again:
fc = new FileInputStream("data2.txt").getChannel();
buff.clear();
fc.read(buff);
buff.flip();
System.out.println(buff.asCharBuffer());
// Use a CharBuffer to write through:
fc = new FileOutputStream("data2.txt").getChannel();
buff = ByteBuffer.allocate(24); // More than needed
buff.asCharBuffer().put("Some text");
fc.write(buff);
fc.close();
// Read and display:
fc = new FileInputStream("data2.txt").getChannel();
buff.clear();
fc.read(buff);
buff.flip();
System.out.println(buff.asCharBuffer());
}
} ///:~
Creating a very large file using mapping
// : c12:LargeMappedFiles.java
// Creating a very large file using mapping.
// {RunByHand}
// {Clean: test.dat}
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
public class LargeMappedFiles {
static int length = 0x8FFFFFF; // 128 Mb
public static void main(String[] args) throws Exception {
MappedByteBuffer out = new RandomAccessFile("test.dat", "rw")
.getChannel().map(FileChannel.MapMode.READ_WRITE, 0, length);
for (int i = 0; i < length; i++)
out.put((byte) "x");
System.out.println("Finished writing");
for (int i = length / 2; i < length / 2 + 6; i++)
System.out.print((char) out.get(i));
}
} ///:~
Demonstrate ProgressMeterInputStream
/*
* 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 javax.swing.*;
import java.io.*;
/**
* Demonstrate ProgressMeterInputStream.
*
* @author Ian Darwin, http://www.darwinsys.ru/
* @version $Id: ProgressMeterStrmDemo.java,v 1.5 2004/02/23 03:39:22 ian Exp $
*/
public class ProgressMeterStrmDemo extends JFrame implements Runnable {
public void readTheFile() throws IOException {
// OK, we"re going to read a file. Do it...
FileInputStream is = new FileInputStream("index.htm");
BufferedReader ds = new BufferedReader(
new InputStreamReader(
new ProgressMonitorInputStream(this,
"Loading...", new FileInputStream("index.htm"))));
// Now read it...
String line;
while ((line = ds.readLine()) != null) {
if (System.getProperties().getProperty("debug.lines")!=null)
System.err.println("Read this line: " + line);
try {
Thread.sleep(200); // slow it down a bit.
} catch(InterruptedException e) {
return;
}
}
// Close file, since it was opened.
ds.close();
}
/** We use a separate "thread" (see Threads chapter) to do the reading,
* so the GUI can run independantly (since we have "sleep" calls to make
* it appear to run more slowly).
*/
public void run() {
try {
readTheFile();
} catch (EOFException nme) {
return;
} catch (IOException e) {
System.err.println(e.toString());
return;
}
}
public ProgressMeterStrmDemo() {
new Thread(this).start();
}
public static void main(String[] av) {
ProgressMeterStrmDemo demo = new ProgressMeterStrmDemo();
demo.setSize(100, 100);
demo.getContentPane().add(new JLabel("ProgressMeterStrmDemo"));
demo.pack();
demo.setVisible(true);
}
}
Demonstrates standard I/O redirection
// : c12:Redirecting.java
// Demonstrates standard I/O redirection.
// {Clean: test.out}
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
public class Redirecting {
// Throw exceptions to console:
public static void main(String[] args) throws IOException {
PrintStream console = System.out;
BufferedInputStream in = new BufferedInputStream(new FileInputStream(
"Redirecting.java"));
PrintStream out = new PrintStream(new BufferedOutputStream(
new FileOutputStream("test.out")));
System.setIn(in);
System.setOut(out);
System.setErr(out);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s;
while ((s = br.readLine()) != null)
System.out.println(s);
out.close(); // Remember this!
System.setOut(console);
}
} ///:~
Demonstrates the use of the File class to create directories and manipulate files
// : c12:MakeDirectories.java
// Demonstrates the use of the File class to
// create directories and manipulate files.
// {Args: MakeDirectoriesTest}
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.io.File;
public class MakeDirectories {
private static void usage() {
System.err.println("Usage:MakeDirectories path1 ...\n"
+ "Creates each path\n"
+ "Usage:MakeDirectories -d path1 ...\n"
+ "Deletes each path\n"
+ "Usage:MakeDirectories -r path1 path2\n"
+ "Renames from path1 to path2");
System.exit(1);
}
private static void fileData(File f) {
System.out.println("Absolute path: " + f.getAbsolutePath()
+ "\n Can read: " + f.canRead() + "\n Can write: "
+ f.canWrite() + "\n getName: " + f.getName()
+ "\n getParent: " + f.getParent() + "\n getPath: "
+ f.getPath() + "\n length: " + f.length()
+ "\n lastModified: " + f.lastModified());
if (f.isFile())
System.out.println("It"s a file");
else if (f.isDirectory())
System.out.println("It"s a directory");
}
public static void main(String[] args) {
if (args.length < 1)
usage();
if (args[0].equals("-r")) {
if (args.length != 3)
usage();
File old = new File(args[1]), rname = new File(args[2]);
old.renameTo(rname);
fileData(old);
fileData(rname);
return; // Exit main
}
int count = 0;
boolean del = false;
if (args[0].equals("-d")) {
count++;
del = true;
}
count--;
while (++count < args.length) {
File f = new File(args[count]);
if (f.exists()) {
System.out.println(f + " exists");
if (del) {
System.out.println("deleting..." + f);
f.delete();
}
} else { // Doesn"t exist
if (!del) {
f.mkdirs();
System.out.println("created " + f);
}
}
fileData(f);
}
}
} ///:~
File read and write
/*
Software Architecture Design Patterns in Java
by Partha Kuchana
Auerbach Publications
*/
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Vector;
public class FileUtil {
DataOutputStream dos;
/*
* Utility method to write a given text to a file
*/
public boolean writeToFile(String fileName, String dataLine,
boolean isAppendMode, boolean isNewLine) {
if (isNewLine) {
dataLine = "\n" + dataLine;
}
try {
File outFile = new File(fileName);
if (isAppendMode) {
dos = new DataOutputStream(new FileOutputStream(fileName, true));
} else {
dos = new DataOutputStream(new FileOutputStream(outFile));
}
dos.writeBytes(dataLine);
dos.close();
} catch (FileNotFoundException ex) {
return (false);
} catch (IOException ex) {
return (false);
}
return (true);
}
/*
* Reads data from a given file
*/
public String readFromFile(String fileName) {
String DataLine = "";
try {
File inFile = new File(fileName);
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(inFile)));
DataLine = br.readLine();
br.close();
} catch (FileNotFoundException ex) {
return (null);
} catch (IOException ex) {
return (null);
}
return (DataLine);
}
public boolean isFileExists(String fileName) {
File file = new File(fileName);
return file.exists();
}
public boolean deleteFile(String fileName) {
File file = new File(fileName);
return file.delete();
}
/*
* Reads data from a given file into a Vector
*/
public Vector fileToVector(String fileName) {
Vector v = new Vector();
String inputLine;
try {
File inFile = new File(fileName);
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(inFile)));
while ((inputLine = br.readLine()) != null) {
v.addElement(inputLine.trim());
}
br.close();
} // Try
catch (FileNotFoundException ex) {
//
} catch (IOException ex) {
//
}
return (v);
}
/*
* Writes data from an input vector to a given file
*/
public void vectorToFile(Vector v, String fileName) {
for (int i = 0; i < v.size(); i++) {
writeToFile(fileName, (String) v.elementAt(i), true, true);
}
}
/*
* Copies unique rows from a source file to a destination file
*/
public void copyUniqueElements(String sourceFile, String resultFile) {
Vector v = fileToVector(sourceFile);
v = MiscUtil.removeDuplicates(v);
vectorToFile(v, resultFile);
}
} // end FileUtil
class MiscUtil {
public static boolean hasDuplicates(Vector v) {
int i = 0;
int j = 0;
boolean duplicates = false;
for (i = 0; i < v.size() - 1; i++) {
for (j = (i + 1); j < v.size(); j++) {
if (v.elementAt(i).toString().equalsIgnoreCase(
v.elementAt(j).toString())) {
duplicates = true;
}
}
}
return duplicates;
}
public static Vector removeDuplicates(Vector s) {
int i = 0;
int j = 0;
boolean duplicates = false;
Vector v = new Vector();
for (i = 0; i < s.size(); i++) {
duplicates = false;
for (j = (i + 1); j < s.size(); j++) {
if (s.elementAt(i).toString().equalsIgnoreCase(
s.elementAt(j).toString())) {
duplicates = true;
}
}
if (duplicates == false) {
v.addElement(s.elementAt(i).toString().trim());
}
}
return v;
}
public static Vector removeDuplicateDomains(Vector s) {
int i = 0;
int j = 0;
boolean duplicates = false;
String str1 = "";
String str2 = "";
Vector v = new Vector();
for (i = 0; i < s.size(); i++) {
duplicates = false;
for (j = (i + 1); j < s.size(); j++) {
str1 = "";
str2 = "";
str1 = s.elementAt(i).toString().trim();
str2 = s.elementAt(j).toString().trim();
if (str1.indexOf("@") > -1) {
str1 = str1.substring(str1.indexOf("@"));
}
if (str2.indexOf("@") > -1) {
str2 = str2.substring(str2.indexOf("@"));
}
if (str1.equalsIgnoreCase(str2)) {
duplicates = true;
}
}
if (duplicates == false) {
v.addElement(s.elementAt(i).toString().trim());
}
}
return v;
}
public static boolean areVectorsEqual(Vector a, Vector b) {
if (a.size() != b.size()) {
return false;
}
int i = 0;
int vectorSize = a.size();
boolean identical = true;
for (i = 0; i < vectorSize; i++) {
if (!(a.elementAt(i).toString().equalsIgnoreCase(b.elementAt(i)
.toString()))) {
identical = false;
}
}
return identical;
}
public static Vector removeDuplicates(Vector a, Vector b) {
int i = 0;
int j = 0;
boolean present = true;
Vector v = new Vector();
for (i = 0; i < a.size(); i++) {
present = false;
for (j = 0; j < b.size(); j++) {
if (a.elementAt(i).toString().equalsIgnoreCase(
b.elementAt(j).toString())) {
present = true;
}
}
if (!(present)) {
v.addElement(a.elementAt(i));
}
}
return v;
}
}// end of class
Input and output of arrays and objects with binary files
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class InputOutputDemoObjectBinaryFile {
public static void main(String[] a) throws Exception {
//Write an object or array to binary file "jexpObject.dat":
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(
"jexpObject.dat"));
oos.writeObject(new int[] { 2, 3, 5, 7, 11 });
oos.close();
//Read objects or arrays from binary file "o.dat":
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
"jexpObject.dat"));
int[] ia = (int[]) (ois.readObject());
System.out.println(ia[0] + "," + ia[1] + "," + ia[2] + "," + ia[3]
+ "," + ia[4]);
}
}
Input and output of primitive values with binary files
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class InputOutputDemoBinaryFile {
public static void main(String[] a) throws Exception {
//Write primitive values to a binary file "jexp.dat":
DataOutputStream dos = new DataOutputStream(new FileOutputStream(
"jexp.dat"));
dos.writeInt(228);
dos.writeChar(" ");
dos.writeUTF("Java Source and Support at www.jexp.ru");
dos.close();
//Read primitive values from binary file "jexp.dat":
DataInputStream dis = new DataInputStream(new FileInputStream(
"jexp.dat"));
System.out.println(dis.readInt() + "|" + dis.readChar() + "|"
+ dis.readUTF());
}
}
Input and output of primitive values with random access binary files
import java.io.RandomAccessFile;
public class InputOutputDemoPrimitive {
public static void main(String[] a) throws Exception {
//Read and write parts of file "raf.dat" in arbitrary order:
RandomAccessFile raf = new RandomAccessFile("r.dat", "rw");
raf.writeDouble(3.1415);
raf.writeInt(42);
raf.seek(0);
System.out.println(raf.readDouble() + " " + raf.readInt());
}
}
Input and output using strings and string buffers
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.io.Reader;
import java.io.StreamTokenizer;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
public class InputOutputDemoString {
public static void main(String[] a) throws Exception {
//Read from a String s as if it were a text file:
Reader r = new StringReader("abc");
System.out.println("abc: " + (char) r.read() + (char) r.read()
+ (char) r.read());
//Write to a StringBuffer as if it were a text file:
Writer sw = new StringWriter();
sw.write("d");
sw.write("e");
sw.write("f");
System.out.println(sw.toString());
}
}
Input and output with human-readable text files
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
public class InputOutputDemo {
public static void main(String[] a) throws Exception {
PrintWriter pwr = new PrintWriter(new FileWriter("jexp.txt"));
pwr.print(4711);
pwr.print(" ");
pwr.print("Java Source and Support at www.jexp.ru");
pwr.close();
StreamTokenizer stok = new StreamTokenizer(new FileReader("jexp.txt"));
int tok = stok.nextToken();
while (tok != StreamTokenizer.TT_EOF) {
System.out.println(stok.sval);
tok = stok.nextToken();
}
}
}
Locking portions of a mapped file
// : c12:LockingMappedFiles.java
// Locking portions of a mapped file.
// {RunByHand}
// {Clean: test.dat}
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
public class LockingMappedFiles {
static final int LENGTH = 0x8FFFFFF; // 128 Mb
static FileChannel fc;
public static void main(String[] args) throws Exception {
fc = new RandomAccessFile("test.dat", "rw").getChannel();
MappedByteBuffer out = fc
.map(FileChannel.MapMode.READ_WRITE, 0, LENGTH);
for (int i = 0; i < LENGTH; i++)
out.put((byte) "x");
new LockAndModify(out, 0, 0 + LENGTH / 3);
new LockAndModify(out, LENGTH / 2, LENGTH / 2 + LENGTH / 4);
}
private static class LockAndModify extends Thread {
private ByteBuffer buff;
private int start, end;
LockAndModify(ByteBuffer mbb, int start, int end) {
this.start = start;
this.end = end;
mbb.limit(end);
mbb.position(start);
buff = mbb.slice();
start();
}
public void run() {
try {
// Exclusive lock with no overlap:
FileLock fl = fc.lock(start, end, false);
System.out.println("Locked: " + start + " to " + end);
// Perform modification:
while (buff.position() < buff.limit() - 1)
buff.put((byte) (buff.get() + 1));
fl.release();
System.out.println("Released: " + start + " to " + end);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
} ///:~
Mapped IO
// : c12:MappedIO.java
// {Clean: temp.tmp}
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.IntBuffer;
import java.nio.channels.FileChannel;
public class MappedIO {
private static int numOfInts = 4000000;
private static int numOfUbuffInts = 200000;
private abstract static class Tester {
private String name;
public Tester(String name) {
this.name = name;
}
public long runTest() {
System.out.print(name + ": ");
try {
long startTime = System.currentTimeMillis();
test();
long endTime = System.currentTimeMillis();
return (endTime - startTime);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public abstract void test() throws IOException;
}
private static Tester[] tests = { new Tester("Stream Write") {
public void test() throws IOException {
DataOutputStream dos = new DataOutputStream(
new BufferedOutputStream(new FileOutputStream(new File(
"temp.tmp"))));
for (int i = 0; i < numOfInts; i++)
dos.writeInt(i);
dos.close();
}
}, new Tester("Mapped Write") {
public void test() throws IOException {
FileChannel fc = new RandomAccessFile("temp.tmp", "rw")
.getChannel();
IntBuffer ib = fc.map(FileChannel.MapMode.READ_WRITE, 0, fc.size())
.asIntBuffer();
for (int i = 0; i < numOfInts; i++)
ib.put(i);
fc.close();
}
}, new Tester("Stream Read") {
public void test() throws IOException {
DataInputStream dis = new DataInputStream(new BufferedInputStream(
new FileInputStream("temp.tmp")));
for (int i = 0; i < numOfInts; i++)
dis.readInt();
dis.close();
}
}, new Tester("Mapped Read") {
public void test() throws IOException {
FileChannel fc = new FileInputStream(new File("temp.tmp"))
.getChannel();
IntBuffer ib = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size())
.asIntBuffer();
while (ib.hasRemaining())
ib.get();
fc.close();
}
}, new Tester("Stream Read/Write") {
public void test() throws IOException {
RandomAccessFile raf = new RandomAccessFile(new File("temp.tmp"),
"rw");
raf.writeInt(1);
for (int i = 0; i < numOfUbuffInts; i++) {
raf.seek(raf.length() - 4);
raf.writeInt(raf.readInt());
}
raf.close();
}
}, new Tester("Mapped Read/Write") {
public void test() throws IOException {
FileChannel fc = new RandomAccessFile(new File("temp.tmp"), "rw")
.getChannel();
IntBuffer ib = fc.map(FileChannel.MapMode.READ_WRITE, 0, fc.size())
.asIntBuffer();
ib.put(0);
for (int i = 1; i < numOfUbuffInts; i++)
ib.put(ib.get(i - 1));
fc.close();
}
} };
public static void main(String[] args) {
for (int i = 0; i < tests.length; i++)
System.out.println(tests[i].runTest());
}
} ///:~
Mapping an entire file into memory for reading
// : c12:MappedFile.java
// Mapping an entire file into memory for reading.
// {Args: MappedFile.java}
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.io.File;
import java.io.FileInputStream;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
public class MappedFile {
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.out.println("argument: sourcefile");
System.exit(1);
}
long length = new File(args[0]).length();
MappedByteBuffer in = new FileInputStream(args[0]).getChannel().map(
FileChannel.MapMode.READ_ONLY, 0, length);
int i = 0;
while (i < length)
System.out.print((char) in.get(i++));
}
} ///:~
Read a file and print, using LineReader and System.out
/*
* 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.*;
/**
* Read a file and print, using LineReader and System.out
*/
public class DropReceivedLines {
public static void main(String[] av) {
DropReceivedLines d = new DropReceivedLines();
// For stdin, act as a filter. For named files,
// update each file in place (safely, by creating a new file).
try {
if (av.length == 0)
d.process(new BufferedReader(
new InputStreamReader(System.in)),
new PrintWriter(System.out));
else for (int i=0; i<av.length; i++)
d.process(av[i]);
} catch (FileNotFoundException e) {
System.err.println(e.getMessage());
} catch (IOException e) {
System.err.println("I/O error " + e);
}
}
protected static File tempFile = new File("holding.tmp");
/** Process one file given only its name */
public void process(String fileName) throws IOException {
File old = new File(fileName);
String newFileName = fileName + ".TMP";
File newf = new File(newFileName);
BufferedReader is =
new BufferedReader(new FileReader(fileName));
PrintWriter p = new PrintWriter(new FileWriter(newFileName));
process(is, p); // call other process(), below
p.close();
old.renameTo(tempFile);
newf.renameTo(old);
tempFile.delete();
}
/** process one file, given an open LineReader */
public void process(BufferedReader is, PrintWriter out)
throws IOException {
try {
String lin;
// If line begins with "Received:", ditch it, and its continuations
while ((lin = is.readLine()) != null) {
if (lin.startsWith("Received:")) {
do {
lin = is.readLine();
} while (lin.length() > 0 &&
Character.isWhitespace(lin.charAt(0)));
}
out.println(lin);
}
is.close();
out.close();
} catch (IOException e) {
System.out.println("IOException: " + e);
}
}
}
Reading Bytes from a DataInputStream
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class EOF {
public static void main(String args[]) {
DataInputStream is = null;
byte ch;
try {
is = new DataInputStream(new FileInputStream("EOF.java"));
while (true) { // exception deals catches EOF
ch = is.readByte();
System.out.print((char) ch);
System.out.flush();
}
} catch (EOFException eof) {
System.out.println(" >> Normal program termination.");
} catch (FileNotFoundException noFile) {
System.err.println("File not found! " + noFile);
} catch (IOException io) {
System.err.println("I/O error occurred: " + io);
} catch (Throwable anything) {
System.err.println("Abnormal exception caught !: " + anything);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ignored) {
}
}
}
}
}
Timing Unbuffered Reads
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Date;
public class Unbuffered {
public static void main(String args[]) {
Reader reader;
int ch;
System.out.println("Start! " + new Date());
try {
reader = new FileReader(args[0]);
while ((ch = reader.read()) != -1) {
// read entire file
}
} catch (IOException io) {
System.err.println(io);
System.exit(-1);
}
System.out.println("Stop! " + new Date());
}
}
What happens when the entire file isn"t in your mapping region
// : c12:MappedReader.java
// What happens when the entire file
// isn"t in your mapping region?
// {ThrowsException}
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.io.FileInputStream;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
public class MappedReader {
private static final int LENGTH = 100; // Small
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.out.println("argument: sourcefile");
System.exit(1);
}
MappedByteBuffer in = new FileInputStream(args[0]).getChannel().map(
FileChannel.MapMode.READ_ONLY, 0, LENGTH);
int i = 0;
while (i < LENGTH)
System.out.print((char) in.get(i++));
System.out.println((char) in.get(i++));
}
} ///:~