STANDARD ERROR - Computer Science Department ...sprenkle/cs209/pre_class/11-streams.pdf• Example:...

17
10/5/16 1 Objec&ves Standard Error Streams Ø Byte Streams Ø Text Streams Oct 5, 2016 Sprenkle - CSCI209 1 STANDARD ERROR Oct 5, 2016 Sprenkle - CSCI209 2

Transcript of STANDARD ERROR - Computer Science Department ...sprenkle/cs209/pre_class/11-streams.pdf• Example:...

Page 1: STANDARD ERROR - Computer Science Department ...sprenkle/cs209/pre_class/11-streams.pdf• Example: Make an input reader of type InputStreamReader that reads from keyboard Øin reads

10/5/16

1

Objec&ves• StandardError• Streams

Ø ByteStreamsØ TextStreams

Oct 5, 2016 Sprenkle - CSCI209 1

STANDARDERROR

Oct 5, 2016 Sprenkle - CSCI209 2

Page 2: STANDARD ERROR - Computer Science Department ...sprenkle/cs209/pre_class/11-streams.pdf• Example: Make an input reader of type InputStreamReader that reads from keyboard Øin reads

10/5/16

2

StandardStreams• Preconnectedstreams

Ø StandardOut:stdoutØ StandardIn:stdinØ StandardError:stderr

• Forerrormessagesanddiagnos&cs•  InJava:System.err

Oct 5, 2016 Sprenkle - CSCI209 3

Benefits of two output streams (out and err)?

Redirec&ngOutput• Recallearlierthissemester

Ø Redirectedstdout toscore.outØ stderr woulds&llgototerminal

• Toredirectstderrtofileaswell

Oct 5, 2016 Sprenkle - CSCI209 4

> java OlympicScore > score.out

> java OlympicScore >& score.out

Page 3: STANDARD ERROR - Computer Science Department ...sprenkle/cs209/pre_class/11-streams.pdf• Example: Make an input reader of type InputStreamReader that reads from keyboard Øin reads

10/5/16

3

STREAMS

Oct 5, 2016 Sprenkle - CSCI209 5

Oct 5, 2016 Sprenkle - CSCI209 6

Streams• Javahandlesinput/outputusingstreams,whicharesequencesofbytes

input stream: an object from which we can read a sequence of bytes abstract class: java.io.InputStream

Page 4: STANDARD ERROR - Computer Science Department ...sprenkle/cs209/pre_class/11-streams.pdf• Example: Make an input reader of type InputStreamReader that reads from keyboard Øin reads

10/5/16

4

Oct 5, 2016 Sprenkle - CSCI209 7

Streams• Javahandlesinput/outputusingstreams,whicharesequencesofbytes

output stream: an object to which we can write a sequence of bytes abstract class: java.io.OutputStream

Oct 5, 2016 Sprenkle - CSCI209 8

java.io ClassesOverview• Twotypesofstreamclasses,basedontypeofdata:Byte,Text

• Abstractbaseclassesforbinarydata:

• Abstractbaseclassesfortextdata:

InputStream OutputStream

Reader Writer

Page 5: STANDARD ERROR - Computer Science Department ...sprenkle/cs209/pre_class/11-streams.pdf• Example: Make an input reader of type InputStreamReader that reads from keyboard Øin reads

10/5/16

5

Oct 5, 2016 Sprenkle - CSCI209 9

ByteStreams

AbstractBaseClasses

Shaded: Read to/write from data sinks White: Does some processing

•  For binary data •  In java.io package

Oct 5, 2016 Sprenkle - CSCI209 10

CharacterStreams

AbstractBaseClasses

Shaded: Read to/write from data sinksWhite: Does some processing

• For Text• In java.io package• Handle any character in

Unicode set

Page 6: STANDARD ERROR - Computer Science Department ...sprenkle/cs209/pre_class/11-streams.pdf• Example: Make an input reader of type InputStreamReader that reads from keyboard Øin reads

10/5/16

6

STREAMS

Oct 5, 2016 Sprenkle - CSCI209 11

Oct 5, 2016 Sprenkle - CSCI209 12

FileInputandOutputStreams• FileInputStream:providesaninputstreamthatcanreadfromafileØ Constructortakesthenameofthefile:

Ø Or,usesaFileobject…

FileInputStream fin = new FileInputStream("chicken.data");

File inputFile = new File("chicken.data");FileInputStream fin = new FileInputStream(inputFile);

FileTest.java

Page 7: STANDARD ERROR - Computer Science Department ...sprenkle/cs209/pre_class/11-streams.pdf• Example: Make an input reader of type InputStreamReader that reads from keyboard Øin reads

10/5/16

7

MorePowerfulStreamObjects• DataInputStream

Ø ReadsJavaprimi&vetypesthroughmethodssuchasreadDouble(), readChar(), readBoolean()

• DataOutputStreamØ WritesJavaprimi&vetypeswithwriteDouble(), writeChar(), …

Oct 5, 2016 Sprenkle - CSCI209 13

ConnectedStreams

• FileInputStreamcanreadfromafilebuthasnomethodstoreadnumerictypes• DataInputStreamcanreadnumerictypesbuthasnomethodstoreadfromafile

• JavaallowsyoutocombinetwotypesofstreamsintoaconnectedstreamØ FileInputStreamàchocolateØ DataInputStreamàpeanutbuPer

Oct 5, 2016 Sprenkle - CSCI209 14

Our goal: read numbers from a file

Page 8: STANDARD ERROR - Computer Science Department ...sprenkle/cs209/pre_class/11-streams.pdf• Example: Make an input reader of type InputStreamReader that reads from keyboard Øin reads

10/5/16

8

Oct 5, 2016 Sprenkle - CSCI209 15

ConnectedStreams

• Thinkofastreamasapipe• FileInputStream knowshowtoreadfromafile• DataInputStreamknowshowtoreadanInputStreamintousefultypes

• ConnectoutendofFileInputStreamtoinendofDataInputStream…

FileInputStream DataInputStreamdouble

charfile

Data Source stream Filtered Stream

Reads from a stream

Oct 5, 2016 Sprenkle - CSCI209 16

Connec&ngStreams•  Ifwewanttoreadnumbersfromafile

Ø FileInputStreamreadsbytesfromfileØ DataInputStreamhandlesnumerictypereading

• ConnecttheDataInputStreamtotheFileInputStreamØ FileInputStreamgetsthebytesfromthefileandDataInputStreamreadsthemasassembledtypes

FileInputStream fin = new FileInputStream(“chicken.data”);

DataInputStream din = new DataInputStream(fin);

double num1 = din.readDouble();“wrap” fin in din

DataIODemo.java

Page 9: STANDARD ERROR - Computer Science Department ...sprenkle/cs209/pre_class/11-streams.pdf• Example: Make an input reader of type InputStreamReader that reads from keyboard Øin reads

10/5/16

9

DataSourcevs.FilteredStreams

FilteredStreams•  Subclasses of FilterInputStream or FilterOutputStream

•  Always contains another stream

•  Adds functionality to other streamØ  Automatically buffered IO Ø  Automatic compressionØ  Automatic encryption Ø  Automatic conversion

between objects and bytes

DataSourceStreams

• Communicate with a data source Ø  file, byte array,

network socket, or URL

Oct 5, 2016 Sprenkle - CSCI209 17

Oct 5, 2016 Sprenkle - CSCI209 18

BufferedStreams• UseaBufferedInputStreamobjecttobufferyourinputstreamsØ ApipeinthechainthataddsbufferingØ SpeedsupaccessDataInputStream din = new DataInputStream ( new BufferedInputStream ( new FileInputStream("chicken.data")));

FileInputStreamdouble

charfile BufferedInputStream

What functionality does each stream add?

DataInputStream

Page 10: STANDARD ERROR - Computer Science Department ...sprenkle/cs209/pre_class/11-streams.pdf• Example: Make an input reader of type InputStreamReader that reads from keyboard Øin reads

10/5/16

10

Oct 5, 2016 Sprenkle - CSCI209 19

ConnectedStreams

• Whatarethetradeoffsforthisdesigndecision?

Combine different types of streamsto get functionality you want

Oct 5, 2016 Sprenkle - CSCI209 20

ConnectedStreams

• Crea&ngaclassforeveryclasswouldresultinevenmoreclassesandalotofredundantcodeØ Considerwhatisrequiredifsomefunc&onalitymustbeupdated

Combine different types of streamsto get functionality you want

Page 11: STANDARD ERROR - Computer Science Department ...sprenkle/cs209/pre_class/11-streams.pdf• Example: Make an input reader of type InputStreamReader that reads from keyboard Øin reads

10/5/16

11

Oct 5, 2016 Sprenkle - CSCI209 21

ConnectedStreams:Output

• SimilarforoutputØ Forbufferedoutputtothefileandtowritetypes• CreateaFileOutputStream• APachaBufferedOutputStream• APachaDataOutputStream• Performtypedwri&ngusingmethodsoftheDataOutputStreamobject

Combine different types of streamsto get functionality you want

TEXTSTREAMS

Oct 5, 2016 Sprenkle - CSCI209 22

Page 12: STANDARD ERROR - Computer Science Department ...sprenkle/cs209/pre_class/11-streams.pdf• Example: Make an input reader of type InputStreamReader that reads from keyboard Øin reads

10/5/16

12

TextStreams• Previousstreams:operateonbinarydata,nottext

• JavausesUnicodetorepresentcharacters/stringsandsomeopera&ngsystemsdonotØ NeedsomethingthatconvertscharactersfromUnicodetowhateverencodingtheunderlyingopera&ngsystemuses

Ø Luckily,thisismostlyhiddenfromyou

Oct 5, 2016 Sprenkle - CSCI209 23

Oct 5, 2016 Sprenkle - CSCI209 24

CharacterStreams

AbstractBaseClasses

Shaded: Read to/write from data sinks White: Does some processing

• For Text • In java.io package • Handle any character

in Unicode set

Page 13: STANDARD ERROR - Computer Science Department ...sprenkle/cs209/pre_class/11-streams.pdf• Example: Make an input reader of type InputStreamReader that reads from keyboard Øin reads

10/5/16

13

TextStreams• DerivedfromReaderandWriterclasses

Ø ReaderandWritergenerallyrefertotextI/O• Example:MakeaninputreaderoftypeInputStreamReader thatreadsfromkeyboard

Ø in readscharactersfromkeyboardandconvertsthemintoUnicodeforJava

Oct 5, 2016 Sprenkle - CSCI209 25

InputStreamReader in = new InputStreamReader(System.in);

Oct 5, 2016 Sprenkle - CSCI209 26

TextStreamsandEncodings• APachanInputStreamReadertoaFileInputStream

Ø AssumesfilehasbeenencodedinthedefaultencodingofunderlyingOS

• YoucanspecifyadifferentencodinginconstructorofInputStreamReader…

InputStreamReader in = new InputStreamReader(new FileInputStream("employee.data"));

InputStreamReader in = new InputStreamReader(new FileInputStream("employee.data"), "UTF-8");

Page 14: STANDARD ERROR - Computer Science Department ...sprenkle/cs209/pre_class/11-streams.pdf• Example: Make an input reader of type InputStreamReader that reads from keyboard Øin reads

10/5/16

14

Oct 5, 2016 Sprenkle - CSCI209 27

ConvenienceClasses• Readingandwri&ngtotextfilesiscommon• FileReader

Ø ConvenienceclasscombinesaInputStreamReaderwithaFileInputStream

• Similarforoutputoftextfile

isequivalenttoFileWriter out = new FileWriter("output.txt");

OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream("output.txt"));

PrintWriter• Useforwri&ngtextoutput

Ø Easiestwritertouse• SimilartoaDataOutputStream, PrintStream à has methods for printing various data types

• Methods: print,printfandprintlnØ SimilartoSystem.out(aPrintStream)todisplaystrings

Oct 5, 2016 Sprenkle - CSCI209 28

Page 15: STANDARD ERROR - Computer Science Department ...sprenkle/cs209/pre_class/11-streams.pdf• Example: Make an input reader of type InputStreamReader that reads from keyboard Øin reads

10/5/16

15

Oct 5, 2016 Sprenkle - CSCI209 29

PrintWriter Example

PrintWriter out = new PrintWriter("output.txt");

String myName = "Homer Simpson";double mySalary = 35700;

out.print(myName);out.print(" makes ");out.print(salary);out.println(" per year.");

orout.println(myName + " makes " + salary +

" per year.");

File to write to

Review:FormaPedOutput• printforformat

Ø PrintStreamnewfunc&onalitysinceJava1.5

Oct 5, 2016 Sprenkle - CSCI209 30

double f1=3.14159, f2=1.45, total=9.43;// simple formatting...System.out.printf("%6.5f and %5.2f", f1, f2);// getting fancy (%n = \n or \r\n)...System.out.printf("%-6s%5.2f%\n", "Tax:", total);

Page 16: STANDARD ERROR - Computer Science Department ...sprenkle/cs209/pre_class/11-streams.pdf• Example: Make an input reader of type InputStreamReader that reads from keyboard Øin reads

10/5/16

16

Oct 5, 2016 Sprenkle - CSCI209 31

PrintWritersandBuffering• PrintWritersarealwaysbuffered• Op&on:autoflushmode

Ø Causesanywritestobeexecuteddirectlyontargetdes&na&on•  Ineffect,defeatsthepurposeofbuffering

Ø Constructorwithsecondparametersettotrue

// create an autoflushing PrintWriterPrintWriter out = new PrintWriter("output.txt",

true);

ReadingTextfromaStream• ThereisnoPrintReaderclass• UseaBufferedReader

Ø ConstructorrequiresaReaderobject

• Readfile,line-by-lineusingreadLine()Ø ReadsinalineoftextandreturnsitasaStringØ Returnsnullwhennomoreinputisavailable

Oct 5, 2016 Sprenkle - CSCI209 32

String line;while ((line = in.readLine()) != null) {

// process the line}

BufferedReader in = new BufferedReader(new FileReader("inputfile.txt"));

Page 17: STANDARD ERROR - Computer Science Department ...sprenkle/cs209/pre_class/11-streams.pdf• Example: Make an input reader of type InputStreamReader that reads from keyboard Øin reads

10/5/16

17

Oct 5, 2016 Sprenkle - CSCI209 33

ReadingTextfromaStream• YoucanalsoaPachaBufferedReadertoanInputStreamReader:

• Usedtobethebestwaytoreadfromtheconsole

BufferedReader consoleReader= new BufferedReader(new InputStreamReader(System.in));

BufferedReader webpageReader = new BufferedReader( new InputStreamReader(url.openStream());

Note how easy it is to read �from different sources