380 likes | 419 Views
Java IO Packages Prepared by Mrs.S.Amudha AP/SWE. Introduction. The Java Input/Output (I/O) is a part of java.io package. The java.io package contains a relatively large number of classes The classes in the package are primarily abstract classes and stream-oriented
E N D
Introduction • The Java Input/Output (I/O) is a part of java.io package. • The java.io package contains a relatively large number of classes • The classes in the package are primarily abstract classes and stream-oriented • Define methods and subclasses for allowing bytes to be read from and written to files or other input and output sources
File • A File object is used to obtain or manipulate the information associated with a disk file • Such as the permissions, time, date, and directory path • Files are a primary source and destination for data within many programs • Constructors • File(String directoryPath) • File(String directoryPath, String filename) • File(File dirObj, String filename)
What Are Streams? • Is a path of communication between the source of some information and its destination • Producers and consumers of bytes • Example • Input stream - allows you to read data from a source • Output stream - allows you to write data to a destination.
InputStream • Is used for reading the data such as a byte and array of bytes from an input source • An input source can be a file, a string, or memory that may contain the data • It is an abstract class that defines the programming interface for all input streams that are inherited from it • An input stream is automatically opened when you create it.
Abstract Class InputStream • Is an abstract class that defines the fundamental ways in which a destination (consumer) reads a stream of bytes from some source. • The identity of the source, and the manner of the creation and transport of the bytes, is irrelevant.
ByteArray I/p Stream Example // Demonstrate ByteArrayInputStream. import java.io.*; class ByteArrayInputStreamDemo { public static void main(String args[]) throws IOException { String tmp = "abcdefghijklmnopqrstuvwxyz"; byte b[] = tmp.getBytes(); ByteArrayInputStream input1 = new ByteArrayInputStream(b); ByteArrayInputStream input2 = new ByteArrayInputStream(b, 0,3); } }
FileReader • The FileReader class creates a Reader that you can use to read the contents of a file • Constructor • FileReader(String filePath) • FileReader(File fileObj)
Example // Demonstrate FileReader. import java.io.*; class FileReaderDemo { public static void main(String args[]) throws Exception { FileReader fr = new FileReader("FileReaderDemo.java"); BufferedReader br = new BufferedReader(fr); String s; while((s = br.readLine()) != null) { System.out.println(s); } fr.close(); } }
CharArrayReader • CharArrayReader is an implementation of an input stream that uses a character array as the source. • This class has two constructors • CharArrayReader(char array[ ]) • CharArrayReader(char array[ ], int start, int numChars)
Example import java.io.*; public class CharArrayReaderDemo { public static void main(String args[]) throws IOException { String tmp = "abcdefghijklmnopqrstuvwxyz"; int length = tmp.length(); char c[] = new char[length]; tmp.getChars(0, length, c, 0); CharArrayReader input1 = new CharArrayReader(c); CharArrayReader input2 = new CharArrayReader(c, 0, 5); int i; System.out.println("input1 is:"); while((i = input1.read()) != -1) { System.out.print((char)i); } System.out.println(); System.out.println("input2 is:"); while((i = input2.read()) != -1) { System.out.print((char)i) ; } System.out.println(); } }
OutputStream • Is a sibling to InputStream that is used for writing byte and array of bytes to an output source • An output source can be anything such as a file, a string, or memory containing the data • An output stream is automatically opened when you create it • You can explicitly close an output stream with the close( ) method, or let it be closed implicitly when the object is garbage collected
Reading Text from the Standard Input * Standard Input: Accessed through System.in which is used to read input from the keyboard. * Standard Output: Accessed through System.out which is used to write output to be display. * Standard Error: Accessed through System.err which is used to write error output to be display. • Syntax: InputStreamReader inp = new InputStreamReader(system.in);
BufferedReader • The BufferedReader class is the subclass of the Reader class. • It reads character-input stream data from a memory area known as a buffer maintains state. • The buffer size may be specified, or the default size may be used Constructor • BufferedReader(Reader in):Creates a buffering character-input stream that uses a default-sized input buffer • BufferedReader(Reader in, int sz): Creates a buffering character-input stream that uses an input buffer of the specified size.
Example import java.io.*; public class ReadStandardIO{ public static void main(String[] args) throws IOException{ InputStreamReader inp = new InputStreamReader(System.in) BufferedReader br = new BufferedReader(inp); System.out.println("Enter text : "); String str = br.readLine(); System.out.println("You entered String : "); System.out.println(str); } } Output: C:\java>javacReadStandardIO.java C:\java>java ReadStandardIO Enter text : this is an Input Stream You entered String : this is an Input Stream C:\java>
Working With File The constructors of the File class are shown in the table: Constructor - Description • File(path) - Create File object for default directory (usually where program is located). • File(dirpath,fname) - Create File object for directory path given as string. • File(dir, fname) - Create File object for directory. Thus the statement can be written as: File f = new File("<filename>");
Create a File • For creating a new file File.createNewFile( ) method is used. • This method returns a boolean value true if the file is created otherwise return false. • If the mentioned file for the specified directory is already exist then the createNewFile() method returns the false otherwise the method creates the mentioned file and return true.
Example import java.io.*; public class CreateFile1{ public static void main(String[] args) throws IOException{ File f; f=new File("myfile.txt"); if(!f.exists()){ f.createNewFile(); System.out.println("New file \"myfile.txt\" has been created to the current directory"); } } }
Read file line by line • Java supports the following I/O file streams. * FileInputstream * FileOutputStream FileInputstream: This class is a subclass of Inputstream class that reads bytes from a specified file name . The read() method of this class reads a byte or array of bytes from the file. It returns -1 when the end-of-file has been reached.
Read file line by line FileOutputStream: This class is a subclass of OutputStream that writes data to a specified file name. • The write() method of this class writes a byte or array of bytes to the file. DataInputStream: • This class is a type of FilterInputStream that allows you to read binary data of Java primitive data types in a portable way.
Example import java.io.*; public class ReadFile{ public static void main(String[] args) throws IOException{ File f; f=new File("myfile.txt"); if(!f.exists()&& f.length()<0) System.out.println("The specified file is not exist"); else{ FileInputStream finp=new FileInputStream(f); byte b; do{ b=(byte)finp.read(); System.out.print((char)b); } while(b!=-1); finp.close(); } } }
Write To File FileOutputStream class is used to write data to a file. • FileWriter is a subclass of OutputStreamWriter class that is used to write text (as opposed to binary data) to a file • The BufferedWriter class is used to write text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays and strings.
Example import java.io.*; public class FileWriter{ public static void main(String[] args) throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Please enter the file name to create : "); String file_name = in.readLine(); File file = new File(file_name); boolean exist = file.createNewFile(); if (!exist) { System.out.println("File already exists."); System.exit(0); } else { FileWriter fstream = new FileWriter(file_name); BufferedWriter out = new BufferedWriter(fstream); out.write(in.readLine()); out.close(); System.out.println("File created successfully."); } } }
Append To File import java.io.*; class FileWrite { public static void main(String args[]) { try{ // Create file FileWriter fstream = new FileWriter("out.txt",true); BufferedWriter out = new BufferedWriter(fstream); out.write("Hello Java"); //Close the output stream out.close(); }catch (Exception e){//Catch exception if any System.err.println("Error: " + e.getMessage()); } } }
Getting the Size of a File import java.io.*; public class FileSize{ public static void main(String[] args) throws IOException{ System.out.print("Enter file name : "); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); File f = new File(in.readLine()); if(f.exists()){ long file_size = f.length(); System.out.println("Size of the file : " + file_size); } else{ System.out.println("File does not exists."); System.exit(0); } } }
Create Temp File import java.io.File; import java.io.FileWriter; mport java.io.BufferedWriter; import java.io.IOException; public class CTFile { public static void main(String[] args){ File tempFile = null; try { tempFile = File.createTempFile("MyFile.txt", ".tmp" ); System.out.print("Created temporary file with name "); System.out.println(tempFile.getAbsolutePath()); } catch (IOException ex) { System.err.println("Cannot create temp file: " + ex.getMessage()); } finally { if (tempFile != null) { } } } }
Example import java.io.*; public class SquareNum { public double square(double num) { return num * num; } public double getNumber() throws IOException { // create a BufferedReader using System.in InputStreamReader isr = new InputStreamReader(System.in); BufferedReader inData = new BufferedReader(isr); String str; str = inData.readLine(); return (new Double(str)).doubleValue(); } public static void main(String args[]) throws IOException { SquareNum ob = new SquareNum(); double val; System.out.println("Enter value to be squared: "); val = ob.getNumber(); val = ob.square(val); System.out.println("Squared value is " + val); } }
Serialization • Serialization is the process of writing the state of an object to a byte stream • Serialization is also needed to implement Remote Method Invocation (RMI) • An object that implements the Serializable interface can be saved and restored by the serialization facilitie
Stream Benefits • Streaming interface to I/O in Java provides a clean abstraction for a complex task • Filtered stream classes allows you to dynamically build the custom streaming interface to suit your data transfer requirements. • InputStream, OutputStream, Reader, and Writer classes will function properly