Introduction to Algorithms and Data Structures
|
|
|
- Avis Harrington
- 9 years ago
- Views:
Transcription
1 Introduction to Algorithms and Data Structures Lecture 8 File I/O Streams A stream is an object that allows for the flow of data between a program and some I/O device (or a file). If the flow is into a program it s an input stream. If the flow is out of a program, it s an output stream. System.in and System.out are examples of input and output streams respectively. 1
2 Text and Binary Files Text files are sequences of characters that can be viewed in a text editor or read by a program. Files whose contents are binary images of information stored in main memory are called binary files. These include the computer s representation of: - numbers - pictures - sound bites - machine instructions The advantage of text files is that they are humanreadable and can be moved easily from computer system to computer system. Writing To A Text File The preferred class for writing to text files is PrintWriter, whose methods include println and print. A PrintWriter object can be created by writing: outputstream = new PrintWrite (new FileOutputStream("stuff.txt")); A FileOutputStream is needed when calling the constructor. It, in turn, needs the name of the file to which output is going to be written. Since opening a file might lead to a FileNotFoundException, it should be done in a try block. 2
3 Every File Has 2 Names Every file has 2 names: the name by which it is known the operating system of its computer and the name of the stream connect to the file (by which the program knows it). PrintWriter Methods There are three constructors: PrintWriter objectstream = new PrintWriter(OutputStream streamobject); is the standard constructor PrintWriter objectstream = new PrintWriter(new FileOutputStream (FileName)); allows us to construct a file to which it will write. PrintWriter(new FileOutputStream(FileName, true)); which we will use for appending to a file. 3
4 PrintWriter Methods (continued) public void println(argument) Prints the argument which can be a string, integer, floatingpoint number, or any object for whch a tostring() method exists. public void print(argument) Works like println with the newline at the end. public PrintWriter void printf() Formatted output close() closes the stream flush() flushes the stream, forcing any other data to be written that has been buffered but not yet written. TextFileOutputDemo.java import java.io.printwriter; import java.io.fileoutputstream; import java.io.filenotfoundexception; public class TextFileOutputDemo { public static void main(string[] args) { PrintWriter outputstream = null; try { outputstream = new PrintWriter (new FileOutputStream("stuff.txt")); catch (FileNotFoundException e) { ("\"Error opening the file stuff.txt\"."); System.exit(0); 4
5 ("Writing to file."); outputstream.println("the quick brown fox "); outputstream.println ("jumped over the lazy dogs."); outputstream.close(); ("End of program."); Reading a Text File using Scanner The same Scanner class that we have been using to read input from the keyboard can be used to read from a text file. Although the Scanner has to be declared outside the try block, the constructor should be called inside it. Example Scanner inputstream = null; try { inputstream = new Scanner (new FileInputStream( stuff.txt )); catch(filenotfoundexception e) { 5
6 Testing for the End of Line If you write Scanner keyb = new Scanner(System.in); int x = keyb.nextint() and there is no more text, (or a non-integer), nextint() will throw a NoSuchElementException You can work around this by using hasnextint()(which return false if there isn t a proper integer there or hasnextline(), which will return false if there is no next line. Some Scanner Constructors There are two constructors in which we can most interested: public Scanner(InputStream streamobject) This can be used to create stream for a file by writing public Scanner (new FileInputStream (filename)); public Scanner(File fileobject) This can be used to create a File object for a file by writing public Scanner(new File(fileName) 6
7 Some Scanner input Methods Scanner has several methods that can be used to obtain a single data item: - nextint() - nextlong() - nextbyte() - nextshort() - nextdouble() - nextfloat() All these methods will return a single value of the indicated type. If there are no more tokens, they will throw a NoSuchElementException. If the data is not a valid representation of the type, they will throw an InputMismatchException, and if the Scanner is closed, they will throw an IllegalStateException Some Scanner Input Methods Scanner has several methods that can be used to detect that there is valid data waiting as input: - hasnextint() - hasnextlong() - hasnextbyte() - hasnextshort() - hasnextdouble() - hasnextfloat() All these methods will return a true if there is a wellformed string representation of the type of the data item ; false otherwise. If the Scanner is closed, they will throw an IllegalStateException 7
8 Some Other Scanner Methods Scanner has two methods that can be used to detect that there is valid data waiting as input: - next() - hasnext() - nextline() - nextline() next() and nextline() return the next token and line respectively. hasnext() and hasnextline() return true if there is another token or line respectively; otherwise false. These methods throw the appropriate exceptions. TextFileScannerDemo.java import java.util.scanner; import java.io.fileinputstream; import java.io.filenotfoundexception; public class TextFileScannerDemo { public static void main(string[] args) { ("I will read three nunbers and a line"); ("of text from the file morestuff.txt"); Scanner inputstream = null; try { inputstream = new Scanner (new FileInputStream("morestuff.txt")); 8
9 catch(filenotfoundexception e) { ("File morestuff.txt was not found."); ("or could not be opened."); System.exit(0); int n1 = inputstream.nextint(); int n2 = inputstream.nextint(); int n3 = inputstream.nextint(); inputstream.nextline(); // Go to the next line String line = inputstream.nextline(); ("The three numbers read from the file are:"); (n1 + ", " + n2 + ", and " + n3); ("The line read from the file is:"); (line); inputstream.close(); 9
10 HasNextLineDemo.java import java.util.scanner; import java.io.fileinputstream; import java.io.filenotfoundexception; import java.io.printwriter; import java.io.fileoutputstream; public class HasNextLineDemo { public static void main(string[] args) { Scanner inputstream = null; PrintWriter outputstream = null; try { inputstream = new Scanner(new FileInputStream("original.txt")); outputstream = new PrintWriter(new FileOutputStream("numbered.txt")); catch (FileNotFoundException e) { ("Problem opening files."); System.exit(0); String line = null; int count = 0; while (inputstream.hasnextline()) { line= inputstream.nextline(); count++; outputstream.println(count + " " + line); inputstream.close(); outputstream.close(); 10
11 HasNextIntDemo.java import java.util.scanner; import java.io.fileinputstream; import java.io.filenotfoundexception; public class HasNextIntDemo { public static void main(string[] args) { Scanner inputstream = null; try { inputstream = new Scanner(new FileInputStream("data.txt")); catch (FileNotFoundException e) { ("File data.txt was not found"); ("or could not be opened."); System.exit(0); int next, sum = 0; while (inputstream.hasnextint()) { next= inputstream.nextint(); sum += next; inputstream.close(); ("The sum of the numbers is " + sum); 11
12 BufferedReader Class BufferedReader is the class that was used for reading text data before Scanner class was introduced in verion 5.0 of Java. A BufferedReader was used to open a file as shown below: BufferedReader inputstream = new BufferedReader (new FileReader( stuff.txt )); Reading Text Using BufferedReader BufferedReader has methods that are used for input: readline() reads a line of input that is returned as text. If there is no more text, it returns a null reference. read() reads a single character from the input stream that is returned as an integer.. If there is no more text, it returns -1 skip(int n) skips n characters. close() closes the stream s connection to the file. These methods all throw IOException. 12
13 TextFileInputDemo.java import java.io.bufferedreader; import java.io.filereader; import java.io.filenotfoundexception; import java.io.ioexception; public class TextFileInputDemo { public static void main(string[] args) { try { BufferedReader inputstream = new BufferedReader (new FileReader("morestuff2.txt")); String line = inputstream.readline(); ("The first line read from the file is:"); (line); line= inputstream.readline(); ("The second line read from the file is:"); (line); inputstream.close(); catch(filenotfoundexception e) { ("File morestuff2.txt was not found"); ("or could not be opened."); catch (IOException e) { ("Error reading from morestuff2.txt"); 13
14 TextEOFDemo.java import java.io.bufferedreader; import java.io.filereader; import java.io.printwriter; import java.io.fileoutputstream; import java.io.filenotfoundexception; import java.io.ioexception; public class TextEOFDemo { public static void main(string[] args) { try { BufferedReader inputstream = new BufferedReader (new FileReader("original.txt")); PrintWriter outputstream = new PrintWriter(new FileOutputStream("numbered.txt")); int count= 0; String line= inputstream.readline(); while (line!= null) { count++; outputstream.println(count + " " + line); line = inputstream.readline(); inputstream.close(); outputstream.close(); catch (FileNotFoundException e) { ("Problem opening file."); catch (IOException e) { ("Error reading from original.txt"); 14
15 Standard Streams All Java programs are assumed to have at least three open streams: System.in, System.out and System.err (the last one allows for error message and output to be redirects separately). RedirectionDemo.java import java.io.printstream; import java.io.fileoutputstream; import java.io.filenotfoundexception; public class RedirectionDemo { public static void main(string[] args) { PrintStream errstream = null; try { errstream = new PrintStream(new FileOutputStream("errormessage.txt")); catch (FileNotFoundException e) { ("Error opening file with FileOutputSteam."); System.exit(0); 15
16 System.setErr(errStream); System.err.println("Hello fgom System.err."); System.err.println("Hello from System.out."); System.err.println("Hello again from System.err."); errstream.close(); File Class The File class is a bit like a wrapper class for file names. It also provides us with some methods that can be used to check some basic properties of files, such as whether it exists, does the program have permission to read or write it. Example: File fileobject = new File( data.txt ); if (!fileobject.canread()) ("file data.txt is not readable."); 16
17 File Class Methods exists() returns true if it exists; false otherwise canread() returns true if the program can read data from the file; false otherwise. canwrite() - returns true if the program can write data from the file; false otherwise. isfile() returns true if the file exists and is a regular file; false otherwise. isdirectory() - returns true if the file exists and is a directory; false otherwise. File Class Methods (continued) length() returns the number of bytes in the file as a long.if it doesn t exist or if it s a directory, the value returned isn t specified. delete() tries to delete the file; returns true if it can, false if it can t. setreadonly() sets the file as read only; returns true if it is can; false if it can t. createnewfile() creates an empty of that name; returns true if it can; false if it can t isfile() returns true if the file exists and is a regular file; false otherwise. isdirectory() - returns true if the file exists and is a directory; false otherwise. 17
18 File Class Methods (continued) getname() return the simple name (the last part of the path). getpath() returns the abstract (absolute or relative) path name or an empty string if the path name is an empty string.. renameto(newname) renames the file to a name represented by the file object newname; returns true if it is can; false if it can t. createnewfile() creates an empty of that name; returns true if it can; false if it can t mkdir() makes the directory named by the abstract path name. Will not create parent directories; returns true if the file exists and is a regular file; false otherwise. mkdirs() - makes the directory named by the abstract path name. Will necessary but nonexistent create parent directories; returns true if the file exists and is a regular file; false otherwise. FileClassDemo.java import java.util.scanner; import java.io.file; import java.io.printwriter; import java.io.fileoutputstream; import java.io.filenotfoundexception; public class FileClassDemo { public static void main(string[] args) { Scanner keyb= new Scanner(System.in); String line = null; String filename = null; ("I will store a line of text for you."); ("Enter the line of text:"); line = keyb.nextline(); 18
19 ("Enter a file name to hold the line:"); filename = keyb.nextline(); File fileobject = new File(fileName); while (fileobject.exists()) { ("There already is a file named " + filename); ("Enter a different file name:"); filename = keyb.nextline(); fileobject= new File(fileName); PrintWriter outputstream = null; try { outputstream = new PrintWriter(new FileOutputStream(fileName)); catch (FileNotFoundException e) { ("Error opening the file."); System.exit(0); ("writing \"" + line + "\""); ("to the file " + filename); outputstream.println(line); outputstream.close(); ("Writing completed."); 19
20 Binary Files Text files save data in the same form as they appear on the screen or printed page. This requires the computer to do some conversion when reading and writing them. Binary files save data in their internal form. Strings have their unused bytes saved Numbers are stored in binary form. Classes Used in Writing a Binary File There are two classes of objects used in writing binary files: FileOutputStream stream objects that write data to a file. ObjectOutputStream - objects that take data of a certain type and converting it into a stream of bytes. 20
21 The writeprimitive() Methods The ObjectOutputStream class has several methods of writeprimitive(di) that allows the programmer to write the data item di of type Primitive into the file. They all throw IOExceptions The methods include: oos.writeint(i)- write integer value i into the binary file dos. oos.writedouble(x) - write double value x into the binary file dos. oos.writechar(c) - write char value c into the binary file dos. BinaryOutputDemo.java import java.io.objectoutputstream; import java.io.fileoutputstream; import java.io.ioexception; public class BinaryOutputDemo { public static void main(string[] args) { try { ObjectOutputStream outputstream = new ObjectOutputStream(new FileOutputStream("numbers.dat")); int i; for (i = 0; i < 5; i++) outputstream.writeint(i); 21
22 ("\"Numbers written to the" + " file numbers.dat\""); outputstream.close(); catch(ioexception e) { ("Problem writing with file output."); Reading a Binary File We do this essentially the same way that we write a binary file. It is very important that we know exactly what the files structure is so we can read it accurately. 22
23 The readprimitive() Methods The ObjectInputStream class has several methods of readprimitive(di) that allows the programmer to read the data item di of type Primitive from the file. The methods include: ois.readint(i)- read integer value i from the binary file dos. ois.readdouble(x) - read double value x from the binary file dos. ois.readchar(c) read char value c from the binary file dos. BinaryInputDemo.java import java.io.objectinputstream; import java.io.fileinputstream; import java.io.ioexception; import java.io.filenotfoundexception; public class BinaryInputDemo { public static void main(string[] args) { try { ObjectInputStream inputstream = new ObjectInputStream(new FileInputStream("numbers.dat")); ("Reading the file \"numbers.dat\""); int n1 = inputstream.readint(); int n2 = inputstream.readint(); 23
24 ("Numbers read from file:"); (n1); (n2); inputstream.close(); catch(filenotfoundexception e) { ("Cannot find file \"numbers.dat\""); catch(ioexception e) { ("Problem with input from \"numbers.dat\"."); Files And Records Many programming languages and computer systems treat files as a collection of records, where you read and write one record at a time. Java does not have anything exactly analogous to records; we use objects instead. We will create an implementation of the class Serializable so the properties of our objects can be converted into a byte stream and saved in a binary file. 24
25 SomeClass.java import java.io.serializable; public class SomeClass implements Serializable { private int number; private char letter; public SomeClass() { number = 0; letter = 'A'; public SomeClass(int thenumber, char theletter) { number = thenumber; letter = theletter; public String tostring() { return "Number = " + number + " Letter " + letter; 25
26 ObjectIODemo.java import java.io.objectoutputstream; import java.io.fileoutputstream; import java.io.objectinputstream; import java.io.fileinputstream; import java.io.ioexception; import java.io.filenotfoundexception; // Demonstrates binaryfile I/O of serializable // class objects public class ObjectIODemo { public static void main(string[] args) { try { ObjectOutputStream outputstream = new ObjectOutputStream(new FileOutputStream("datafile")); SomeClass oneobject = new SomeClass(1, 'A'); SomeClass anotherobject = new SomeClass(42, '2'); outputstream.writeobject(oneobject); outputstream.writeobject(anotherobject); outputstream.close(); ("Data sent fo file."); catch(ioexception e) { ("Problem with file output."); ("Now let\'s reopen the file " + " and display the data."); 26
27 try { ObjectInputStream inputstream = new ObjectInputStream(new FileInputStream("datafile")); SomeClass readone = (SomeClass) inputstream.readobject(); SomeClass readtwo = (SomeClass) inputstream.readobject(); ("The following were read from the file:"); (readone); (readtwo); catch (FileNotFoundException e) { ("Cannot find datafile."); catch(classnotfoundexception e) { ("Problems with file input."); catch(ioexception e) { ("Problems with file input."); ("End of program."); 27
28 ArrayIODemo.java import java.io.objectoutputstream; import java.io.fileoutputstream; import java.io.objectinputstream; import java.io.fileinputstream; import java.io.ioexception; import java.io.filenotfoundexception; public class ArrayIODemo { public static void main(string[] args) { SomeClass[] a = new SomeClass[2]; a[0] = new SomeClass(1, 'A'); a[1] = new SomeClass(2, 'B'); try { ObjectOutputStream outputstream = new ObjectOutputStream( new FileOutputStream("arrayfile")); outputstream.writeobject(a); outputstream.close(); catch(ioexception e) { ("Error writing to file."); System.exit(0); ("Array written to file arrayfile."); ("Now let's re-open the " + "file and display the arrow."); 28
29 SomeClass[] b = null; try { ObjectInputStream inputstream = new ObjectInputStream( new FileInputStream("arrayfile")); b = (SomeClass[])inputStream.readObject(); inputstream.close(); catch (FileNotFoundException e) { ("Cannot find file arrayfile."); System.exit(0); catch (ClassNotFoundException e) { ("Problems with file input."); System.exit(0); catch(ioexception e) { ("Problems with file input."); ("The following array + "elements were read from the file:"); int i; for (i = 0; i < b.length; i++) (b[i]); ("End of program."); 29
30 Random Access Files We usually read files from the beginning to the end. Files that are always accessed in this fashion as called sequential access files. Sometimes we need to read files from any particular point to which we may need access. These are called random access files. These have two methods that other files do not have: getfilepointer() (which takes us to the current location from which we are reading) and seek() (which moves us to another location in the file). RandomAccessDemo.java import java.io.randomaccessfile; import java.io.ioexception; import java.io.filenotfoundexception; public class RandomAccessDemo { public static void main(string[] args) { try { RandomAccessFile iostream = new RandomAccessFile("bytedata", "rw"); ("Writing 3 bytes to the file bytedata."); iostream.writebyte(1); iostream.writebyte(2); iostream.writebyte(3); ("the length of the file is now = " + iostream.length()); 30
31 ("The file pointer location is " + iostream.getfilepointer()); ("Moving the file pointer to location 1."); iostream.seek(1); byte onebyte = iostream.readbyte(); ("The value at location 1is " + onebyte); onebyte = iostream.readbyte(); ("The value at the next location is " + onebyte); ("Now we can move the file pointer back to "); ("location 1, and change the byte."); iostream.seek(1); iostream.writebyte(9); iostream.seek(1); onebyte = iostream.readbyte(); ("The value at location 1 is now " + onebyte); ("Now we can go to the end of the file"); ("and write a double."); iostream.seek(iostream.length()); iostream.writedouble(41.99); ("the length of the fiule is now = " + iostream.length()); ("Returning to location 3, "); 31
32 ("where we wrote the double."); iostream.seek(3); double onedouble = iostream.readdouble(); ("The double version of location is " + onedouble); iostream.close(); catch(filenotfoundexception e) { ("Problem opening file."); catch (IOException e) { ("Problems with file I/O"); ("End of program."); 32
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
Chapter 10 File I/O Streams A stream is an object that enables the flow of data between a program and some I/O device or file If the data flows into a program, then the stream is called an input stream
D06 PROGRAMMING with JAVA
Cicles Formatius de Grau Superior Desenvolupament d Aplicacions Informàtiques D06 PROGRAMMING with JAVA Ch16 Files and Streams PowerPoint presentation, created by Angel A. Juan - ajuanp(@)gmail.com, for
JAVA.UTIL.SCANNER CLASS
JAVA.UTIL.SCANNER CLASS http://www.tutorialspoint.com/java/util/java_util_scanner.htm Copyright tutorialspoint.com Introduction The java.util.scanner class is a simple text scanner which can parse primitive
Objectives. Streams and File I/O. Objectives, cont. Outline. I/O Overview. Streams
Objectives Streams and File I/O Chapter 9 become familiar with the concept of an I/O stream understand the difference between binary files and text files learn how to save data in a file learn how to read
CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O
CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O 1 Sending Output to a (Text) File import java.util.scanner; import java.io.*; public class TextFileOutputDemo1 public static void
Object-Oriented Programming in Java
CSCI/CMPE 3326 Object-Oriented Programming in Java Class, object, member field and method, final constant, format specifier, file I/O Dongchul Kim Department of Computer Science University of Texas Rio
INPUT AND OUTPUT STREAMS
INPUT AND OUTPUT The Java Platform supports different kinds of information sources and information sinks. A program may get data from an information source which may be a file on disk, a network connection,
Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.
Scanner The Scanner class is intended to be used for input. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit. For example, suppose the input
Chapter 20 Streams and Binary Input/Output. Big Java Early Objects by Cay Horstmann Copyright 2014 by John Wiley & Sons. All rights reserved.
Chapter 20 Streams and Binary Input/Output Big Java Early Objects by Cay Horstmann Copyright 2014 by John Wiley & Sons. All rights reserved. 20.1 Readers, Writers, and Streams Two ways to store data: Text
Using Files as Input/Output in Java 5.0 Applications
Using Files as Input/Output in Java 5.0 Applications The goal of this module is to present enough information about files to allow you to write applications in Java that fetch their input from a file instead
java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner
java.util.scanner java.util.scanner is a class in the Java API used to create a Scanner object, an extremely versatile object that you can use to input alphanumeric characters from several input sources
Files and input/output streams
Unit 9 Files and input/output streams Summary The concept of file Writing and reading text files Operations on files Input streams: keyboard, file, internet Output streams: file, video Generalized writing
Chulalongkorn University International School of Engineering Department of Computer Engineering 2140105 Computer Programming Lab.
Chulalongkorn University Name International School of Engineering Student ID Department of Computer Engineering Station No. 2140105 Computer Programming Lab. Date Lab 2 Using Java API documents, command
What is an I/O Stream?
Java I/O Stream 1 Topics What is an I/O stream? Types of Streams Stream class hierarchy Control flow of an I/O operation using Streams Byte streams Character streams Buffered streams Standard I/O streams
Event-Driven Programming
Event-Driven Programming Lecture 4 Jenny Walter Fall 2008 Simple Graphics Program import acm.graphics.*; import java.awt.*; import acm.program.*; public class Circle extends GraphicsProgram { public void
Input / Output Framework java.io Framework
Date Chapter 11/6/2006 Chapter 10, start Chapter 11 11/13/2006 Chapter 11, start Chapter 12 11/20/2006 Chapter 12 11/27/2006 Chapter 13 12/4/2006 Final Exam 12/11/2006 Project Due Input / Output Framework
Introduction to Java
Introduction to Java The HelloWorld program Primitive data types Assignment and arithmetic operations User input Conditional statements Looping Arrays CSA0011 Matthew Xuereb 2008 1 Java Overview A high
File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)
File class in Java File Input and Output (Savitch, Chapter 10) TOPICS File Input Exception Handling File Output Programmers refer to input/output as "I/O". The File class represents files as objects. The
320341 Programming in Java
320341 Programming in Java Fall Semester 2014 Lecture 10: The Java I/O System Instructor: Slides: Jürgen Schönwälder Bendick Mahleko Objectives This lecture introduces the following - Java Streams - Object
CS 1302 Ch 19, Binary I/O
CS 1302 Ch 19, Binary I/O Sections Pages Review Questions Programming Exercises 19.1-19.4.1, 19.6-19.6 710-715, 724-729 Liang s Site any Sections 19.1 Introduction 1. An important part of programming is
File I/O - Chapter 10. Many Stream Classes. Text Files vs Binary Files
File I/O - Chapter 10 A Java stream is a sequence of bytes. An InputStream can read from a file the console (System.in) a network socket an array of bytes in memory a StringBuffer a pipe, which is an OutputStream
Principles of Software Construction: Objects, Design, and Concurrency. Design Case Study: Stream I/O Some answers. Charlie Garrod Jonathan Aldrich
Principles of Software Construction: Objects, Design, and Concurrency Design Case Study: Stream I/O Some answers Fall 2014 Charlie Garrod Jonathan Aldrich School of Computer Science 2012-14 C Kästner,
JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4
JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4 NOTE: SUN ONE Studio is almost identical with NetBeans. NetBeans is open source and can be downloaded from www.netbeans.org. I
Creating a Simple, Multithreaded Chat System with Java
Creating a Simple, Multithreaded Chat System with Java Introduction by George Crawford III In this edition of Objective Viewpoint, you will learn how to develop a simple chat system. The program will demonstrate
AP Computer Science File Input with Scanner
AP Computer Science File Input with Scanner Subset of the Supplement Lesson slides from: Building Java Programs, Chapter 6 by Stuart Reges and Marty Stepp (http://www.buildingjavaprograms.com/ ) Input/output
Chapter 2: Elements of Java
Chapter 2: Elements of Java Basic components of a Java program Primitive data types Arithmetic expressions Type casting. The String type (introduction) Basic I/O statements Importing packages. 1 Introduction
13 File Output and Input
SCIENTIFIC PROGRAMMING -1 13 File Output and Input 13.1 Introduction To make programs really useful we have to be able to input and output data in large machinereadable amounts, in particular we have to
JAVA - FILES AND I/O
http://www.tutorialspoint.com/java/java_files_io.htm JAVA - FILES AND I/O Copyright tutorialspoint.com The java.io package contains nearly every class you might ever need to perform input and output I/O
The Java I/O System. Binary I/O streams (ascii, 8 bits) The decorator design pattern Character I/O streams (Unicode, 16 bits)
Binary I/O streams (ascii, 8 bits) InputStream OutputStream The Java I/O System The decorator design pattern Character I/O streams (Unicode, 16 bits) Reader Writer Comparing Binary I/O to Character I/O
WRITING DATA TO A BINARY FILE
WRITING DATA TO A BINARY FILE TEXT FILES VS. BINARY FILES Up to now, we have looked at how to write and read characters to and from a text file. Text files are files that contain sequences of characters.
Carron Shankland. Content. String manipula3on in Java The use of files in Java The use of the command line arguments References:
CSCU9T4 (Managing Informa3on): Strings and Files in Java Carron Shankland Content String manipula3on in Java The use of files in Java The use of the command line arguments References: Java For Everyone,
Visit us at www.apluscompsci.com
Visit us at www.apluscompsci.com Full Curriculum Solutions M/C Review Question Banks Live Programming Problems Tons of great content! www.facebook.com/apluscomputerscience Scanner kb = new Scanner(System.in);
Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output
Chapter 2 Console Input and Output System.out.println for console output System.out is an object that is part of the Java language println is a method invoked dby the System.out object that can be used
Stream Classes and File I/O
Stream Classes and File I/O A stream is any input source or output destination for data. The Java API includes about fifty classes for managing input/output streams. Objects of these classes can be instantiated
Course Intro Instructor Intro Java Intro, Continued
Course Intro Instructor Intro Java Intro, Continued The syllabus Java etc. To submit your homework, do Team > Share Your repository name is csse220-200830-username Use your old SVN password. Note to assistants:
Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.
Handout 1 CS603 Object-Oriented Programming Fall 15 Page 1 of 11 Handout 1 Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Java
6.1. Example: A Tip Calculator 6-1
Chapter 6. Transition to Java Not all programming languages are created equal. Each is designed by its creator to achieve a particular purpose, which can range from highly focused languages designed for
Question1-part2 What undesirable consequences might there be in having too long a DNS cache entry lifetime?
CSCI 312 - DATA COMMUNICATIONS AND NETWORKS FALL, 2014 Assignment 4 Working as a group. Working in small gruops of 2-4 students. When you work as a group, you have to return only one home assignment per
READING DATA FROM KEYBOARD USING DATAINPUTSTREAM, BUFFEREDREADER AND SCANNER
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
Readings and References. Topic #10: Java Input / Output. "Streams" are the basic I/O objects. Input & Output. Streams. The stream model A-1.
Readings and References Topic #10: Java Input / Output CSE 413, Autumn 2004 Programming Languages Reading Other References» Section "I/O" of the Java tutorial» http://java.sun.com/docs/books/tutorial/essential/io/index.html
CS 111 Classes I 1. Software Organization View to this point:
CS 111 Classes I 1 Software Organization View to this point: Data Objects and primitive types Primitive types operators (+, /,,*, %). int, float, double, char, boolean Memory location holds the data Objects
CS 121 Intro to Programming:Java - Lecture 11 Announcements
CS 121 Intro to Programming:Java - Lecture 11 Announcements Next Owl assignment up, due Friday (it s short!) Programming assignment due next Monday morning Preregistration advice: More computing? Take
Chapter 3. Input and output. 3.1 The System class
Chapter 3 Input and output The programs we ve looked at so far just display messages, which doesn t involve a lot of real computation. This chapter will show you how to read input from the keyboard, use
public static void main(string[] args) { System.out.println("hello, world"); } }
Java in 21 minutes hello world basic data types classes & objects program structure constructors garbage collection I/O exceptions Strings Hello world import java.io.*; public class hello { public static
Building Java Programs
Building Java Programs Chapter 3 Lecture 3-3: Interactive Programs w/ Scanner reading: 3.3-3.4 self-check: #16-19 exercises: #11 videos: Ch. 3 #4 Interactive programs We have written programs that print
Building Java Programs
Building Java Programs Chapter 3 Lecture 3-3: Interactive Programs w/ Scanner reading: 3.3-3.4 self-check: #16-19 exercises: #11 videos: Ch. 3 #4 Interactive programs We have written programs that print
CS 193A. Data files and storage
CS 193A Data files and storage This document is copyright (C) Marty Stepp and Stanford Computer Science. Licensed under Creative Commons Attribution 2.5 License. All rights reserved. Files and storage
Explain the relationship between a class and an object. Which is general and which is specific?
A.1.1 What is the Java Virtual Machine? Is it hardware or software? How does its role differ from that of the Java compiler? The Java Virtual Machine (JVM) is software that simulates the execution of a
D06 PROGRAMMING with JAVA
Cicles Formatius de Grau Superior Desenvolupament d Aplicacions Informàtiques D06 PROGRAMMING with JAVA Ch15 Exception Handling PowerPoint presentation, created by Angel A. Juan - ajuanp(@)gmail.com, for
Quick Introduction to Java
Quick Introduction to Java Dr. Chris Bourke Department of Computer Science & Engineering University of Nebraska Lincoln Lincoln, NE 68588, USA Email: [email protected] 2015/10/30 20:02:28 Abstract These
Building a Multi-Threaded Web Server
Building a Multi-Threaded Web Server In this lab we will develop a Web server in two steps. In the end, you will have built a multi-threaded Web server that is capable of processing multiple simultaneous
Introduction to Java. CS 3: Computer Programming in Java
Introduction to Java CS 3: Computer Programming in Java Objectives Begin with primitive data types Create a main class with helper methods Learn how to call built-in class methods and instance methods
Comp 248 Introduction to Programming
Comp 248 Introduction to Programming Chapter 2 - Console Input & Output Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal, Canada These slides has been
Lecture 5: Java Fundamentals III
Lecture 5: Java Fundamentals III School of Science and Technology The University of New England Trimester 2 2015 Lecture 5: Java Fundamentals III - Operators Reading: Finish reading Chapter 2 of the 2nd
Introduction to Java Applications. 2005 Pearson Education, Inc. All rights reserved.
1 2 Introduction to Java Applications 2.2 First Program in Java: Printing a Line of Text 2 Application Executes when you use the java command to launch the Java Virtual Machine (JVM) Sample program Displays
First Java Programs. V. Paúl Pauca. CSC 111D Fall, 2015. Department of Computer Science Wake Forest University. Introduction to Computer Science
First Java Programs V. Paúl Pauca Department of Computer Science Wake Forest University CSC 111D Fall, 2015 Hello World revisited / 8/23/15 The f i r s t o b l i g a t o r y Java program @author Paul Pauca
Question R11.3. R11.3 How do you open a file whose name contains a backslash, like c:\temp\output.dat?
Chapter 11 Question R11.1: R11.1 What happens if you try to open a file for reading that doesn t exist? What happens if you try to open a file for writing that doesn t exist? The system throws an IOException
CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals
CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals 1 Recall From Last Time: Java Program import java.util.scanner; public class EggBasket { public static void main(string[]
Programming Languages CIS 443
Course Objectives Programming Languages CIS 443 0.1 Lexical analysis Syntax Semantics Functional programming Variable lifetime and scoping Parameter passing Object-oriented programming Continuations Exception
www.virtualians.pk CS506 Web Design and Development Solved Online Quiz No. 01 www.virtualians.pk
CS506 Web Design and Development Solved Online Quiz No. 01 Which of the following is a general purpose container? JFrame Dialog JPanel JApplet Which of the following package needs to be import while handling
Basics of Java Programming Input and the Scanner class
Basics of Java Programming Input and the Scanner class CSC 1051 Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/
Chapter 2 Elementary Programming
Chapter 2 Elementary Programming 2.1 Introduction You will learn elementary programming using Java primitive data types and related subjects, such as variables, constants, operators, expressions, and input
Basics of I/O Streams and File I/O
Basics of This is like a cheat sheet for file I/O in C++. It summarizes the steps you must take to do basic I/O to and from files, with only a tiny bit of explanation. It is not a replacement for reading
Assignment 4 Solutions
CSCI 312 - DATA COMMUNICATIONS AND NETWORKS FALL, 2014 Assignment 4 Solutions Working as a pair Working in pairs. When you work as a pair you have to return only one home assignment per pair on a round.
Java Network Programming. The java.net package contains the Socket class. This class speaks TCP (connection-oriented protocol).
Java Network Programming The java.net package contains the Socket class. This class speaks TCP (connection-oriented protocol). The DatagramSocket class uses UDP (connectionless protocol). The java.net.socket
Software Development in Java
Software Development in Java Week8 Semester 2 2015 Object-Oriented Development Design process Implementation process Testing process (Supplement: Introduction to JUnit) File IO Next Wed (WEEK 9): QUIZ
Install Java Development Kit (JDK) 1.8 http://www.oracle.com/technetwork/java/javase/downloads/index.html
CS 259: Data Structures with Java Hello World with the IntelliJ IDE Instructor: Joel Castellanos e-mail: joel.unm.edu Web: http://cs.unm.edu/~joel/ Office: Farris Engineering Center 319 8/19/2015 Install
Continuous Integration Part 2
1 Continuous Integration Part 2 This blog post is a follow up to my blog post Continuous Integration (CI), in which I described how to execute test cases in Code Tester (CT) in a CI environment. What I
AVRO - SERIALIZATION
http://www.tutorialspoint.com/avro/avro_serialization.htm AVRO - SERIALIZATION Copyright tutorialspoint.com What is Serialization? Serialization is the process of translating data structures or objects
JAVA - EXCEPTIONS. An exception can occur for many different reasons, below given are some scenarios where exception occurs.
http://www.tutorialspoint.com/java/java_exceptions.htm JAVA - EXCEPTIONS Copyright tutorialspoint.com An exception orexceptionalevent is a problem that arises during the execution of a program. When an
Reading Input From A File
Reading Input From A File In addition to reading in values from the keyboard, the Scanner class also allows us to read in numeric values from a file. 1. Create and save a text file (.txt or.dat extension)
Java from a C perspective. Plan
Java from a C perspective Cristian Bogdan 2D2052/ingint04 Plan Objectives and Book Packages and Classes Types and memory allocation Syntax and C-like Statements Object Orientation (minimal intro) Exceptions,
About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. AVRO Tutorial
i About the Tutorial Apache Avro is a language-neutral data serialization system, developed by Doug Cutting, the father of Hadoop. This is a brief tutorial that provides an overview of how to set up Avro
Division of Informatics, University of Edinburgh
CS1Bh Lecture Note 20 Client/server computing A modern computing environment consists of not just one computer, but several. When designing such an arrangement of computers it might at first seem that
Topic 11 Scanner object, conditional execution
Topic 11 Scanner object, conditional execution "There are only two kinds of programming languages: those people always [complain] about and those nobody uses." Bjarne Stroustroup, creator of C++ Copyright
Lesson: All About Sockets
All About Sockets http://java.sun.com/docs/books/tutorial/networking/sockets/index.html Page 1 sur 1 The Java TM Tutorial Start of Tutorial > Start of Trail Trail: Custom Networking Lesson: All About Sockets
CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013
Oct 4, 2013, p 1 Name: CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013 1. (max 18) 4. (max 16) 2. (max 12) 5. (max 12) 3. (max 24) 6. (max 18) Total: (max 100)
COSC 6397 Big Data Analytics. Distributed File Systems (II) Edgar Gabriel Spring 2014. HDFS Basics
COSC 6397 Big Data Analytics Distributed File Systems (II) Edgar Gabriel Spring 2014 HDFS Basics An open-source implementation of Google File System Assume that node failure rate is high Assumes a small
IMDB Data Set Topics: Parsing Input using Scanner class. Atul Prakash
IMDB Data Set Topics: Parsing Input using Scanner class Atul Prakash IMDB Data Set Consists of several files: movies.list: contains actors.list: contains aka-titles.list:
Programming and Data Structures with Java and JUnit. Rick Mercer
Programming and Data Structures with Java and JUnit Rick Mercer ii Chapter Title 1 Program Development 2 Java Fundamentals 3 Objects and JUnit 4 Methods 5 Selection (if- else) 6 Repetition (while and for
TP N 10 : Gestion des fichiers Langage JAVA
TP N 10 : Gestion des fichiers Langage JAVA Rappel : Exemple d utilisation de FileReader/FileWriter import java.io.*; public class Copy public static void main(string[] args) throws IOException File inputfile
Using Two-Dimensional Arrays
Using Two-Dimensional Arrays Great news! What used to be the old one-floor Java Motel has just been renovated! The new, five-floor Java Hotel features a free continental breakfast and, at absolutely no
Line-based file processing
Line-based file processing reading: 6.3 self-check: #7-11 exercises: #1-4, 8-11 Hours question Given a file hours.txt with the following contents: 123 Kim 12.5 8.1 7.6 3.2 456 Brad 4.0 11.6 6.5 2.7 12
COSC 1020 3.0 Introduction to Computer Science I Section A, Summer 2005. Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19
Term Test #2 COSC 1020 3.0 Introduction to Computer Science I Section A, Summer 2005 Family Name: Given Name(s): Student Number: Question Out of Mark A Total 16 B-1 7 B-2 4 B-3 4 B-4 4 B Total 19 C-1 4
CS 106 Introduction to Computer Science I
CS 106 Introduction to Computer Science I 01 / 29 / 2014 Instructor: Michael Eckmann Today s Topics Comments and/or Questions? import user input using JOptionPane user input using Scanner psuedocode import
Computer Programming I
Computer Programming I COP 2210 Syllabus Spring Semester 2012 Instructor: Greg Shaw Office: ECS 313 (Engineering and Computer Science Bldg) Office Hours: Tuesday: 2:50 4:50, 7:45 8:30 Thursday: 2:50 4:50,
java Features Version April 19, 2013 by Thorsten Kracht
java Features Version April 19, 2013 by Thorsten Kracht Contents 1 Introduction 2 1.1 Hello World................................................ 2 2 Variables, Types 3 3 Input/Output 4 3.1 Standard I/O................................................
System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :
Benjamin Michael Java Homework 3 10/31/2012 1) Sales.java Code // Sales.java // Program calculates sales, based on an input of product // number and quantity sold import java.util.scanner; public class
Introduction to Programming
Introduction to Programming Lecturer: Steve Maybank Department of Computer Science and Information Systems [email protected] Spring 2015 Week 2b: Review of Week 1, Variables 16 January 2015 Birkbeck
J a v a Quiz (Unit 3, Test 0 Practice)
Computer Science S-111a: Intensive Introduction to Computer Science Using Java Handout #11 Your Name Teaching Fellow J a v a Quiz (Unit 3, Test 0 Practice) Multiple-choice questions are worth 2 points
AP Computer Science Java Mr. Clausen Program 9A, 9B
AP Computer Science Java Mr. Clausen Program 9A, 9B PROGRAM 9A I m_sort_of_searching (20 points now, 60 points when all parts are finished) The purpose of this project is to set up a program that will
Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:
Introduction to Programming and Algorithms Module 2 CS 146 Sam Houston State University Dr. Tim McGuire Introduction To Computers And Java Chapter Objectives To understand: the meaning and placement of
AWS Encryption SDK. Developer Guide
AWS Encryption SDK Developer Guide AWS Encryption SDK: Developer Guide Copyright 2016 Amazon Web Services, Inc. and/or its affiliates. All rights reserved. Amazon's trademarks and trade dress may not be
CSS 543 Program 3: Online Tic-Tac-Toe Game Professor: Munehiro Fukuda Due date: see the syllabus
CSS 543 Program 3: Online Tic-Tac-Toe Game Professor: Munehiro Fukuda Due date: see the syllabus 1. Purpose This assignment exercises how to write a peer-to-peer communicating program using non-blocking
Building Java Programs
Building Java Programs Chapter 4 Lecture 4-1: Scanner; if/else reading: 3.3 3.4, 4.1 Interactive Programs with Scanner reading: 3.3-3.4 1 Interactive programs We have written programs that print console
