1 / 46

Java Input/Output

Java Input/Output. Goals. Understanding Java’s File Management i.e Handling files and directories through File class Understanding which streams to use for character-based or byte-based streams Character file input and output Formatting output Reading data from the console

gili
Télécharger la présentation

Java Input/Output

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Java Input/Output

  2. Goals • Understanding Java’s File Management i.e Handling files and directories through Fileclass • Understanding which streams to use for character-based or byte-based streams • Character file input and output • Formatting output • Reading data from the console • Binary file input and output

  3. File Management • File system is one of the most basic services provided by the OS • Most of the file systems allow hierarchical directory structure • Files are identified by filenames limited in length (32-256) • Although the basic services are identical in all OSs, their exact implementations make them mutually incompatible

  4. Java’s File Management • Java classFiledefines platform-independent manipulation of file system (Files & directories) by providing whether the file • exists • is read protected • is write protected • is, in fact, a directory • Instances of File class are immutable

  5. File Class • A File object can refer to either a file or directory File file1 = new File(“data.txt”); File file2 = new File(“C:\Java”); • To obtain the path to the current working directory use System.getProperty(“user.dir”); • To obtain the file or path separator use System.getProperty (“file.separator”); System.getProperty (“path.separator”); Or File.separator File.pathSeparator

  6. Useful File Methods • isFile/isDirectory • canRead/canWrite • length • Length of the file in bytes (long) or 0 if nonexistent • list • If the file object is a directory, returns a String array of all the files and directories contained in the directory; otherwise, null • mkdir • Creates a new subdirectory • delete • Deletes the directory and returns true if successful • toURL • Converts the file path to URL object

  7. Directory Listing Example import java.io.*; public class DirListing { public static void main(String[] args) { File dir = new File(System.getProperty(“user.dir”)); if (dir.isDirectory()) { System.out.println(“Directory of ” + dir); String[] listing = dir.list(); for (int i=0; i < listing.length; i++) { System.out.println(“\t” + listing[i]); } } } }

  8. Directory Listing, Result > java DirListing Direcotry of c:\Java\ DirListing.class DirListing.java Test TryCatchExample.class TryCatchExample.java XslTransformer.class XslTransformer.java

  9. Java IO package provides over 60 input/output classes (streams) Streams are ordered sequence of data that have a source (input), or a destination (output) Input/Output Streams bytes bytes OutputStream InputStream 010011001 010011001

  10. Streams • An abstraction of the continuous one-way of data • Transfers a sequence of bytes to or from • Disk files • Network connections • Memory • Threads • Another Computer • Streams are either byte-oriented or character-oriented • An IOExaception may occur during any IO operation

  11. Reading open a stream while more information read information close the stream Writing open a stream while more information write information close the stream Basic IO Algorithm

  12. The Stream Zoo Character Streams Byte Streams

  13. Character Streams • Read and write 16-bit characters • Reader and Writer are the abstract classes • Use readers and writers to read and write textual information

  14. Byte Streams • Read and write 8-bit bytes • InputStream and OutputStream are abstract super classes • Typically used to read and write binary data such as images and sounds

  15. Data Streams • Grouping of classes based on their purpose is often more convenient rather their data type, so that streams can be cross-grouped by: • Whether they read from and write to data ”sinks” or • Process the information as it is being read or written Byte Streams Character Streams Data Sink Streams Processing Streams

  16. Reader int read(); int read(char cbuf[]); int read(char cbuf[], int offset, int length) Writer int write(int c); int write(char cbuf[]); int write(char cbuf[], int offset, int length) InputStream int read(); intread(byte buffer[]); int read(byte buffer[], int offset, int length) OutputStream int write(byte b); int write(byte buffer[]); int write(byte buffer[], int offset, int length) I/O Super Classes

  17. Streams • All of the streams are automatically opened when created • Any stream can be closed explicitly by calling its close() method

  18. Using Character File Streams import java.io.*; public class Copy { public static void main(String[] args) throws IOException { File in = new File(“src.txt"); File out = new File("out.txt"); FileReader in = new FileReader(in); FileWriter out = new FileWriter(out); int c; while ((c = in.read()) != -1) { out.write(c); } in.close(); out.close(); } } FileReader in FileWriter out

  19. Using String Streams import java.io.*; class Capitalize { public static void main(String[] args) { Reader in = new StringReader (“advance programming”); Writer out = new StringWriter(10); int nextChar = 0; while ((nextChar = in.read()) != -1) { out.write(Character.toUpperCase ((char)nextChar)); } System.out.println(out.toString()); in.close(); out.close(); } } ADVANCE PRGRAMMING

  20. Buffer Streams • Buffer data while reading or writing, thereby reducing the number of accesses required on the original data source. • More efficient than similar non-buffered streams and are often used with other streams • The buffer size may be specified, or default size may be accepted BufferedReader BufferedWriter BufferedInputStream BufferedOutputStream Byte Streams Character Streams

  21. Using Buffer Streams import java.io.*; public class Copy { public static void main(String[] args) throws IOException { // opening the streams FileReader in = new FileReader (“infile.txt"); BufferedReader br = new BufferedReader(in); FileWriter out = new FileWriter ("outfile.txt"); BufferedWriter bw = new BufferedWriter(out); // processing the streams String aLine = null; while ((aLine = br.readLine()) != null) { bw.write(aLine, 0, aLine.length()); } // closing the streams in.close(); out.close(); } }

  22. Console Input • To read input from the console, a stream must be associated with the standard input, System.in import java.io.*; public class IOInput { public static void main(String[] args) { BufferedReader keyboard; String aLine; try { System.out.print(“Enter value: “); System.flush(); keyboard = new BufferedReader( new InputStreamReader(System.in)); aLine = keyboard.readLine(); } catch (IOExcerption ex) { System.out.println(“Error reading input!”); } } }

  23. Using String Streams • StringReader character stream whose source is string • StringWriter character stream that collects its output in string buffer

  24. Example: String Streams class Read { public static void main(String[] args) { Reader in = new StringReader (“abcdefghij”); System.out.println(in.read() + “ raw read, ascii value”); System.out.println((char)in.read() + “ cast read to char”); } } $ java Read 97 raw read, ascii value b cast read to char

  25. Example: Using String Streams classCapitalize { public static void main(String[] args) { Reader in = new StringReader (“advance programming”); Writer out = new StringWriter(10); int nextChar = 0; while ((nextChar = in.read()) != -1) { out.write(Character.toUpperCase ((char)nextChar)); } System.out.println(out.toString()); in.close(); out.close(); } } $ java Capitalize ADVANCE PRGRAMMING

  26. Binary File I/O • Handle byte base I/O using a DataInputStream and DataOutputStream

  27. Binary File Output File file = new File(“filename”); FileOutputStream fout = new FileOutputStream(file); OR FileOutputStream fout = new FileOutputStream(“filename”); • Methods • write(byte b) • write(byte[] buffer);

  28. Binary File Output File file = new File(“filename”); FileOutputStream fout = new FileOutputStream(file); DataOutputStream dout = new DataOutputStream(fout); OR DataOutputStream dout = new DataOutputStream( new FileOutputStream( new File(“filename”))); • Methods: writeByte(byte); writeInt(int); writeLong(long); writeDouble(double); ...

  29. Binary File Output File file = new File(“filename”); BufferedOutputStream bout = new BufferedOutputStream(file); DataOutputStream dout = new DataOutputStream(bout); • Methods: flush(); write(byte) write(byte[] buffer, int off, int len)

  30. Example: BinaryFileOutput class BinaryFileOutput { public static void main(String[] args) { int[] primes={1,2,3,5,11,13, 17,19}; DataOutputStream dout = null; try { dout = new DataOutputStream( new FileOutputStream(“primes.bin”)); for (int i=0; i < primes.length; i++) { dout.writeInt(primes[n]); } dout.close(); } catch (IOException ex) { ex.printStackTrace(); } } }

  31. Binary File Input File file = new File(“filename”); FileInputStream fin = new FileInputStream(file); Or FileInputStream fin = new FileInputStream(“filename”); • Methods • read() • read(byte[] buffer);

  32. Binary File Input File file = new File(“filename”); BufferedInputStream bin = new BufferedInputStream(file); DataInputStream din = new DataInputStream(bin); • Methods: read(); write(byte[] buffer, int off, int len) skip(long)

  33. Filter Streams • Abstract classes define the interface for filter streams, which filter data as it's being read or written • Attach a filter stream to another stream to filter data • java.io package contains the following filtered streams which are subclasses of either FilterInputStream or FilterOutputStream: • DataInputStream and DataOutputStrem • BufferedInputStream and BufferedOutputStream • LineNumberInputStream • PrintStream (output stream)

  34. PrintWriter and PrintStream • Easiest streams containing high level printing methods (print, println) to write • Can be created so as to flush automatically • PrintStream • Adds functionality to another output stream, namely the ability to print representations of various data values conveniently • Never throws an IOException • Flush automatically • All characters printed by a PrintStream are converted into bytes using the platform's default character encoding

  35. PrintWriter and PrintStream • PrintWriter • prints formatted representations of objects to text-output stream • Implements all of the print methods found in PrintStream • PrintWriter(Writer) creates a new PrintWriter • PrintWriter(Writer, boolean) creates a new PrintWriter with auto flushing

  36. Example Writer out = new FileWriter (“out.txt”); FileWriter (out)

  37. Example Writer out = new FileWriter (“out.txt”); PrintWriter easyOut = new PrintWriter(out); easyOut.println(“Hi Mom”); easyOut.println(5); easyOut.println(true); easyOut.close(); FileWriter (out) PrintWriter (easyOut)

  38. Conversion Streams • InputStreamReader • Reads bytes and translate them into character streams using the specified char set • Can be wrapped within a BufferedReader for efficiency BufferedReader in = new BufferedReader( new InputStreamReader(System.in)); System.in BufferedReader (in) InputStreamReader

  39. Conversion Streams • OutputStreamWriter • Writes character to an output stream translating into bytes • Can be wrapped within a BufferedWriter for efficiency OutputStreamWriter outWriter = new OutputStreamWriter(System.out); Bufferedwriter out = new Bufferedwriter(outWriter); BufferedWriter (out) System.out OutputStreamWriter

  40. Custom Filtered Streams • Steps writing your own filtered I/O streams: • Create a subclass of FilterInputStream and FilterOutputStream • Override the read and write methods, if needed • Provide any new methods • Make sure that the input and output streams work together

  41. Example import java.io.*; public class WhiteSpaceStripInputStream extendsFilterInpuStream { public WhiteSpaceStripInputStream(InputStream in) { super(in); } public int read() throws IOException { int c; do { c = in.read(); } while ((c ==‘ ‘ || c ==‘\t’|| c==‘\r’ || c ==‘\n’|| c ==‘\f’)&& c != -1 ); return c; }

  42. public int read(byte[] b) throws IOException { int c = 0, i = 0; for (i=0; i < b.length && (c=read())!= -1; i++){ b[i] = (byte) c; } } public int read(byte[] b, int offset, int len) throws IOException { int c = 0, i = 0; for (i=0; i < len && (c =read()) != -1; i++) { b[offset + i] = (byte) c; } return i; }

  43. public long skip(long n) throws IOException { int c = 0; for (int i = 0; i<n && (c=read()) != -1; i++) ; return i; } public int available() throws IOException { return 0; } }

  44. Random Access File • Permit nonsequential, or random, access to a file's contents • RandomAccessFile is used for both reading and writing files new RandomAccessFile ("farrago.txt", "r"); new RandomAccessFile("farrago.txt", "rw"); • It contains readXXX and writeXXX methods to perform I/O operations on the file

  45. Random Access File • Supports the notion of a file pointer which indicates the current location of in the file • Contains methods for explicitly manipulating the file pointer: • skipBytes(int): moves the file pointer forward • seek(long): position the file pointer • long getFilePointer(): returns the current byte location of the file pointer

  46. Question & Answer ?

More Related