SlideShare a Scribd company logo
1 © 2001-2003 Marty Hall, Larry Brown http://www.corewebprogramming.com
core
programming
Java Input/Output
Input/Output2 www.corewebprogramming.com
Agenda
• Handling files and directories through the
File class
• Understanding which streams to use for
character-based or byte-based streams
• Character File input and output
• Formatting output
• Reading data from the console
• Binary File input and output
Input/Output3 www.corewebprogramming.com
File Class
• A File object can refer to either a file or a
directory
File file1 = new File("data.txt");
File file1 = new File("C:java");
– To obtain the path to the current working directory use
System.getProperty("user.dir");
– To obtain the file or path separator use
System.getProperty("file.separator");
System.getProperty("path.separator");
or
File.separator()
File.pathSeparator()
Input/Output4 www.corewebprogramming.com
Useful File Methods
• isFile/isDirectory
• canRead/canWrite
• length
– Length of the file in bytes (long) or 0 if nonexistant
• list
– If the File object is a directory, returns a String array of all the
files and directories contained in the directory; otherwise, null
• mkdir
– Creates a new subdirectory
• delete
– Deletes the directory and returns true if successful
• toURL
– Converts the file path to a URL object
Input/Output5 www.corewebprogramming.com
Directory Listing, Example
import java.io.*;
public class DirListing {
public static void main(String[] args) {
File dir = new File(System.getProperty("user.dir"));
if(dir.isDirectory()){
System.out.println("Directory of " + dir);
String[] listing = dir.list();
for(int i=0; i<listing.length; i++) {
System.out.println("t" + listing[i]);
}
}
}
}
Input/Output6 www.corewebprogramming.com
DirectoryListing, Result
> java DirListing
Directory of C:java
DirListing.class
DirListing.java
test
TryCatchExample.class
TryCatchExample.java
XslTransformer.class
XslTransformer.java
Input/Output7 www.corewebprogramming.com
Input/Output
• The java.io package provides over 60
input/output classes (streams)
• Streams are combined (piped together) to
create a desired data source or sink
• Streams are either byte-oriented or
character-oriented
– Use DataStreams for byte-oriented I/O
– Use Readers and Writers for character-based I/O
• Character I/O uses an encoding scheme
• Note: An IOException may occur during
any I/O operation
Input/Output8 www.corewebprogramming.com
Character File Output
Desired … Methods Construction
Character File Ouput FileWriter File file = new File("filename");
write(int char) FileWriter fout = new FileWriter(file);
write(byte[] buffer) or
write(String str) FileWriter fout = new FileWriter("filename");
Buffered Character BufferedWriter File file = new File("filename");
File Output write(int char) FileWriter fout = new FileWriter(file);
write(char[] buffer) BufferedWriter bout = new BufferedWriter(fout);
write(String str) or
newLine() BufferedWriter bout = new BufferedWriter(
new FileWriter(
new File("filename")));
Input/Output9 www.corewebprogramming.com
Character File Output, cont.
Desired … Methods Construction
Character Output PrintWriter FileWriter fout = new FileWriter("filename");
write(int char) PrintWriter pout = new PrintWriter(fout);
write(char[] buffer) or
writer(String str) PrintWriter pout = new PrintWriter(
print( … ) new FileWriter("filename"));
println( … ) or
PrintWriter pout = new PrintWriter(
new BufferedWriter(
new FileWriter("filename")));
Input/Output10 www.corewebprogramming.com
FileWriter
• Constructors
– FileWriter(String filename)/FileWriter(File file)
• Creates a output stream using the default encoding
– FileWriter(String filename, boolean append)
• Creates a new output stream or appends to the existing output
stream (append = true)
• Useful Methods
– write(String str)/write(char[] buffer)
• Writes string or array of chars to the file
– write(int char)
• Writes a character (int) to the file
– flush
• Writes any buffered characters to the file
– close
• Closes the file stream after performing a flush
– getEncoding
• Returns the character encoding used by the file stream
Input/Output11 www.corewebprogramming.com
CharacterFileOutput, Example
import java.io.*;
public class CharacterFileOutput {
public static void main(String[] args) {
FileWriter out = null;
try {
out = new FileWriter("book.txt");
System.out.println("Encoding: " + out.getEncoding());
out.write("Core Web Programming");
out.close();
out = null;
} catch(IOException ioe) {
System.out.println("IO problem: " + ioe);
ioe.printStackTrace();
try {
if (out != null) {
out.close();
}
} catch(IOException ioe2) { }
}
}
}
Input/Output12 www.corewebprogramming.com
CharacterFileOutput, Result
> java CharacterFileOutput
Encoding: Cp1252
> type book.txt
Core Web Programming
• Note: Cp1252 is Windows Western Europe / Latin-1
– To change the system default encoding use
System.setProperty("file.encoding", "encoding");
– To specify the encoding when creating the output steam, use an
OutputStreamWriter
OutputStreamWriter out =
new OutputStreamWriter(
new FileOutputStream("book.txt", "8859_1"));
Input/Output13 www.corewebprogramming.com
Formatting Output
• Use DecimalFormat to control spacing
and formatting
– Java has no printf method
• Approach
1. Create a DecimalFormat object describing the
formatting
DecimalFormat formatter =
new DecimalFormat("#,###.##");
2. Then use the format method to convert values into
formatted strings
formatter.format(24.99);
Input/Output14 www.corewebprogramming.com
Formatting Characters
Symbol Meaning
0 Placeholder for a digit.
# Placeholder for a digit.
If the digit is leading or trailing zero, then don't display.
. Location of decimal point.
, Display comma at this location.
- Minus sign.
E Scientific notation.
Indicates the location to separate the mattissa from the exponent.
% Multipy the value by 100 and display as a percent.
Input/Output15 www.corewebprogramming.com
NumFormat, Example
import java.text.*;
public class NumFormat {
public static void main (String[] args) {
DecimalFormat science = new DecimalFormat("0.000E0");
DecimalFormat plain = new DecimalFormat("0.0000");
for(double d=100.0; d<140.0; d*=1.10) {
System.out.println("Scientific: " + science.format(d) +
" and Plain: " + plain.format(d));
}
}
}
Input/Output16 www.corewebprogramming.com
NumFormat, Result
> java NumFormat
Scientific: 1.000E2 and Plain: 100.0000
Scientific: 1.100E2 and Plain: 110.0000
Scientific: 1.210E2 and Plain: 121.0000
Scientific: 1.331E2 and Plain: 133.1000
Input/Output17 www.corewebprogramming.com
Character File Input
Desired … Methods Construction
Character File Input FileReader File file = new File("filename");
read() FileReader fin = new FileReader(file);
read(char[] buffer) or
FileReader fin = new FileReader("filename");
Buffered Character BufferedReader File file = new File("filename");
File Input read() FileReader fin = new FileReader(file);
read(char[] buffer) BufferedReader bin = new BufferedReader(fin);
readLine() or
BufferedReader bin = new BufferedReader(
new FileReader(
new File("filename")));
Input/Output18 www.corewebprogramming.com
FileReader
• Constructors
– FileReader(String filename)/FileReader(File file)
• Creates a input stream using the default encoding
• Useful Methods
– read/read(char[] buffer)
• Reads a single character or array of characters
• Returns –1 if the end of the steam is reached
– reset
• Moves to beginning of stream (file)
– skip
• Advances the number of characters
• Note: Wrap a BufferedReader around the FileReader to
read full lines of text using readLine
Input/Output19 www.corewebprogramming.com
CharacterFileInput, Example
import java.io.*;
public class CharacterFileInput {
public static void main(String[] args) {
File file = new File("book.txt");
FileReader in = null;
if(file.exists()) {
try {
in = new FileReader(file);
System.out.println("Encoding: " + in.getEncoding());
char[] buffer = new char[(int)file.length()];
in.read(buffer);
System.out.println(buffer);
in.close();
} catch(IOException ioe) {
System.out.println("IO problem: " + ioe);
ioe.printStackTrace();
...
}
}
}
}
Input/Output20 www.corewebprogramming.com
CharacterFileInput, Result
> java CharacterFileInput
Encoding: Cp1252
Core Web Programming
• Alternatively, could read file one line at a time:
BufferedReader in =
new BufferedReader(new FileReader(file));
String lineIn;
while ((lineIn = in.readLine()) != null) {
System.out.println(lineIn);
}
Input/Output21 www.corewebprogramming.com
Console Input
• To read input from the console, a stream
must be associated with the standard input,
System.in
import java.io.*;
public class IOInput{
public static void main(String[] args) {
BufferedReader keyboard;
String line;
try {
System.out.print("Enter value: ");
System.out.flush();
keyboard = new BufferedReader(
new InputStreamReader(System.in));
line = keyboard.readLine();
} catch(IOException e) {
System.out.println("Error reading input!"); }
}
}
}
Input/Output22 www.corewebprogramming.com
Binary File Input and Output
• Handle byte-based I/O using a
DataInputStream or DataOutputStream
– The readFully method blocks until all bytes are read or an EOF occurs
– Values are written in big-endian fashion regardless of computer platform
DataType DataInputStream DataOutputStream
byte readByte writeByte
short readShort writeShort
int readInt writeInt
long readLong writeLong
float readFloat writeFloat
double readDouble writeDouble
boolean readBoolean writeBoolean
char readChar writeChar
String readUTF writeUTF
byte[] readFully
Input/Output23 www.corewebprogramming.com
UCS Transformation Format –
UTF-8
• UTF encoding represents a 2-byte Unicode
character in 1-3 bytes
– Benefit of backward compatibility with existing ASCII
data (one-byte over two-byte Unicode)
– Disadvantage of different byte sizes for character
representation
UTF Encoding
Bit Pattern Representation
0xxxxxxx ASCII (0x0000 - 0x007F)
10xxxxxx Second or third byte
110xxxxx First byte in a 2-byte sequence (0x0080 - 0x07FF)
1110xxxx First byte in a 3-byte sequence (0x0800 - 0xFFFF)
Input/Output24 www.corewebprogramming.com
Binary File Output
Desired … Methods Construction
Binary File Output FileOutputStream File file = new File("filename");
bytes write(byte) FileOutputStream fout = new FileOutputStream(file);
write(byte[] buffer) or
FileOutputStream fout = new FileOutputStream("filename");
Binary File Output DataOutputStream File file = new File("filename");
byte writeByte(byte) FileOutputStream fout = new FileOutputStream(file);
short writeShort(short) DataOutputStream dout = new DataOutputStream(fout);
int writeInt(int)
long writeLong(long) or
float writeFloat(float)
double writeDouble(double) DataOutputStream dout = new DataOutputStream(
char writechar(char) new FileOutputStream(
boolean writeBoolean(boolean) new File("filename")));
writeUTF(string)
writeBytes(string)
writeChars(string)
Input/Output25 www.corewebprogramming.com
Binary File Output, cont.
Desired … Methods Construction
Buffered Binary BufferedOutputStream File file = new File("filename");
File Output flush() FileOutputStream fout = new FileOutputStream(file);
write(byte) BufferedOutputStream bout = new BufferedOutputStream(fout);
write(byte[] buffer, int off, int len) DataOutputStream dout = new DataOutputStream(bout);
or
DataOutputStream dout = new DataOutputStream(
new BufferedOutputStream(
new FileOutputStream(
new File("filename"))));
Input/Output26 www.corewebprogramming.com
BinaryFileOutput, Example
import java.io.*;
public class BinaryFileOutput {
public static void main(String[] args) {
int[] primes = { 1, 2, 3, 5, 11, 17, 19, 23 };
DataOutputStream out = null;
try {
out = new DataOutputStream(
new FileOutputStream("primes.bin"));
for(int i=0; i<primes.length; i++) {
out.writeInt(primes[i]);
}
out.close();
} catch(IOException ioe) {
System.out.println("IO problem: " + ioe);
ioe.printStackTrace();
}
}
}
Input/Output27 www.corewebprogramming.com
Binary File Input
Desired … Methods Construction
Binary File Input FileInputStream File file = new File("filename");
bytes read() FileInputStream fin = new FileInputStream(file);
read(byte[] buffer) or
FileInputStream fin = new FileInputStream("filename");
Binary File Input DataInputStream File file = new File("filename");
byte readByte() FileInputStream fin = new FileInputStream(file);
short readShort() DataInputStream din = new DataInputStream(fin);
int readInt()
long readLong() or
float readFloat()
double readDouble() DataInputStream din = new DataInputStream(
char readchar() new FileInputStream(
boolean readBoolean() new File("filename")));
readUTF()
readFully(byte[] buffer)
Input/Output28 www.corewebprogramming.com
Binary File Input, cont.
Desired … Methods Construction
Bufferred Binary BufferedInputStream File file = new File("filename");
File Input read() FileInputStream fin = new FileInputStream(file);
read(byte[] buffer, int off, int len) BufferedInputStream bin = new BufferedInputStream(fin);
skip(long) DataInputStream din = new DataInputStream(bin);
or
DataInputStream din = new DataInputStream(
new BufferedInputStream(
new FileInputStream(
new File("filename"))));
Input/Output29 www.corewebprogramming.com
BinaryFileInput, Example
import java.io.*;
public class BinaryFileInput {
public static void main(String[] args) {
DataInputStream in = null;
File file = new File("primes.bin");
try {
in = new DataInputStream(
new FileInputStream(file));
int prime;
long size = file.length()/4; // 4 bytes per int
for(long i=0; i<size; i++) {
prime = in.readInt();
System.out.println(prime);
}
in.close();
} catch(IOException ioe) {
System.out.println("IO problem: " + ioe);
ioe.printStackTrace();
}
}
}
Input/Output30 www.corewebprogramming.com
Summary
• A File can refer to either a file or a
directory
• Use Readers and Writers for character-
based I/O
– A BufferedReader is required for readLine
– Java provides no printf; use DecimalFormat for formatted
output
• Use DataStreams for byte-based I/O
– Chain a FileOutputStream to a DataOutputStream for
binary file output
– Chain a FileInputStream to a DataInputStream for binary
file input
31 © 2001-2003 Marty Hall, Larry Brown http://www.corewebprogramming.com
core
programming
Questions?

More Related Content

What's hot

file handling c++
file handling c++file handling c++
file handling c++Guddu Spy
 
Files in php
Files in phpFiles in php
Files in php
sana mateen
 
File in c
File in cFile in c
File in c
Prabhu Govind
 
I/O in java Part 1
I/O in java Part 1I/O in java Part 1
I/O in java Part 1
ashishspace
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
Vikram Nandini
 
File handling-c
File handling-cFile handling-c
Cs1123 10 file operations
Cs1123 10 file operationsCs1123 10 file operations
Cs1123 10 file operationsTAlha MAlik
 
Understanding c file handling functions with examples
Understanding c file handling functions with examplesUnderstanding c file handling functions with examples
Understanding c file handling functions with examplesMuhammed Thanveer M
 
Module 03 File Handling in C
Module 03 File Handling in CModule 03 File Handling in C
Module 03 File Handling in C
Tushar B Kute
 
File handling in C by Faixan
File handling in C by FaixanFile handling in C by Faixan
File handling in C by Faixan
ٖFaiXy :)
 
File handling in 'C'
File handling in 'C'File handling in 'C'
File handling in 'C'
Gaurav Garg
 
Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output Concepts
Victer Paul
 
File in C Programming
File in C ProgrammingFile in C Programming
File in C Programming
Sonya Akter Rupa
 
Files in C
Files in CFiles in C
Files in C
Prabu U
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handlingpinkpreet_kaur
 
Python-files
Python-filesPython-files
Python-files
Krishna Nanda
 
C programming file handling
C  programming file handlingC  programming file handling
C programming file handling
argusacademy
 

What's hot (20)

file handling c++
file handling c++file handling c++
file handling c++
 
Files in php
Files in phpFiles in php
Files in php
 
File in c
File in cFile in c
File in c
 
I/O in java Part 1
I/O in java Part 1I/O in java Part 1
I/O in java Part 1
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
 
File handling in c
File handling in cFile handling in c
File handling in c
 
File handling-c
File handling-cFile handling-c
File handling-c
 
Cs1123 10 file operations
Cs1123 10 file operationsCs1123 10 file operations
Cs1123 10 file operations
 
Understanding c file handling functions with examples
Understanding c file handling functions with examplesUnderstanding c file handling functions with examples
Understanding c file handling functions with examples
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
 
File operations in c
File operations in cFile operations in c
File operations in c
 
Module 03 File Handling in C
Module 03 File Handling in CModule 03 File Handling in C
Module 03 File Handling in C
 
File handling in C by Faixan
File handling in C by FaixanFile handling in C by Faixan
File handling in C by Faixan
 
File handling in 'C'
File handling in 'C'File handling in 'C'
File handling in 'C'
 
Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output Concepts
 
File in C Programming
File in C ProgrammingFile in C Programming
File in C Programming
 
Files in C
Files in CFiles in C
Files in C
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
 
Python-files
Python-filesPython-files
Python-files
 
C programming file handling
C  programming file handlingC  programming file handling
C programming file handling
 

Similar to 5java Io

Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
Hamid Ghorbani
 
Files and streams In Java
Files and streams In JavaFiles and streams In Java
Files and streams In Java
Rajan Shah
 
Files in c++
Files in c++Files in c++
Files in c++
Selvin Josy Bai Somu
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
Sunil OS
 
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/OCore Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
WebStackAcademy
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streamsShahjahan Samoon
 
Jedi Slides Intro2 Chapter12 Advanced Io Streams
Jedi Slides Intro2 Chapter12 Advanced Io StreamsJedi Slides Intro2 Chapter12 Advanced Io Streams
Jedi Slides Intro2 Chapter12 Advanced Io StreamsDon Bosco BSIT
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
Kavitha713564
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdf
SudhanshiBakre1
 
Java - Processing input and output
Java - Processing input and outputJava - Processing input and output
Java - Processing input and output
Riccardo Cardin
 
Java căn bản - Chapter12
Java căn bản - Chapter12Java căn bản - Chapter12
Java căn bản - Chapter12Vince Vo
 
Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and Output
Eduardo Bergavera
 
Session 22 - Java IO, Serialization
Session 22 - Java IO, SerializationSession 22 - Java IO, Serialization
Session 22 - Java IO, Serialization
PawanMM
 
Java IO, Serialization
Java IO, Serialization Java IO, Serialization
Java IO, Serialization
Hitesh-Java
 
Files in C++.pdf is the notes of cpp for reference
Files in C++.pdf is the notes of cpp for referenceFiles in C++.pdf is the notes of cpp for reference
Files in C++.pdf is the notes of cpp for reference
anuvayalil5525
 
Java I/O
Java I/OJava I/O
Java I/O
Jayant Dalvi
 
Chapter 10.3
Chapter 10.3Chapter 10.3
Chapter 10.3sotlsoc
 

Similar to 5java Io (20)

Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Files and streams In Java
Files and streams In JavaFiles and streams In Java
Files and streams In Java
 
Files in c++
Files in c++Files in c++
Files in c++
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
 
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/OCore Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
 
Jedi Slides Intro2 Chapter12 Advanced Io Streams
Jedi Slides Intro2 Chapter12 Advanced Io StreamsJedi Slides Intro2 Chapter12 Advanced Io Streams
Jedi Slides Intro2 Chapter12 Advanced Io Streams
 
Java I/O
Java I/OJava I/O
Java I/O
 
Java Day-6
Java Day-6Java Day-6
Java Day-6
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdf
 
Java - Processing input and output
Java - Processing input and outputJava - Processing input and output
Java - Processing input and output
 
26 io -ii file handling
26  io -ii  file handling26  io -ii  file handling
26 io -ii file handling
 
Java căn bản - Chapter12
Java căn bản - Chapter12Java căn bản - Chapter12
Java căn bản - Chapter12
 
Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and Output
 
Session 22 - Java IO, Serialization
Session 22 - Java IO, SerializationSession 22 - Java IO, Serialization
Session 22 - Java IO, Serialization
 
Java IO, Serialization
Java IO, Serialization Java IO, Serialization
Java IO, Serialization
 
Files in C++.pdf is the notes of cpp for reference
Files in C++.pdf is the notes of cpp for referenceFiles in C++.pdf is the notes of cpp for reference
Files in C++.pdf is the notes of cpp for reference
 
Java I/O
Java I/OJava I/O
Java I/O
 
Chapter 10.3
Chapter 10.3Chapter 10.3
Chapter 10.3
 

More from Adil Jafri

Csajsp Chapter5
Csajsp Chapter5Csajsp Chapter5
Csajsp Chapter5Adil Jafri
 
Programming Asp Net Bible
Programming Asp Net BibleProgramming Asp Net Bible
Programming Asp Net BibleAdil Jafri
 
Network Programming Clients
Network Programming ClientsNetwork Programming Clients
Network Programming ClientsAdil Jafri
 
Ta Javaserverside Eran Toch
Ta Javaserverside Eran TochTa Javaserverside Eran Toch
Ta Javaserverside Eran TochAdil Jafri
 
Csajsp Chapter10
Csajsp Chapter10Csajsp Chapter10
Csajsp Chapter10Adil Jafri
 
Flashmx Tutorials
Flashmx TutorialsFlashmx Tutorials
Flashmx TutorialsAdil Jafri
 
Java For The Web With Servlets%2cjsp%2cand Ejb
Java For The Web With Servlets%2cjsp%2cand EjbJava For The Web With Servlets%2cjsp%2cand Ejb
Java For The Web With Servlets%2cjsp%2cand EjbAdil Jafri
 
Csajsp Chapter12
Csajsp Chapter12Csajsp Chapter12
Csajsp Chapter12Adil Jafri
 
Flash Tutorial
Flash TutorialFlash Tutorial
Flash TutorialAdil Jafri
 

More from Adil Jafri (20)

Csajsp Chapter5
Csajsp Chapter5Csajsp Chapter5
Csajsp Chapter5
 
Php How To
Php How ToPhp How To
Php How To
 
Php How To
Php How ToPhp How To
Php How To
 
Owl Clock
Owl ClockOwl Clock
Owl Clock
 
Phpcodebook
PhpcodebookPhpcodebook
Phpcodebook
 
Phpcodebook
PhpcodebookPhpcodebook
Phpcodebook
 
Programming Asp Net Bible
Programming Asp Net BibleProgramming Asp Net Bible
Programming Asp Net Bible
 
Tcpip Intro
Tcpip IntroTcpip Intro
Tcpip Intro
 
Network Programming Clients
Network Programming ClientsNetwork Programming Clients
Network Programming Clients
 
Jsp Tutorial
Jsp TutorialJsp Tutorial
Jsp Tutorial
 
Ta Javaserverside Eran Toch
Ta Javaserverside Eran TochTa Javaserverside Eran Toch
Ta Javaserverside Eran Toch
 
Csajsp Chapter10
Csajsp Chapter10Csajsp Chapter10
Csajsp Chapter10
 
Javascript
JavascriptJavascript
Javascript
 
Flashmx Tutorials
Flashmx TutorialsFlashmx Tutorials
Flashmx Tutorials
 
Java For The Web With Servlets%2cjsp%2cand Ejb
Java For The Web With Servlets%2cjsp%2cand EjbJava For The Web With Servlets%2cjsp%2cand Ejb
Java For The Web With Servlets%2cjsp%2cand Ejb
 
Html Css
Html CssHtml Css
Html Css
 
Digwc
DigwcDigwc
Digwc
 
Csajsp Chapter12
Csajsp Chapter12Csajsp Chapter12
Csajsp Chapter12
 
Html Frames
Html FramesHtml Frames
Html Frames
 
Flash Tutorial
Flash TutorialFlash Tutorial
Flash Tutorial
 

Recently uploaded

Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
UiPathCommunity
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
Vlad Stirbu
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
Peter Spielvogel
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
RinaMondal9
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 

Recently uploaded (20)

Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 

5java Io

  • 1. 1 © 2001-2003 Marty Hall, Larry Brown http://www.corewebprogramming.com core programming Java Input/Output
  • 2. Input/Output2 www.corewebprogramming.com Agenda • Handling files and directories through the File class • Understanding which streams to use for character-based or byte-based streams • Character File input and output • Formatting output • Reading data from the console • Binary File input and output
  • 3. Input/Output3 www.corewebprogramming.com File Class • A File object can refer to either a file or a directory File file1 = new File("data.txt"); File file1 = new File("C:java"); – To obtain the path to the current working directory use System.getProperty("user.dir"); – To obtain the file or path separator use System.getProperty("file.separator"); System.getProperty("path.separator"); or File.separator() File.pathSeparator()
  • 4. Input/Output4 www.corewebprogramming.com Useful File Methods • isFile/isDirectory • canRead/canWrite • length – Length of the file in bytes (long) or 0 if nonexistant • list – If the File object is a directory, returns a String array of all the files and directories contained in the directory; otherwise, null • mkdir – Creates a new subdirectory • delete – Deletes the directory and returns true if successful • toURL – Converts the file path to a URL object
  • 5. Input/Output5 www.corewebprogramming.com Directory Listing, Example import java.io.*; public class DirListing { public static void main(String[] args) { File dir = new File(System.getProperty("user.dir")); if(dir.isDirectory()){ System.out.println("Directory of " + dir); String[] listing = dir.list(); for(int i=0; i<listing.length; i++) { System.out.println("t" + listing[i]); } } } }
  • 6. Input/Output6 www.corewebprogramming.com DirectoryListing, Result > java DirListing Directory of C:java DirListing.class DirListing.java test TryCatchExample.class TryCatchExample.java XslTransformer.class XslTransformer.java
  • 7. Input/Output7 www.corewebprogramming.com Input/Output • The java.io package provides over 60 input/output classes (streams) • Streams are combined (piped together) to create a desired data source or sink • Streams are either byte-oriented or character-oriented – Use DataStreams for byte-oriented I/O – Use Readers and Writers for character-based I/O • Character I/O uses an encoding scheme • Note: An IOException may occur during any I/O operation
  • 8. Input/Output8 www.corewebprogramming.com Character File Output Desired … Methods Construction Character File Ouput FileWriter File file = new File("filename"); write(int char) FileWriter fout = new FileWriter(file); write(byte[] buffer) or write(String str) FileWriter fout = new FileWriter("filename"); Buffered Character BufferedWriter File file = new File("filename"); File Output write(int char) FileWriter fout = new FileWriter(file); write(char[] buffer) BufferedWriter bout = new BufferedWriter(fout); write(String str) or newLine() BufferedWriter bout = new BufferedWriter( new FileWriter( new File("filename")));
  • 9. Input/Output9 www.corewebprogramming.com Character File Output, cont. Desired … Methods Construction Character Output PrintWriter FileWriter fout = new FileWriter("filename"); write(int char) PrintWriter pout = new PrintWriter(fout); write(char[] buffer) or writer(String str) PrintWriter pout = new PrintWriter( print( … ) new FileWriter("filename")); println( … ) or PrintWriter pout = new PrintWriter( new BufferedWriter( new FileWriter("filename")));
  • 10. Input/Output10 www.corewebprogramming.com FileWriter • Constructors – FileWriter(String filename)/FileWriter(File file) • Creates a output stream using the default encoding – FileWriter(String filename, boolean append) • Creates a new output stream or appends to the existing output stream (append = true) • Useful Methods – write(String str)/write(char[] buffer) • Writes string or array of chars to the file – write(int char) • Writes a character (int) to the file – flush • Writes any buffered characters to the file – close • Closes the file stream after performing a flush – getEncoding • Returns the character encoding used by the file stream
  • 11. Input/Output11 www.corewebprogramming.com CharacterFileOutput, Example import java.io.*; public class CharacterFileOutput { public static void main(String[] args) { FileWriter out = null; try { out = new FileWriter("book.txt"); System.out.println("Encoding: " + out.getEncoding()); out.write("Core Web Programming"); out.close(); out = null; } catch(IOException ioe) { System.out.println("IO problem: " + ioe); ioe.printStackTrace(); try { if (out != null) { out.close(); } } catch(IOException ioe2) { } } } }
  • 12. Input/Output12 www.corewebprogramming.com CharacterFileOutput, Result > java CharacterFileOutput Encoding: Cp1252 > type book.txt Core Web Programming • Note: Cp1252 is Windows Western Europe / Latin-1 – To change the system default encoding use System.setProperty("file.encoding", "encoding"); – To specify the encoding when creating the output steam, use an OutputStreamWriter OutputStreamWriter out = new OutputStreamWriter( new FileOutputStream("book.txt", "8859_1"));
  • 13. Input/Output13 www.corewebprogramming.com Formatting Output • Use DecimalFormat to control spacing and formatting – Java has no printf method • Approach 1. Create a DecimalFormat object describing the formatting DecimalFormat formatter = new DecimalFormat("#,###.##"); 2. Then use the format method to convert values into formatted strings formatter.format(24.99);
  • 14. Input/Output14 www.corewebprogramming.com Formatting Characters Symbol Meaning 0 Placeholder for a digit. # Placeholder for a digit. If the digit is leading or trailing zero, then don't display. . Location of decimal point. , Display comma at this location. - Minus sign. E Scientific notation. Indicates the location to separate the mattissa from the exponent. % Multipy the value by 100 and display as a percent.
  • 15. Input/Output15 www.corewebprogramming.com NumFormat, Example import java.text.*; public class NumFormat { public static void main (String[] args) { DecimalFormat science = new DecimalFormat("0.000E0"); DecimalFormat plain = new DecimalFormat("0.0000"); for(double d=100.0; d<140.0; d*=1.10) { System.out.println("Scientific: " + science.format(d) + " and Plain: " + plain.format(d)); } } }
  • 16. Input/Output16 www.corewebprogramming.com NumFormat, Result > java NumFormat Scientific: 1.000E2 and Plain: 100.0000 Scientific: 1.100E2 and Plain: 110.0000 Scientific: 1.210E2 and Plain: 121.0000 Scientific: 1.331E2 and Plain: 133.1000
  • 17. Input/Output17 www.corewebprogramming.com Character File Input Desired … Methods Construction Character File Input FileReader File file = new File("filename"); read() FileReader fin = new FileReader(file); read(char[] buffer) or FileReader fin = new FileReader("filename"); Buffered Character BufferedReader File file = new File("filename"); File Input read() FileReader fin = new FileReader(file); read(char[] buffer) BufferedReader bin = new BufferedReader(fin); readLine() or BufferedReader bin = new BufferedReader( new FileReader( new File("filename")));
  • 18. Input/Output18 www.corewebprogramming.com FileReader • Constructors – FileReader(String filename)/FileReader(File file) • Creates a input stream using the default encoding • Useful Methods – read/read(char[] buffer) • Reads a single character or array of characters • Returns –1 if the end of the steam is reached – reset • Moves to beginning of stream (file) – skip • Advances the number of characters • Note: Wrap a BufferedReader around the FileReader to read full lines of text using readLine
  • 19. Input/Output19 www.corewebprogramming.com CharacterFileInput, Example import java.io.*; public class CharacterFileInput { public static void main(String[] args) { File file = new File("book.txt"); FileReader in = null; if(file.exists()) { try { in = new FileReader(file); System.out.println("Encoding: " + in.getEncoding()); char[] buffer = new char[(int)file.length()]; in.read(buffer); System.out.println(buffer); in.close(); } catch(IOException ioe) { System.out.println("IO problem: " + ioe); ioe.printStackTrace(); ... } } } }
  • 20. Input/Output20 www.corewebprogramming.com CharacterFileInput, Result > java CharacterFileInput Encoding: Cp1252 Core Web Programming • Alternatively, could read file one line at a time: BufferedReader in = new BufferedReader(new FileReader(file)); String lineIn; while ((lineIn = in.readLine()) != null) { System.out.println(lineIn); }
  • 21. Input/Output21 www.corewebprogramming.com Console Input • To read input from the console, a stream must be associated with the standard input, System.in import java.io.*; public class IOInput{ public static void main(String[] args) { BufferedReader keyboard; String line; try { System.out.print("Enter value: "); System.out.flush(); keyboard = new BufferedReader( new InputStreamReader(System.in)); line = keyboard.readLine(); } catch(IOException e) { System.out.println("Error reading input!"); } } } }
  • 22. Input/Output22 www.corewebprogramming.com Binary File Input and Output • Handle byte-based I/O using a DataInputStream or DataOutputStream – The readFully method blocks until all bytes are read or an EOF occurs – Values are written in big-endian fashion regardless of computer platform DataType DataInputStream DataOutputStream byte readByte writeByte short readShort writeShort int readInt writeInt long readLong writeLong float readFloat writeFloat double readDouble writeDouble boolean readBoolean writeBoolean char readChar writeChar String readUTF writeUTF byte[] readFully
  • 23. Input/Output23 www.corewebprogramming.com UCS Transformation Format – UTF-8 • UTF encoding represents a 2-byte Unicode character in 1-3 bytes – Benefit of backward compatibility with existing ASCII data (one-byte over two-byte Unicode) – Disadvantage of different byte sizes for character representation UTF Encoding Bit Pattern Representation 0xxxxxxx ASCII (0x0000 - 0x007F) 10xxxxxx Second or third byte 110xxxxx First byte in a 2-byte sequence (0x0080 - 0x07FF) 1110xxxx First byte in a 3-byte sequence (0x0800 - 0xFFFF)
  • 24. Input/Output24 www.corewebprogramming.com Binary File Output Desired … Methods Construction Binary File Output FileOutputStream File file = new File("filename"); bytes write(byte) FileOutputStream fout = new FileOutputStream(file); write(byte[] buffer) or FileOutputStream fout = new FileOutputStream("filename"); Binary File Output DataOutputStream File file = new File("filename"); byte writeByte(byte) FileOutputStream fout = new FileOutputStream(file); short writeShort(short) DataOutputStream dout = new DataOutputStream(fout); int writeInt(int) long writeLong(long) or float writeFloat(float) double writeDouble(double) DataOutputStream dout = new DataOutputStream( char writechar(char) new FileOutputStream( boolean writeBoolean(boolean) new File("filename"))); writeUTF(string) writeBytes(string) writeChars(string)
  • 25. Input/Output25 www.corewebprogramming.com Binary File Output, cont. Desired … Methods Construction Buffered Binary BufferedOutputStream File file = new File("filename"); File Output flush() FileOutputStream fout = new FileOutputStream(file); write(byte) BufferedOutputStream bout = new BufferedOutputStream(fout); write(byte[] buffer, int off, int len) DataOutputStream dout = new DataOutputStream(bout); or DataOutputStream dout = new DataOutputStream( new BufferedOutputStream( new FileOutputStream( new File("filename"))));
  • 26. Input/Output26 www.corewebprogramming.com BinaryFileOutput, Example import java.io.*; public class BinaryFileOutput { public static void main(String[] args) { int[] primes = { 1, 2, 3, 5, 11, 17, 19, 23 }; DataOutputStream out = null; try { out = new DataOutputStream( new FileOutputStream("primes.bin")); for(int i=0; i<primes.length; i++) { out.writeInt(primes[i]); } out.close(); } catch(IOException ioe) { System.out.println("IO problem: " + ioe); ioe.printStackTrace(); } } }
  • 27. Input/Output27 www.corewebprogramming.com Binary File Input Desired … Methods Construction Binary File Input FileInputStream File file = new File("filename"); bytes read() FileInputStream fin = new FileInputStream(file); read(byte[] buffer) or FileInputStream fin = new FileInputStream("filename"); Binary File Input DataInputStream File file = new File("filename"); byte readByte() FileInputStream fin = new FileInputStream(file); short readShort() DataInputStream din = new DataInputStream(fin); int readInt() long readLong() or float readFloat() double readDouble() DataInputStream din = new DataInputStream( char readchar() new FileInputStream( boolean readBoolean() new File("filename"))); readUTF() readFully(byte[] buffer)
  • 28. Input/Output28 www.corewebprogramming.com Binary File Input, cont. Desired … Methods Construction Bufferred Binary BufferedInputStream File file = new File("filename"); File Input read() FileInputStream fin = new FileInputStream(file); read(byte[] buffer, int off, int len) BufferedInputStream bin = new BufferedInputStream(fin); skip(long) DataInputStream din = new DataInputStream(bin); or DataInputStream din = new DataInputStream( new BufferedInputStream( new FileInputStream( new File("filename"))));
  • 29. Input/Output29 www.corewebprogramming.com BinaryFileInput, Example import java.io.*; public class BinaryFileInput { public static void main(String[] args) { DataInputStream in = null; File file = new File("primes.bin"); try { in = new DataInputStream( new FileInputStream(file)); int prime; long size = file.length()/4; // 4 bytes per int for(long i=0; i<size; i++) { prime = in.readInt(); System.out.println(prime); } in.close(); } catch(IOException ioe) { System.out.println("IO problem: " + ioe); ioe.printStackTrace(); } } }
  • 30. Input/Output30 www.corewebprogramming.com Summary • A File can refer to either a file or a directory • Use Readers and Writers for character- based I/O – A BufferedReader is required for readLine – Java provides no printf; use DecimalFormat for formatted output • Use DataStreams for byte-based I/O – Chain a FileOutputStream to a DataOutputStream for binary file output – Chain a FileInputStream to a DataInputStream for binary file input
  • 31. 31 © 2001-2003 Marty Hall, Larry Brown http://www.corewebprogramming.com core programming Questions?