0% found this document useful (0 votes)
20 views

Java I/O: Jussi Pohjolainen Tampere University of Applied Sciences

The document provides an overview of Java I/O and input/output streams. It discusses reading and writing to the console and files using streams like System.in, System.out, FileReader, FileWriter, and buffered versions. It also covers reading and writing bytes, objects, and the Java NIO framework which provides higher performance I/O compared to standard Java I/O streams.

Uploaded by

ShanavasAbdu
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Java I/O: Jussi Pohjolainen Tampere University of Applied Sciences

The document provides an overview of Java I/O and input/output streams. It discusses reading and writing to the console and files using streams like System.in, System.out, FileReader, FileWriter, and buffered versions. It also covers reading and writing bytes, objects, and the Java NIO framework which provides higher performance I/O compared to standard Java I/O streams.

Uploaded by

ShanavasAbdu
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

Java

I/O
Jussi Pohjolainen Tampere University of Applied Sciences

Intro
Input / Output
Input from le or keyboard Output to screen or a le

To deliver data, stream is used

READ AND WRITE CONSOLE

Read and Write to Console


Output stream:
System.out

Input Stream:
System.in

PrintStream (System.out)

InputStream (System.in)

Read a byte from user input?

Using InputStreamReader
To use InputStreamReader
InputStreamReader a = new InputStreamReader(System.in);

An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specied charset InputStreamReader has methods for reading one char at a Kme We dont want to read one char at a .me from user!

Using BueredReader
To use InputStreamReader
BufferedReader a = new BufferedReader(new InputStreamReader(System.in)); String mj = a.readLine();

Read text from a character-input stream, buering characters so as to provide for the ecient reading of characters, arrays, and lines. Done!

Scanner
Or just use Scanner from Java 1.5!
Scanner s = new Scanner(System.in); String mj = s.nextLine();

READ AND WRITE FILES

Binary vs text
All data are in the end binary:
01010101001011100110

Binary les: bits represent encoded informaKons, executable instrucKons or numeric data. Text les: the binarys represent characters.

Text les
In text les bits represent printable characters In ASCII encoding, one byte represents one character Encoding is a rule where you map chars to integers. a => 97 => 1100001

Example Encoding: ASCII

TesKng in Java
class CharTest { public static void main(String [] args) { char myChar1 = 'a'; int myChar2 = 97; System.out.println(myChar1); // 'a' System.out.println(myChar2); // 97 System.out.println( (int) myChar1); // 97 System.out.println((char) myChar2); // 'a' } }

Character Streams
Java uses UTF-8 internally To read characters
FileReader

To write characters
FileWriter

FileReader
import java.io.FileReader; import java.io.IOException; public class CharTest { public static void main(String[] args) throws IOException { FileReader inputStream = new FileReader("CharTest.java"); char oneChar = (char) inputStream.read(); System.out.println(oneChar); inputStream.close(); } }

FileReader: Reading MulKple Chars


import java.io.FileReader; import java.io.IOException; public class CharTest { public static void main(String[] args) throws IOException { FileReader inputStream = new FileReader("CharTest.java"); int oneChar; while ((oneChar = inputStream.read()) != -1) { System.out.print((char) oneChar); } inputStream.close(); } }

FileWriter
import java.io.FileWriter; import java.io.IOException; public class CharTest { public static void main(String[] args) throws IOException { FileWriter outputStream = new FileWriter("output.txt"); outputStream.write("hello!"); outputStream.close(); } }

Buering
Using unbuered IO is less ecient than using buered IO. Read stu to buer in memory and when buer is full, write it. Less disk access or network acKvity

BueredReader
import java.io.FileReader; import java.io.BufferedReader; import java.io.IOException; public class CharTest { public static void main(String[] args) throws IOException { BufferedReader inputStream = new BufferedReader(new FileReader("output.txt")); System.out.println( inputStream.readLine() ); inputStream.close(); } }

PrintWriter, BueredWriter
Convenient way of wriKng les using PrintWriter:
PrintWriter pw = new PrintWriter( new BufferedWriter( new FileWriter("output.txt"))); pw.println("hello!"); pw.close();

READING AND WRITING BYTES

Read and Write


To Read
FileInputStream

To Write
FileOutputStream

Read and Write


FileInputStream in = new FileInputStream("output.txt"); FileOutputStream out = new FileOutputStream("outagain.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } in.close(); out.close();

CLOSING STREAMS

import java.io.*; public class CharTest { public static void main(String[] args) { BufferedReader inputStream = null; try { inputStream = new BufferedReader(new FileReader("output.txt")); System.out.println( inputStream.readLine() ); } catch(IOException e) { e.printStackTrace(); } finally { try { if(inputStream != null) { inputStream.close(); } } catch(IOException e) { e.printStackTrace(); } } } }

Java 7: AutomaKc Closing!


try (InputStream is = new FileInputStream(myfile.txt)) { // do something with this input stream // ... } catch (Exception ex) { ex.printStackTrace(); }

HELPER CLASS: FILE

File
File class has very useful methods:
exists canRead canWrite Length getPath

Example
File f = new File(file.txt); If(f.exists()) { .. }

SERIALIZATION

Object Streams
To read and write objects! How?
Object class must implement serializable marker interface Read and write using ObjectInputStream and ObjectOutputStream

SerializaKon is used in Java RMI

Example: Car
class Car implements Serializable { private String brand; public Car(String brand) { setBrand(brand); } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } }

Example: Saving and Reading


// Save the object fos = new FileOutputStream("car.dat"); oos = new ObjectOutputStream(fos); oos.writeObject(datsun); // Read the object fis = new FileInputStream("car.dat"); ois = new ObjectInputStream(fis); Car datsun2 = (Car) ois.readObject();

Transient
Every a^ribute of the object is saved into disk.. except a^ribute is marked with transient keyword Mark a^ributes to transient when the informaKon is secret or uneccessary. When object is deserializaled, transient a^ributes values are null

JAVA NIO

NIO: High performance IO


java.io is suitable for basic needs. When there is a need for higher performance, use Java NIO (New I/O) (java.nio) Less GC, less threads, more ecient use of operaKng system Provides scalable I/O operaKons on both binary and character les. Also a simple parsing facility based on regular expressions A li^le bit harder to use than java.io

Streams vs Blocks
java.io Stream: movement of single bytes one at a Kme. java.nio Block: movement of many bytes (blocks) at a Kme Processing data by block can be much faster than one byte at a Kme

Channels and Buers


Channels are what streams were in java.io All data transferred in java.nio must go through a Channel Buer is a container object, before sending data into a channel, the data must be wrapped inside a Buer Buer is an object, which holds an array of bytes

Buer Types
There are many classes for buers. These classes inherit java.nio.Buer: ByteBuer - byte array CharBuer ShortBuer IntBuer LongBuer FloatBuer DoubleBuer

About Channels
You never write a byte directly into a channel. Bytes must be wrapped inside a buer Channels are bi-direcTonal Channels can be opened for reading, wriKng, or both

Example: Reading
FileInputStream n = new FileInputStream( "data.txt" ); // Get a channel via the FileInputStream FileChannel fc = n.getChannel(); // Create a buer ByteBuer buer = ByteBuer.allocate( 1024 ); // Read from channel into a buer fc.read( buer );

Example: WriKng
FileOutputStream fout = new FileOutputStream( "data.txt" ); // Get a channel via the FileOutputStream FileChannel fc = fout.getChannel(); // Create a buffer ByteBuffer buffer = ByteBuffer.allocate( 1024 ); // Data to be saved byte [] message = "this will be saved".toByteArray(); // Write into buffer for ( int i=0; i<message.length; i++ ) { buffer.put( message[i] ); } // Flip the buffer, this will be explained later buffer.flip(); // Writes SOME bytes from the buffer! fc.write( buffer );

Buer Internals
Every buer has posiKon, limit and capacity These three variables track the state of the buer posiTon: is the index of the next element to be read or wri^en. A buer's posiKon is never negaKve and is never greater than its limit. limit: is the index of the rst element that should not be read or wri^en. A buer's limit is never negaKve and is never greater than its capacity capacity: is the number of elements buer contains. The capacity of a buer is never negaKve and never changes.

Buer Example 1

Buer Example 2

Buer Example 3

Buer Example 4

Buer Example 5

Buer Example 6

Buer Example 7

FileInputStream fin = new FileInputStream( infile.exe ); FileOutputStream fout = new FileOutputStream( outfile.exe ); FileChannel fcin = fin.getChannel(); FileChannel fcout = fout.getChannel();

ByteBuffer buffer = ByteBuffer.allocate( 1024 ); while (true) { // Reset the buffer buffer.clear(); int numberOfReadBytes = fcin.read( buffer ); if ( numberOfReadBytes == -1 ) { break; } // prepare the buffer to be written to a buffer buffer.flip(); int numberOfWrittenBytes = 0; do { numberOfWrittenBytes += fcout.write( buffer ); } while(numberOfWrittenBytes < numberOfReadBytes); }

You might also like