Beruflich Dokumente
Kultur Dokumente
CT038-3-2 OODJ
Learning outcomes
At the end of this lecture you should be able to: read and write text files become familiar with the concepts of text and binary formats
CT038-3-2 OODJ
CT038-3-2 OODJ
Concept of Streams
Java uses the concept of streams to represent the ordered sequence of data. A stream is a path along which data flows. It has the source and a destination. Streams are classified as input stream and output stream
CT038-3-2 OODJ
Input stream extracts data from the source file. Output stream takes data from the program and sends it to the destination file.
CT038-3-2 OODJ
Stream Classes
The java.io package contains a large number of stream classes. These classes are categorized into: 1. Byte stream provide support for handling I/O operations on bytes 2. Character stream provide support for managing I/O operations on characters
CT038-3-2 OODJ
CT038-3-2 OODJ
CT038-3-2 OODJ
Creation of files
Suitable name for the file Data type to be stored Purpose ( reading or writing) Method of creating the file
CT038-3-2 OODJ
For using a file , it must be opened first. This is done by creating a file stream and then linking it to the filename. Use Reader/InputStream or Writer/OutputStream
CT038-3-2 OODJ
Example:
FileInputStream fis; // Declare a file stream object try { // Assign the filename to the file stream object fis = new FileInputStream(test.data) . } catch (IOException e)
CT038-3-2 OODJ
CT038-3-2 OODJ
try { ins = new FileReader(inFile); outs = new FileReader(outFile); int ch; while ((ch=ins.read()) !=-1) { outs.write(ch); } } catch(IOException e) { System.out.println(e); System.exit(-1); } finally { try { ins.close(); outs.close(); } catch(IOException e){} } } }
CT038-3-2 OODJ Managing Input Output Files
}
catch (IOException ioe){} } }
CT038-3-2 OODJ
CT038-3-2 OODJ
Example:
import java.io.*; class SequenceBuffer { public static void main (String args[]) throws IOException { FileInputStream file1 = null; FileInputStream file2 = null; SequenceInputStream file3 = null; file1 = new FileInputStream(text1.dat); file2 = new FileInputStream(text2.dat); file3 = new SequenceInputStream(file1,file2); BufferedInputStream inBuffer = new BufferedInputStream(file3); BufferedOutputStream outBuffer = new BufferedOutputStream(System.out); int ch; while ((ch = inBuffer.read()) !=-1) { outBuffer.write((char)ch); } inBuffer.close(); outBuffer.close(); file1.close(); file2.close(); } }
CT038-3-2 OODJ Managing Input Output Files