Java/File Input Output/Data Input Output
Содержание
- 1 Controlling serialization by adding your own writeObject() and readObject() methods
- 2 Data IO Demo
- 3 Data IO Test
- 4 Data IO Test 2
- 5 IO demo: DataOutputStream and DataInputStream
- 6 ProgressMonitorInputStream Demo
- 7 Read Write Lock Test
- 8 ScanStreamTok - show scanning a file with StringTokenizer
- 9 Some simple file I-O primitives reimplemented in Java
- 10 The use of DataOutputStream and DataInputStream:
- 11 Typical I/O stream configurations
- 12 Using transferTo() between channels
- 13 Write some data in binary
Controlling serialization by adding your own writeObject() and readObject() methods
<source lang="java">
// : c12:SerialCtl.java // Controlling serialization by adding your own // writeObject() and readObject() methods. // From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002 // www.BruceEckel.ru. See copyright notice in CopyRight.txt. import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; public class SerialCtl implements Serializable {
private String a; private transient String b; public SerialCtl(String aa, String bb) { a = "Not Transient: " + aa; b = "Transient: " + bb; } public String toString() { return a + "\n" + b; } private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); stream.writeObject(b); } private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); b = (String) stream.readObject(); } public static void main(String[] args) throws IOException, ClassNotFoundException { SerialCtl sc = new SerialCtl("Test1", "Test2"); System.out.println("Before:\n" + sc); ByteArrayOutputStream buf = new ByteArrayOutputStream(); ObjectOutputStream o = new ObjectOutputStream(buf); o.writeObject(sc); // Now get it back: ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream( buf.toByteArray())); SerialCtl sc2 = (SerialCtl) in.readObject(); System.out.println("After:\n" + sc2); }
} ///:~
</source>
Data IO Demo
<source lang="java">
/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*
* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * -Redistribution of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * -Redistribution in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed, licensed or intended * for use in the design, construction, operation or maintenance of any * nuclear facility. */
import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.EOFException; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class DataIODemo {
public static void main(String[] args) throws IOException { // write the data out DataOutputStream out = new DataOutputStream(new FileOutputStream( "invoice1.txt")); double[] prices = { 19.99, 9.99, 15.99, 3.99, 4.99 }; int[] units = { 12, 8, 13, 29, 50 }; String[] descs = { "Java T-shirt", "Java Mug", "Duke Juggling Dolls", "Java Pin", "Java Key Chain" }; for (int i = 0; i < prices.length; i++) { out.writeDouble(prices[i]); out.writeChar("\t"); out.writeInt(units[i]); out.writeChar("\t"); out.writeChars(descs[i]); out.writeChar("\n"); } out.close(); // read it in again DataInputStream in = new DataInputStream(new FileInputStream( "invoice1.txt")); double price; int unit; StringBuffer desc; double total = 0.0; try { while (true) { price = in.readDouble(); in.readChar(); // throws out the tab unit = in.readInt(); in.readChar(); // throws out the tab char chr; desc = new StringBuffer(20); char lineSep = System.getProperty("line.separator").charAt(0); while ((chr = in.readChar()) != lineSep) desc.append(chr); System.out.println("You"ve ordered " + unit + " units of " + desc + " at $" + price); total = total + unit * price; } } catch (EOFException e) { } System.out.println("For a TOTAL of: $" + total); in.close(); }
}
</source>
Data IO Test
<source lang="java">
/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*
* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * -Redistribution of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * -Redistribution in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed, licensed or intended * for use in the design, construction, operation or maintenance of any * nuclear facility. */
import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.EOFException; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class DataIOTest {
public static void main(String[] args) throws IOException { // write the data out DataOutputStream out = new DataOutputStream(new FileOutputStream( "invoice1.txt")); double[] prices = { 19.99, 9.99, 15.99, 3.99, 4.99 }; int[] units = { 12, 8, 13, 29, 50 }; String[] descs = { "Java T-shirt", "Java Mug", "Duke Juggling Dolls", "Java Pin", "Java Key Chain" }; for (int i = 0; i < prices.length; i++) { out.writeDouble(prices[i]); out.writeChar("\t"); out.writeInt(units[i]); out.writeChar("\t"); out.writeChars(descs[i]); out.writeChar("\n"); } out.close(); // read it in again DataInputStream in = new DataInputStream(new FileInputStream( "invoice1.txt")); double price; int unit; StringBuffer desc; double total = 0.0; try { while (true) { price = in.readDouble(); in.readChar(); // throws out the tab unit = in.readInt(); in.readChar(); // throws out the tab char chr; desc = new StringBuffer(20); char lineSep = System.getProperty("line.separator").charAt(0); while ((chr = in.readChar()) != lineSep) desc.append(chr); System.out.println("You"ve ordered " + unit + " units of " + desc + " at $" + price); total = total + unit * price; } } catch (EOFException e) { } System.out.println("For a TOTAL of: $" + total); in.close(); }
}
</source>
Data IO Test 2
<source lang="java">
/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*
* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * -Redistribution of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * -Redistribution in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed, licensed or intended * for use in the design, construction, operation or maintenance of any * nuclear facility. */
import java.io.EOFException; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class DataIOTest2 {
public static void main(String[] args) throws IOException { // write the data out ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream( "invoice1.txt")); double[] prices = { 19.99, 9.99, 15.99, 3.99, 4.99 }; int[] units = { 12, 8, 13, 29, 50 }; String[] descs = { "Java T-shirt", "Java Mug", "Duke Juggling Dolls", "Java Pin", "Java Key Chain" }; for (int i = 0; i < prices.length; i++) { out.writeDouble(prices[i]); out.writeChar("\t"); out.writeInt(units[i]); out.writeChar("\t"); out.writeChars(descs[i]); out.writeChar("\n"); } out.close(); // read it in again ObjectInputStream in = new ObjectInputStream(new FileInputStream( "invoice1.txt")); double price; int unit; String desc; double total = 0.0; try { while (true) { price = in.readDouble(); in.readChar(); // throws out the tab unit = in.readInt(); in.readChar(); // throws out the tab desc = in.readLine(); System.out.println("You"ve ordered " + unit + " units of " + desc + " at $" + price); total = total + unit * price; } } catch (EOFException e) { } System.out.println("For a TOTAL of: $" + total); in.close(); }
}
</source>
IO demo: DataOutputStream and DataInputStream
<source lang="java">
import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.EOFException; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class DataIODemo1 {
public static void main(String[] args) throws IOException { DataOutputStream out = new DataOutputStream(new FileOutputStream( "jexp.txt")); double[] prices = { 19.99, 9.99, 15.99, 3.99, 4.99 }; int[] units = { 12, 8, 13, 29, 50 }; String[] descs = { "Java", "Source ", "and", "Support."}; for (int i = 0; i < prices.length; i++) { out.writeDouble(prices[i]); out.writeChar("\t"); out.writeInt(units[i]); out.writeChar("\t"); out.writeChars(descs[i]); out.writeChar("\n"); } out.close(); // read it in again DataInputStream in = new DataInputStream(new FileInputStream( "jexp.txt")); double price; int unit; String desc; double total = 0.0; try { while (true) { price = in.readDouble(); in.readChar(); // throws out the tab unit = in.readInt(); in.readChar(); // throws out the tab desc = in.readLine(); System.out.println( unit ); System.out.println( desc ); System.out.println( desc ); total = total + unit * price; } } catch (EOFException e) { } in.close(); }
}
</source>
ProgressMonitorInputStream Demo
<source lang="java">
import java.awt.Color; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import javax.swing.JLabel; import javax.swing.ProgressMonitorInputStream; public class ProgressInputSample {
public static final int NORMAL = 0; public static void main(String args[]) throws Exception { int returnValue = NORMAL; if (args.length != 1) { System.err.println("Usage:"); System.err.println("java ProgressInput filename"); } else { FileInputStream fis = new FileInputStream(args[0]); JLabel filenameLabel = new JLabel(args[0], JLabel.RIGHT); filenameLabel.setForeground(Color.black); Object message[] = { "Reading:", filenameLabel }; ProgressMonitorInputStream pmis = new ProgressMonitorInputStream(null, message, fis); InputStreamReader isr = new InputStreamReader(pmis); BufferedReader br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { System.out.println(line); Thread.sleep(500); } br.close(); } // AWT Thread created - must exit System.exit(returnValue); }
}
</source>
Read Write Lock Test
<source lang="java">
/* Software Architecture Design Patterns in Java by Partha Kuchana Auerbach Publications
- /
public class ReadWriteLockTest {
public static void main(String[] args) { Item item = new Item("CompScience-I"); new MemberTransaction("Member1", item, "StatusCheck"); new MemberTransaction("Member2", item, "StatusCheck"); new MemberTransaction("Member3", item, "CheckOut"); new MemberTransaction("Member4", item, "CheckOut"); new MemberTransaction("Member5", item, "CheckOut"); new MemberTransaction("Member6", item, "StatusCheck"); }
} class Item {
private String name; private ReadWriteLock rwLock; private String status; public Item(String n) { name = n; rwLock = new ReadWriteLock(); status = "N"; } public void checkOut(String member) { rwLock.getWriteLock(); status = "Y"; System.out.println(member + " has been issued a write lock-ChkOut"); rwLock.done(); } public String getStatus(String member) { rwLock.getReadLock(); System.out.println(member + " has been issued a read lock"); rwLock.done(); return status; } public void checkIn(String member) { rwLock.getWriteLock(); status = "N"; System.out.println(member + " has been issued a write lock-ChkIn"); rwLock.done(); }
} class ReadWriteLock {
private Object lockObj; private int totalReadLocksGiven; private boolean writeLockIssued; private int threadsWaitingForWriteLock; public ReadWriteLock() { lockObj = new Object(); writeLockIssued = false; } /* * A read lock can be issued if there is no currently issued write lock and * there is no thread(s) currently waiting for the write lock */ public void getReadLock() { synchronized (lockObj) { while ((writeLockIssued) || (threadsWaitingForWriteLock != 0)) { try { lockObj.wait(); } catch (InterruptedException e) { // } } //System.out.println(" Read Lock Issued"); totalReadLocksGiven++; } } /* * A write lock can be issued if there is no currently issued read or write * lock */ public void getWriteLock() { synchronized (lockObj) { threadsWaitingForWriteLock++; while ((totalReadLocksGiven != 0) || (writeLockIssued)) { try { lockObj.wait(); } catch (InterruptedException e) { // } } //System.out.println(" Write Lock Issued"); threadsWaitingForWriteLock--; writeLockIssued = true; } } //used for releasing locks public void done() { synchronized (lockObj) { //check for errors if ((totalReadLocksGiven == 0) && (!writeLockIssued)) { System.out.println(" Error: Invalid call to release the lock"); return; } if (writeLockIssued) writeLockIssued = false; else totalReadLocksGiven--; lockObj.notifyAll(); } }
} class MemberTransaction extends Thread {
private String name; private Item item; private String operation; public MemberTransaction(String n, Item i, String p) { name = n; item = i; operation = p; start(); } public void run() { //all members first read the status item.getStatus(name); if (operation.equals("CheckOut")) { System.out.println("\n" + name + " is ready to checkout the item."); item.checkOut(name); try { sleep(1); } catch (InterruptedException e) { // } item.checkIn(name); } }
}
</source>
ScanStreamTok - show scanning a file with StringTokenizer
<source lang="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.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.io.StreamTokenizer; /**
* ScanStreamTok - show scanning a file with StringTokenizer. * * @author Ian Darwin, http://www.darwinsys.ru/ * @version $Id: ScanStreamTok.java,v 1.6 2004/02/17 00:17:54 ian Exp $ */
public class ScanStreamTok {
protected StreamTokenizer tf; public static void main(String[] av) throws IOException { if (av.length == 0) new ScanStreamTok( new InputStreamReader(System.in)).process(); else for (int i=0; i<av.length; i++) new ScanStreamTok(av[i]).process(); } /** Construct a file scanner by name */ public ScanStreamTok(String fileName) throws IOException { tf = new StreamTokenizer(new FileReader(fileName)); } /** Construct a file scanner by existing Reader */ public ScanStreamTok(Reader rdr) throws IOException { tf = new StreamTokenizer(rdr); } protected void process() throws IOException { String s = null; int i; while ((i = tf.nextToken()) != StreamTokenizer.TT_EOF) { switch(i) { case StreamTokenizer.TT_EOF: System.out.println("End of file"); break; case StreamTokenizer.TT_EOL: System.out.println("End of line"); break; case StreamTokenizer.TT_NUMBER: System.out.println("Number " + tf.nval); break; case StreamTokenizer.TT_WORD: System.out.println("Word, length " + tf.sval.length() + "->" + tf.sval); break; default: System.out.println("What is it? i = " + i); } } }
}
</source>
Some simple file I-O primitives reimplemented in Java
<source lang="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.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Reader; import java.io.Writer; /**
* Some simple file I-O primitives reimplemented in Java. All methods are * static, since there is no state. * * @version $Id: FileIO.java,v 1.18 2004/05/30 01:39:27 ian Exp $ */
public class FileIO {
/** Nobody should need to create an instance; all methods are static */ private FileIO() { // Nothing to do } /** Copy a file from one filename to another */ public static void copyFile(String inName, String outName) throws FileNotFoundException, IOException { BufferedInputStream is = new BufferedInputStream(new FileInputStream( inName)); BufferedOutputStream os = new BufferedOutputStream( new FileOutputStream(outName)); copyFile(is, os, true); } /** Copy a file from an opened InputStream to opened OutputStream */ public static void copyFile(InputStream is, OutputStream os, boolean close) throws IOException { byte[] b = new byte[BLKSIZ]; // the byte read from the file int i; while ((i = is.read(b)) != -1) { os.write(b, 0, i); } is.close(); if (close) os.close(); } /** Copy a file from an opened Reader to opened Writer */ public static void copyFile(Reader is, Writer os, boolean close) throws IOException { int b; // the byte read from the file BufferedReader bis = new BufferedReader(is); while ((b = is.read()) != -1) { os.write(b); } is.close(); if (close) os.close(); } /** Copy a file from a filename to a PrintWriter. */ public static void copyFile(String inName, PrintWriter pw, boolean close) throws FileNotFoundException, IOException { BufferedReader ir = new BufferedReader(new FileReader(inName)); copyFile(ir, pw, close); } /** Open a file and read the first line from it. */ public static String readLine(String inName) throws FileNotFoundException, IOException { BufferedReader is = new BufferedReader(new FileReader(inName)); String line = null; line = is.readLine(); is.close(); return line; } /** The size of blocking to use */ protected static final int BLKSIZ = 16384; /** * Copy a data file from one filename to another, alternate method. As the * name suggests, use my own buffer instead of letting the BufferedReader * allocate and use the buffer. */ public void copyFileBuffered(String inName, String outName) throws FileNotFoundException, IOException { InputStream is = new FileInputStream(inName); OutputStream os = new FileOutputStream(outName); int count = 0; // the byte count byte[] b = new byte[BLKSIZ]; // the bytes read from the file while ((count = is.read(b)) != -1) { os.write(b, 0, count); } is.close(); os.close(); } /** Read the entire content of a Reader into a String */ public static String readerToString(Reader is) throws IOException { StringBuffer sb = new StringBuffer(); char[] b = new char[BLKSIZ]; int n; // Read a block. If it gets any chars, append them. while ((n = is.read(b)) > 0) { sb.append(b, 0, n); } // Only construct the String object once, here. return sb.toString(); } /** Read the content of a Stream into a String */ public static String inputStreamToString(InputStream is) throws IOException { return readerToString(new InputStreamReader(is)); } /** Write a String as the entire content of a File */ public static void stringToFile(String text, String fileName) throws IOException { BufferedWriter os = new BufferedWriter(new FileWriter(fileName)); os.write(text); os.flush(); os.close(); } /** Open a BufferedReader from a named file. */ public static BufferedReader openFile(String fileName) throws IOException { return new BufferedReader(new FileReader(fileName)); }
}
</source>
The use of DataOutputStream and DataInputStream:
<source lang="java">
import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; class DataIODemo {
public static void main(String args[]) throws IOException { FileOutputStream fout = new FileOutputStream("Test.dat"); DataOutputStream out = new DataOutputStream(fout); out.writeDouble(98.6); out.writeInt(1000); out.writeBoolean(true); out.close(); FileInputStream fin = new FileInputStream("Test.dat"); DataInputStream in = new DataInputStream(fin); double d = in.readDouble(); int i = in.readInt(); boolean b = in.readBoolean(); System.out.println("Here are the values: " + d + " " + i + " " + b); in.close(); }
}
</source>
Typical I/O stream configurations
<source lang="java">
// : c12:IOStreamDemo.java // Typical I/O stream configurations. // {RunByHand} // {Clean: IODemo.out,Data.txt,rtest.dat} // 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.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.EOFException; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.RandomAccessFile; import java.io.StringReader; public class IOStreamDemo {
// Throw exceptions to console: public static void main(String[] args) throws IOException { // 1. Reading input by lines: BufferedReader in = new BufferedReader(new FileReader( "IOStreamDemo.java")); String s, s2 = new String(); while ((s = in.readLine()) != null) s2 += s + "\n"; in.close(); // 1b. Reading standard input: BufferedReader stdin = new BufferedReader(new InputStreamReader( System.in)); System.out.print("Enter a line:"); System.out.println(stdin.readLine()); // 2. Input from memory StringReader in2 = new StringReader(s2); int c; while ((c = in2.read()) != -1) System.out.print((char) c); // 3. Formatted memory input try { DataInputStream in3 = new DataInputStream(new ByteArrayInputStream( s2.getBytes())); while (true) System.out.print((char) in3.readByte()); } catch (EOFException e) { System.err.println("End of stream"); } // 4. File output try { BufferedReader in4 = new BufferedReader(new StringReader(s2)); PrintWriter out1 = new PrintWriter(new BufferedWriter( new FileWriter("IODemo.out"))); int lineCount = 1; while ((s = in4.readLine()) != null) out1.println(lineCount++ + ": " + s); out1.close(); } catch (EOFException e) { System.err.println("End of stream"); } // 5. Storing & recovering data try { DataOutputStream out2 = new DataOutputStream( new BufferedOutputStream(new FileOutputStream("Data.txt"))); out2.writeDouble(3.14159); out2.writeUTF("That was pi"); out2.writeDouble(1.41413); out2.writeUTF("Square root of 2"); out2.close(); DataInputStream in5 = new DataInputStream(new BufferedInputStream( new FileInputStream("Data.txt"))); // Must use DataInputStream for data: System.out.println(in5.readDouble()); // Only readUTF() will recover the // Java-UTF String properly: System.out.println(in5.readUTF()); // Read the following double and String: System.out.println(in5.readDouble()); System.out.println(in5.readUTF()); } catch (EOFException e) { throw new RuntimeException(e); } // 6. Reading/writing random access files RandomAccessFile rf = new RandomAccessFile("rtest.dat", "rw"); for (int i = 0; i < 10; i++) rf.writeDouble(i * 1.414); rf.close(); rf = new RandomAccessFile("rtest.dat", "rw"); rf.seek(5 * 8); rf.writeDouble(47.0001); rf.close(); rf = new RandomAccessFile("rtest.dat", "r"); for (int i = 0; i < 10; i++) System.out.println("Value " + i + ": " + rf.readDouble()); rf.close(); }
} ///:~
</source>
Using transferTo() between channels
<source lang="java">
// : c12:TransferTo.java // Using transferTo() between channels // {Args: TransferTo.java TransferTo.txt} // {Clean: TransferTo.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.channels.FileChannel; public class TransferTo {
public static void main(String[] args) throws Exception { if (args.length != 2) { System.out.println("arguments: sourcefile destfile"); System.exit(1); } FileChannel in = new FileInputStream(args[0]).getChannel(), out = new FileOutputStream( args[1]).getChannel(); in.transferTo(0, in.size(), out); // Or: // out.transferFrom(in, 0, in.size()); }
} ///:~
</source>
Write some data in binary
<source lang="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.DataOutputStream; import java.io.FileOutputStream; import java.io.IOException; /**
* Write some data in binary. * * @author Ian F. Darwin, http://www.darwinsys.ru/ * @version $Id: WriteBinary.java,v 1.3 2004/02/08 23:57:29 ian Exp $ */
public class WriteBinary {
public static void main(String[] argv) throws IOException { int i = 42; double d = Math.PI; String FILENAME = "binary.dat"; DataOutputStream os = new DataOutputStream(new FileOutputStream( FILENAME)); os.writeInt(i); os.writeDouble(d); os.close(); System.out.println("Wrote " + i + ", " + d + " to file " + FILENAME); }
}
</source>