java input/output. java input/output input is any information that is needed by your program to...

19
Java Input/Output

Upload: benjamin-strickland

Post on 19-Jan-2018

243 views

Category:

Documents


1 download

DESCRIPTION

Stream A stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination. Java provides strong but flexible support for I/O related to Files and networks Streams support many different kinds of data, including simple bytes, primitive data types, localized characters, and objects. Some streams simply pass on data; others manipulate and transform the data in useful ways. Types of Streams Byte Streams: Byte streams perform input and output of 8-bit bytes. They read and write data one byte at a time. Using byte streams is the lowest level of I/0, so if you are reading or writing character data the best approach is to use character streams. Other stream types are built on top of byte streams. Byte streams are defined by using two class hierarchies. At the top are two abstract classes: InputStream and OutputStream. The abstract classes InputStream and OutputStream define several key methods that the other stream classes implement. Two of the most important are read( ) and write( ), which, respectively, read and write bytes of data. Both methods are declared as abstract inside InputStream and OutputStream.

TRANSCRIPT

Page 1: Java Input/Output. Java Input/output Input is any information that is needed by your program to complete its execution. Output is any information that

Java Input/Output

Page 2: Java Input/Output. Java Input/output Input is any information that is needed by your program to complete its execution. Output is any information that

Java Input/output Input is any information that is needed by your program to complete its execution.

Output is any information that the program must convey to use the user.

The information we see on our computer screen is being output by one or more programs that are currently running on our computer

Java I/O (Input and Output) is used to process the input and produce the output based on the input.

The java.io package contains nearly every class you might ever need to perform input and output (I/O) in Java. All these streams represent an input source and an output destination. The stream in the java.io package supports many data such as primitives, Object, localized characters, etc.

Page 3: Java Input/Output. Java Input/output Input is any information that is needed by your program to complete its execution. Output is any information that

Stream A stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination.

Java provides strong but flexible support for I/O related to Files and networks

Streams support many different kinds of data, including simple bytes, primitive data types, localized characters, and objects. Some streams simply pass on data; others manipulate and transform the data in useful ways.

Types of Streams Byte Streams: Byte streams perform input and output of 8-bit bytes. They read and write data one byte at a time. Using byte streams is the lowest level of I/0, so if you are reading or writing character data the best approach is to use character streams. Other stream types are built on top of byte streams.

Byte streams are defined by using two class hierarchies. At the top are two abstract classes: InputStream and OutputStream. The abstract classes InputStream and OutputStream define several key methods that the other stream classes implement. Two of the most important are read( ) and write( ), which, respectively, read and write bytes of data. Both methods are declared as abstract inside InputStream and OutputStream.

Page 4: Java Input/Output. Java Input/output Input is any information that is needed by your program to complete its execution. Output is any information that

Stream Contd.. Character Streams: Java Byte streams are used to perform input and output of 8-bit bytes, where as Java Character streams are used to perform input and output for 16-bit unicode.

Character streams are defined by using two class hierarchies. At the top are two abstract classes, Reader and Writer

The abstract classes Reader and Writer define several key methods that the other

stream classes implement. Two of the most important methods are read( ) and write( ),

which read and write characters of data, respectively.

Page 5: Java Input/Output. Java Input/output Input is any information that is needed by your program to complete its execution. Output is any information that

BufferedReader/Writer The BufferedReader class provides buffering to your Reader's. Buffering can speed up IO quite a bit. Rather than read one character at a time from the network or disk, you read a larger block at a time. This is typically much faster, especially for disk access and larger data amounts.

The main difference between BufferedReader and BufferedInputStream is that Reader's work on characters (text), where as InputStream's works on raw bytes.

The BufferedWriter class provides buffering to your Writer's. Buffering can speed up IO quite a bit. Rather than write one character at a time to the network or disk, you write a larger block at a time. This is typically much faster, especially for disk access and larger data amounts.

To add buffering to your Writer's simply wrap them in a BufferedWriter

Page 6: Java Input/Output. Java Input/output Input is any information that is needed by your program to complete its execution. Output is any information that

//Example Console Inputimport java.io.*;class ColsoleInputEx {public static void main(String args[])throws IOException{// create a BufferedReader using System.in

InputStreamReader In=new InputStreamReader(System.in);BufferedReader br = new BufferedReader(In);String str[] = new String[100];System.out.println("Enter lines of text.");System.out.println("Enter 'stop' to quit.");for(int i=0; i<100; i++) {

str[i] = br.readLine(); //Reading Line of Textif(str[i].equals("stop")) break;

}System.out.println("\nHere is your file:");

for(int i=0; i<100; i++) {if(str[i].equals("stop"))

break;System.out.println(str[i]);

}}}

Page 7: Java Input/Output. Java Input/output Input is any information that is needed by your program to complete its execution. Output is any information that

FileReader /FileWriter Java FileWriter and FileReader classes are used to write and read data from text files. These are character-oriented classes, used for file handling in java.

Java FileWriter class is used to write character-oriented data to the file.Constructor Description

FileWriter(String file) creates a new file. It gets file name in string.

FileWriter(File file) creates a new file. It gets file name in File object.

Method Description

1) public void write(String text) writes the string into FileWriter.2) public void write(char c) writes the char into FileWriter.3) public void write(char[] c) writes char array into FileWriter.4) public void flush() flushes the data of FileWriter.5) public void close() closes FileWriter.

Page 8: Java Input/Output. Java Input/output Input is any information that is needed by your program to complete its execution. Output is any information that

Java FileReader class is used to read data from the file. It returns data in byte format like FileInputStream class.

FileReader /FileWriter Contd…Constructor Description

FileReader(String file) It gets filename in string. It opens the given file in read mode. If file doesn't exist, it throws FileNotFoundException.

FileReader(File file) It gets filename in file instance. It opens the given file in read mode. If file doesn't exist, it throws FileNotFoundException.

Method Description

1) public int read() returns a character in ASCII form. It returns -1 at the end of file.2) public void close() closes FileReader.

Page 9: Java Input/Output. Java Input/output Input is any information that is needed by your program to complete its execution. Output is any information that

FileReader /FileWriter Example//File Outputimport java.io.*;class FileOutputEx {public static void main(String args[]) throws IOException{

InputStreamReader In=new InputStreamReader(System.in);BufferedReader br = new BufferedReader(In);

FileWriter fw=new FileWriter(“xyz.txt”);BufferedWriter bw=new BufferedWriter(fw);

String str;System.out.println("Enter lines of text.");System.out.println("Enter 'stop' to quit.");for(int i=0; i<100; i++) {

str= br.readLine(); //Reading Line of Textif(str.equals("stop")) break;bw.write(str); //Write data automatically to File xyz.txtbw.newLine();

}pw.close();fw.close();}

}

Page 10: Java Input/Output. Java Input/output Input is any information that is needed by your program to complete its execution. Output is any information that

FileReader /FileWriter Example//File Inputimport java.io.*;class FileInputEx {public static void main(String args[]) throws IOException{

FileReader fr=new FileReader(“xyz.txt”);BufferedReader br = new BufferedReader(fr);

String str;str=br.readLine();while(str!=null) {

System.out.println(str);str=br.readLine();

}br.close();}

}

Page 11: Java Input/Output. Java Input/output Input is any information that is needed by your program to complete its execution. Output is any information that

PrintWriter Although using System.out to write to the console is still permissible under Java, its use is recommended mostly for debugging purposes . For real-world programs, the recommended method of writing to the console when using Java is through a PrintWriter stream. PrintWriter is one of the character-based classes. Using a character-based class for console output makes it easier to internationalize your program.

Syntax

PrintWriter(OutputStream outputStream, boolean flushOnNewline)

Here, outputStream is an object of type OutputStream, and flushOnNewline controls whether Java flushes the output stream every time a println( ) method is called. If flushOnNewline is true, flushing automatically takes place. If false, flushing is not automatic.

Page 12: Java Input/Output. Java Input/output Input is any information that is needed by your program to complete its execution. Output is any information that

PrintWriter Example // Demonstrate PrintWriter

import java.io.*;

public class PrintWriterDemo {public static void main(String args[]) {PrintWriter pw = new PrintWriter(System.out, true);pw.println("This is a string");int i = -7;pw.println(i);double d = 4.5e-7;pw.println(d);}

}

Page 13: Java Input/Output. Java Input/output Input is any information that is needed by your program to complete its execution. Output is any information that

// Demonstrate PrintWriter in Saving File

import java.io.*;

public class PrintWriterFile {public static void main(String args[]) throws IOException {FileWriter file1=new FileWriter(“PrintWriter.txt”);PrintWriter pw = new PrintWriter(file1,true);pw.print(“Some Test Data that will be written when flush is called.”);pw.flush();//Flush all buffered data to the file

pw.println(“This is automatically flush it to the file”);pw.close();file1.close();}

}

Page 14: Java Input/Output. Java Input/output Input is any information that is needed by your program to complete its execution. Output is any information that

Random Access Files The term random access means that data can be read from or written to random locations within a file. In all the above mentioned streams, data is read and written as a continuous stream of information. Java provides the RandomAccessFile class to perform I/O operation at specified location within a file.

Creating a Random Access File there are two constructors

RandomAccessFile(String pathname, String mode);

RandomAccessFile(File name, String mode);

Examples

RandomAccessFile randomFile=new RandomAccessFile(“iotest.txt”,”rw”);

Methods:getFilePointer() to get the current position of the pointer

read(byte[] b) to reads up to b.length bytes of data from the file into an array of bytes

write(byte[] b) to write b.length bytes from the specified byte array to the file, starting at the current file pointer

Page 15: Java Input/Output. Java Input/output Input is any information that is needed by your program to complete its execution. Output is any information that

import java.io.IOException;import java.io.RandomAccessFile;

public class RandomAccessFileExample {

public static void main(String[] args) { try { String filePath = "/Users/admin/source.txt"; System.out.println(new String(readCharsFromFile(filePath, 1, 5))); writeData(filePath, "Data", 5); } catch (IOException e) { e.printStackTrace(); } }

private static void writeData(String filePath, String data, int seek) throws IOException { RandomAccessFile file = new RandomAccessFile(filePath, "rw"); file.seek(seek); file.write(data.getBytes()); file.close(); }

Page 16: Java Input/Output. Java Input/output Input is any information that is needed by your program to complete its execution. Output is any information that

private static byte[] readCharsFromFile(String filePath, int seek, int chars) throws IOException { RandomAccessFile file = new RandomAccessFile(filePath, "r"); file.seek(seek); byte[] bytes = new byte[chars]; file.read(bytes); file.close(); return bytes; }

}

Page 17: Java Input/Output. Java Input/output Input is any information that is needed by your program to complete its execution. Output is any information that

String Tokenizer• The process of splitting a line of text into different parts is known as tokenizing, and each

piece is a token.• The standard Java library includes a class called, StringTokenizer that makes this process

much more convenient for the Java programmers• A StringTokenizer object is created from a String Object. Use hasMoreTokens method to

determine if there are any remaining tokens to process. Use nextToken method to return the next token as a String object.

Example:Crate a file called Student.txt that contains data for three students and three exam

scores for each studentShrestha, Jasmin: 87: 82: 95Sharma, Ravi: 85: 89: 92Tiwari, Rajan: 94: 12:35

Page 18: Java Input/Output. Java Input/output Input is any information that is needed by your program to complete its execution. Output is any information that

//StringTokenizer and File input Exampleimport java.io.*;import java.util.*;public Class StringTokenizerEx{

File gradeFile=new File(“Student.txt”);if(gradeFile.exists()){

BufferedReader inFile=new BufferedReader(new FileReader(gradeFile));String line=inFile.readLine();

while(line!=null){

StringTokenizer st=new StringTokenizer(line,”:”);System.out.print(“Name: ” + st.nextToken());int numScore = st.CountTokens();

int sum=0;for(int i=1; i<=numScore; i++){

int score=Integer.parseInt(st.nextToken());

Page 19: Java Input/Output. Java Input/output Input is any information that is needed by your program to complete its execution. Output is any information that

//StringTokenizer and File input Example Contd….

sum+=score;}System.out.println(“ Total Score: “ + sum);line=inFile.readLine();

}inFile.close();}

}