READING DATA FROM KEYBOARD USING DATAINPUTSTREAM, BUFFEREDREADER AND SCANNER



Similar documents
INPUT AND OUTPUT STREAMS

Input / Output Framework java.io Framework

Files and input/output streams

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

The Java I/O System. Binary I/O streams (ascii, 8 bits) The decorator design pattern Character I/O streams (Unicode, 16 bits)

Programming in Java

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

Stream Classes and File I/O

Chapter 10. A stream is an object that enables the flow of data between a program and some I/O device or file. File I/O

Readings and References. Topic #10: Java Input / Output. "Streams" are the basic I/O objects. Input & Output. Streams. The stream model A-1.

What is an I/O Stream?

CS 1302 Ch 19, Binary I/O

Simple Java I/O. Streams

JAVA.UTIL.SCANNER CLASS

Building a Multi-Threaded Web Server

Amazon EC2 KAIST Haejoon LEE

Today s Outline. Computer Communications. Java Communications uses Streams. Wrapping Streams. Stream Conventions 2/13/2016 CSE 132

Some Scanner Class Methods

JAVA - FILES AND I/O

Reading Input From A File

Course Intro Instructor Intro Java Intro, Continued

Creating a Simple, Multithreaded Chat System with Java

Event-Driven Programming

File I/O - Chapter 10. Many Stream Classes. Text Files vs Binary Files

D06 PROGRAMMING with JAVA

Programming Languages CIS 443

Java Network Programming. The java.net package contains the Socket class. This class speaks TCP (connection-oriented protocol).

Quick Introduction to Java

Object-Oriented Programming in Java

Visit us at

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Chapter 2: Elements of Java

Introduction to Java

6.1. Example: A Tip Calculator 6-1

Chapter 20 Streams and Binary Input/Output. Big Java Early Objects by Cay Horstmann Copyright 2014 by John Wiley & Sons. All rights reserved.

public static void main(string[] args) { System.out.println("hello, world"); } }

Learning Outcomes. Networking. Sockets. TCP/IP Networks. Hostnames and DNS TCP/IP

Introduction to Java I/O

1 of 1 24/05/ :23 AM

Lesson: All About Sockets

Lecture 5: Java Fundamentals III

Principles of Software Construction: Objects, Design, and Concurrency. Design Case Study: Stream I/O Some answers. Charlie Garrod Jonathan Aldrich

Chapter 3. Input and output. 3.1 The System class

Member Functions of the istream Class

B.Sc (Honours) - Software Development

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

Comp 248 Introduction to Programming

Basics of I/O Streams and File I/O

AVRO - SERIALIZATION

AP Computer Science Java Subset

CS 106 Introduction to Computer Science I

Using Files as Input/Output in Java 5.0 Applications

CS506 Web Design and Development Solved Online Quiz No. 01

Scanner sc = new Scanner(System.in); // scanner for the keyboard. Scanner sc = new Scanner(System.in); // scanner for the keyboard

The Sun Certified Associate for the Java Platform, Standard Edition, Exam Version 1.0

Android Persistency: Files

13 File Output and Input

Introduction to Programming

Install Java Development Kit (JDK) 1.8

Week 1: Review of Java Programming Basics

Carron Shankland. Content. String manipula3on in Java The use of files in Java The use of the command line arguments References:

1 Introduction. 2 An Interpreter. 2.1 Handling Source Code

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

WRITING DATA TO A BINARY FILE

Topic 11 Scanner object, conditional execution

java Features Version April 19, 2013 by Thorsten Kracht

Introduction to Java. CS 3: Computer Programming in Java

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

All rights reserved. Copyright in this document is owned by Sun Microsystems, Inc.

Objectives. Streams and File I/O. Objectives, cont. Outline. I/O Overview. Streams

How To Write A Program For The Web In Java (Java)

Question R11.3. R11.3 How do you open a file whose name contains a backslash, like c:\temp\output.dat?

Interactive Programs and Graphics in Java

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Mail User Agent Project

Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output

Web Development in Java

1. Writing Simple Classes:

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

Java and XML parsing. EH2745 Lecture #8 Spring

Building Java Programs

Java CPD (I) Frans Coenen Department of Computer Science

J a v a Quiz (Unit 3, Test 0 Practice)

CSC 551: Web Programming. Fall 2001

03 - Lexical Analysis

ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters

Basics of Java Programming Input and the Scanner class

JAVA for Beginners. 2 nd Edition. Riccardo Flask

File System. /boot /system /recovery /data /cache /misc. /sdcard /sd-ext. Also Below are the for SD Card Fie System Partitions.

Building Java Programs

Files and Streams. Writeappropriatecodetoread,writeandupdatefilesusingFileInputStream, FileOutputStream and RandomAccessFile objects.

Eryq (Erik Dorfman) Zeegee Software Inc. A Crash Course in Java 1

Java Interview Questions and Answers

Computing Concepts with Java Essentials

CS1020 Data Structures and Algorithms I Lecture Note #1. Introduction to Java

The following program is aiming to extract from a simple text file an analysis of the content such as:

Explain the relationship between a class and an object. Which is general and which is specific?

Transcription:

READING DATA FROM KEYBOARD USING DATAINPUTSTREAM, BUFFEREDREADER AND SCANNER Reading text data from keyboard using DataInputStream As we have seen in introduction to streams, DataInputStream is a FilterInputStream that read primitive data from an underlying input stream in a machine-independent way. It implements the DataInput interface and provides convenience methods such as readint(), readchar etc. It also inherits the methods from its immediate parent FilterInputStream. Below program will take the input from keyboard using DataInputStream with its inherited read method and print it to a file using FileOutputStream. DataInputStream dis = new DataInputStream(System.in); FileOutputStream fout = new FileOutputStream("myFile.txt"); System.out.println("Enter text (enter & to end):"); char ch; while ((ch = (char) dis.read())!= '&') fout.write(ch); fout.close(); Input will be read on every new line byte by byte and ends reading when a '&' is encountered. FileOutputStream is a low level byte stream, whose constructor takes the name of the file as an argument. If you are not clear about streams, please do read introduction to streams first. Here the

DataInputStream wraps the System.in variable. System class s static member variable in (System.in) is of type PrintStream and represents the standard input device that is keyboard by default. To use the methods implemented for the DataInput interface, you need to understand the contract of DataInput well or you might run into errors or confusion. Also, the readline() method of the DataInputStream is deprecated as method does not properly convert bytes to characters. To use readline() and other character convenience methods, a more popular approach is to use a BufferedReader with InputStreamReader. Reading text data from keyboard using BufferedReader with InputStreamReader Instead of a DataInputStream, you can use a BufferedReader to use methods such as readline(). However System.in is a PrintStream object (PrintStream is an InputStream) and most readers like BufferedReader cannot directly use an InputStream. Hence you need to also use an InputStreamReader which will act like a bridge between an InputStream like PrintStream and a Reader like BufferedReader. BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); FileOutputStream fout = new FileOutputStream("myFile.txt"); str = br.readline(); fout.write(str.getbytes()); fout.write(system.lineseparator().getbytes()); fout.close(); br.close();

I have only replaced DataInputStream with BufferedReader from the previous example, and kept the FileOutputStream for writing to file, as is. FileOutputStream operate with bytes, but readline() of BufferedReader returns a String. Hence you need to convert your String to bytes using String's getbytes method. You can use a FileWriter or a BufferedWriter to write strings to the file without any casting or explicit conversion. BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); FileWriter fw = new FileWriter("myFile.txt"); str = br.readline(); fw.write(str); fw.write(system.lineseparator()); fw.close(); br.close(); Note that you no longer has to use getbytes() method of the String. Using a BufferedWriter will still improve the code in terms of performance and also adds a convenience method newline() which will print the line separator string as defined by the system property line.separator. You can attach a FileWriter to a BufferedWriter as:

BufferedWriter bw = new BufferedWriter(fw); And then replace the line: fw.write(system.lineseparator()); with bw.newline(); Using Scanner to read text data from keyboard Use of Scanner is a more convenient and preferred approach for reading text data from keyboard. A Scanner can parse primitive types and strings using regular expressions. A Scanner breaks its input into tokens using a delimiter pattern, which by default is whitespace, and then get those using various next methods. You can get the whole line using the nextline() method, which will return the rest of the current line, excluding any line separator and advances this scanner past the current line so that a call to nextline() again will return the next line and so on. For reading data from keyboard, we can attach the PrintStream System.in which reprecents the default input device (which is usually keyboard). import java.util.scanner; Scanner sc = new Scanner(new InputStreamReader(System.in)); FileWriter fw = new FileWriter("myFile.txt"); str = sc.nextline(); fw.write(str + "\n");

fw.close(); sc.close(); Scanner can do lot more than these and we will see them in a separate note. Source : http://javajee.com/reading-data-from-keyboard-using-datainputstream-bufferedreader-and-scanner