Input Output Examples. import java.io.*; class Greetings { public static void main (String[] args) { try { DataInputStream in = new DataInputStream(System.in);

Slides:



Advertisements
Similar presentations
1 StringBuffer & StringTokenizer Classes Chapter 5 - Other String Classes.
Advertisements

Lecture 15: I/O and Parsing
III. Streams. Introduction Often a program needs to bring in information from an external source or to send out information to an external destination.
Chapter 9 Streams and File I/O Overview of Streams and File I/O
Using Processing Stream. Predefined Streams System.in InputStream used to read bytes from the keyboard System.out PrintStream used to write bytes to the.
Unit 201 FILE IO Types of files Opening a text file for reading Reading from a text file Opening a text file for writing/appending Writing/appending to.
Exception examples. import java.io.*; import java.util.*; class IO { private String line; private StringTokenizer tokenizer; public void newline(DataInputStream.
ARRAYS public class ArrayDemo { public static void main(String[] args) { int[] anArray; // declare an array of integers anArray = new int[10]; // create.
1 String Buffer & String Tokenizer Overview l Overview of String Buffer class and Methods l Overview of String Tokenizer class and methods l Preview: Notions.
COMP 14 Introduction to Programming Miguel A. Otaduy May 17, 2004.
1 Text File I/O  I/O streams  Opening a text file for reading  Closing a stream  Reading a text file  Writing and appending to a text file.
COMP 14 Introduction to Programming Mr. Joshua Stough February 2, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
String Tokenization What is String Tokenization?
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 29, 2005.
StringBuffer class  Alternative to String class  Can be used wherever a string is used  More flexible than String  Has three constructors and more.
1 Text File I/O Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l.
1 StringTokenizer and StringBuffer classes Overview l StringTokenizer class l Some StringTokenizer methods l StringTokenizer examples l StringBuffer class.
1 Streams Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l Writing.
Strings and File I/O. Strings Java String objects are immutable Common methods include: –boolean equalsIgnoreCase(String str) –String toLowerCase() –String.
Java Review 2. The Agenda The following topics were highlighted to me as issues: –File IO (Rem) –Wrappers (Rem) –Interfaces (Rem) –Asymptotic Notation.
Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 1 Files.
7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing.
Using java’s Scanner class To read from input and from a file. (horstmann ch04 and ch 17)
Saravanan.G.
Example 1 :- Handling integer values public class Program1 { public static void main(String [] args) { int value1, value2, sum; value1 = Integer.parseInt(args[0]);
Two Ways to Store Data in a File Text format Binary format.
Session 05 Java Strings and Files. Exercise Complete the “quick-and-dirty” class CharacterCounter containing only a main() method that displays the number.
5-Oct-15 Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming Design Topic : Streams and Files Maj Joel Young.
1 Chapter 11 – Files and Streams 1 Introduction What are files? –Long-term storage of large amounts of data –Persistent data exists after termination of.
Input and Output F Stream Classes F Processing External Files F Data Streams F Print Streams F Buffered Streams F Text Input and Output on the Console.
Basic Java Programming CSCI 392 Week Two. Stuff that is the same as C++ for loops and while loops for (int i=0; i
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
Program data (instance variables, local variables, and parameters) is transient, because its lifetime ends with the program...if not, before. Sometimes.
Based on OOP with Java, by David J. Barnes Input-Output1 The java.io Package 4 Text files Reader and Writer classes 4 Byte stream files InputStream, FileInputStream,
OOP with Java, David J. Barnes Input-Output1 A complex issue in programming language design. The interface to the outside world. –Differences must be accommodated.
I/O in Java Dennis Burford
1 Recitation 8. 2 Outline Goals of this recitation: 1.Learn about loading files 2.Learn about command line arguments 3.Review of Exceptions.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
File IO Basics By Dan Fleck Coming up: Data Streams.
Introduction to Programming G50PRO University of Nottingham Unit 11 : Files Input/Ouput Paul Tennent
1 StringTokenization Overview l StringTokenizer class l Some StringTokenizer methods l StringTokenizer examples.
Two Ways to Store Data in a File  Text format  Binary format.
CS101 Lab “File input/Output”. File input, output File : binary file, text file READ/WRITE class of “text file” - File Reading class : FileReader, BufferedReader.
1 CHAPTER 3 StringTokenizer. 2 StringTokenizer CLASS There are BufferedReader methods to read a line (i.e. a record) and a character, but not just a single.
5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.
Files and Streams CS /02/05 L7: Files Slide 2 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved.
1 Software 1 Java I/O. 2 The java.io package The java.io package provides: Classes for reading input Classes for writing output Classes for manipulating.
Lecture 5 I/O and Parsing
Chapter 9 1 Chapter 9 – Part 2 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
CSI 3125, Preliminaries, page 1 Java I/O. CSI 3125, Preliminaries, page 2 Java I/O Java I/O (Input and Output) is used to process the input and produce.
String line = console.readLine() StringTokenizer st = new StringTokenizer(line)
1 / 65 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 12 Programming Fundamentals using Java 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.
Strings and File I/O. Strings Java String objects are immutable Common methods include: –boolean equalsIgnoreCase(String str) –String toLowerCase() –String.
Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Announcements/Reminders l Project 6 due on Thursday March 31 (3 weeks)
CS1020 Data Structures and Algorithms I Lecture Note #16 File Processing.
Object Oriented Programming Lecture 2: BallWorld.
1 Input-Output A complex issue in programming language design. The interface to the outside world. –Differences must be accommodated as transparently as.
CS202 Java Object Oriented Programming Input and Output Chengyu Sun California State University, Los Angeles.
OO Design and Programming II I/O: Reading and Writing
Lesson 8: More File I/O February 5, 2008
Math and String Examples
Strings and File I/O.
תרגול מס' 5: IO (קלט-פלט) זרמי קלט וזרמי פלט ((Input & Output Streams,
File class File myFile=new File(“c:/javaDemo/aa
תרגול מס' 5: IO (קלט-פלט) זרמי קלט וזרמי פלט ((Input & Output Streams,
Reading and Writing Text Files
File Input and Output.
Java IO Packages Prepared by Mrs.S.Amudha AP/SWE
Presentation transcript:

Input Output Examples

import java.io.*; class Greetings { public static void main (String[] args) { try { DataInputStream in = new DataInputStream(System.in); System.out.println("What is your name?"); String name = in.readLine(); System.out.println("Hello " + name); } catch (IOException e) { System.out.println("Exception: " + e.getMessage()); } /////////////////////////////////////////////////////////////////////////////// What is your name? Bill Gates Hello Bill Gates

import java.io.*; class Sum { public static void main (String[] args) { try { DataInputStream in = new DataInputStream(System.in); DataInputStream fin = new DataInputStream(new FileInputStream(“numbers.dat”)); int count; double total = 0; System.out.print(“How many numbers? “); System.out.flush(); count = Integer.parseInt(in.readLine()); for (int i=1; i<=count; i++) { Double number = Double.valueOf(fin.readLine()); total += number.doubleValue(); } System.out.println(“The total is: “ + total); } catch (IOException e) { System.out.println(“Exception while performing “ + e.getMessage()); }

“Numbers.dat” file ///////////////////////////////////////// javac Sum.java java Sum How many numbers: 5 The total is 21.5

//This program does not use deprecated methods import java.io.*; class MyTest { BufferedReader reader = null; public void read() { try { reader = new BufferedReader (new FileReader ("numbers.dat")); } catch (FileNotFoundException f)//if file was not found { System.out.println("File was not found"); System.exit(0); }

try { String line= new String(); double sum = 0.0; while((line=reader.readLine())!=null) { double d = Double.parseDouble(line); sum += d; } System.out.println("Sum is " + sum); } catch (Exception e) { System.out.println("Exception occurred"); } } // close read() function public static void main(String[] args) { MyTest test = new MyTest(); test.read(); } } // close MyTest class

Class java.io.File import java.io.*; public class BuildDir { public static void main(String[] args) throws IOException { File from = new File("source.txt"); File newDir = new File("newDir"); File to = new File("newDir/target.txt"); newDir.mkdir(); FileReader in = new FileReader( from ); FileWriter out = new FileWriter( to ); int character; while( (character=in.read())!= -1 ) { out.write(character); } in.close(); out.close(); from.delete(); }

Useful methods of File getAbsoulutePath() – return string. Absoulute path of the file. canRead(),canWrite()-return boolean.app can read/write to file. IsFile(), isDirectory()- return boolean. list()- return string[]. The list of the files in the directory. mkDir() – return boolean. Creat a directory. renameTo(File des) –return boolean. Renames the file name to the Des pathname.

StringTokenizer StringTokenizer היא מחלקה שמקבלת מחרוזת ומפרקת אותה לתתי מחרוזות תוך התעלמות מרווחים וטאבים (פירסינג). ;(StringTokenizer st = new StringTokenizer (str, delim, true הסבר: העצם st מקבל 3 פרמטרים: str - מחרוזת לפירוק delim - מפרידים. למשל: "," ";" וכיו"ב. כלומר, המחרוזת str תחולק לחלקים, תתי מחרוזות, עפ"י המפריד שנבחר (אם בחרנו פסיק, המחלקה תחלק את המחרוזת עפ"י הפסיקים שיש בה). ניתן להגדיר כמה מפרידים ואז הם יכתבו ברצף בתור הפרמטר delim. למשל: ";,." יגרום לחלוקת המחרוזת str עפ"י פסיקים, נקודה-פסיק, או נקודה. true/false - ערך true יחזיר גם את המפרידים (כלומר את הפסיק למשל) בתור תת מחרוזת. פונקציות במחלקה ( )st.nextToken - תחזיר את חלק המחרוזת הבא. היא יכולה לקבל מפריד מסוים, ואז תחלק את החלק הבא רק עפ"י המפריד הספציפי, ולא עפ"י המפרידים שהועברו בבנאי. ( )st.hasMoreToken - מחזיר true/false אם הסתיימה חלוקת המחרוזת.

java.util.StringTokenizer import java.io.*; import java.util.StringTokenizer; public class Tokens { public static void main(String[] args) throws IOException { BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); int first,second,pitaron; int i; char sign; String line; do { System.out.println("Enter the exercise with =."); line = in.readLine(); StringTokenizer st=new StringTokenizer(line); first=Integer.parseInt( st.nextToken("-+*/") ); sign = ( st.nextToken(" ") ).charAt(0); second= Integer.parseInt( st.nextToken("=") );

switch(sign) { case '+': pitaron= first+second; break; case '-': pitaron= first-second; break; case '*': pitaron= first*second; break; case '/': pitaron= first/second; break; default : pitaron =0; } System.out.println(line + pitaron); } while( pitaron != 0); } // close main } //close class

output: Enter the exercise with = = 12-33=-21 StringTokenizer(st1,delim)- construct a StringTokenizer for st1. delim= the delimiters. StringTokenizer(st1)- construct a StringTokenizer for st1. delimiters= tab,\n,space.(default) nextToken(delim)- return the string until the delim. CountTokens()- return the number of tokens, using the current delimiter set. HasMoreTokens()- return boolean, test if there are more tokens available.