Title: Some Simple I/O Examples
1Week One
Some Simple I/O Examples
2// copy a binary or text file import
java.io. public class CopyBytes public static
void main( String args) throws IOException
DataInputStream in
new DataInputStream( new
BufferedInputStream(
new FileInputStream(args0)))
DataOutputStream out new
DataOutputStream( new
BufferedOutputStream(
new FileOutputStream(args1)))
3byte byteIn try
while(true) byteIn
in.readByte()
out.writeByte(byteIn)
catch(EOFException e)
in.close()
out.close()
4// reading a String from the user import
java.io. public class InputDemo public static
void main(String args) throws IOException
BufferedReader in
new BufferedReader( new
InputStreamReader(System.in))
System.out.println("What is your name?")
String name in.readLine()
System.out.println("Hello " name)
5// Using the StringTokenizer class // Read a line
of integers // and display their sum import
java.io. import java.util. // for
StringTokenizer public class LineOfInts public
static void main(String arg) throws
IOException
6 InputStreamReader is new InputStreamReader(S
ystem.in) BufferedReader br new
BufferedReader(is) StringTokenizer st
System.out.println("Enter a line of integers")
String s br.readLine() // use comma,
space, and tab for delimeters t new
StringTokenizer(s, ", \t")
7 int sum 0 while(st.hasMoreElements(
)) int val Integer.parseInt(st.nextToken())
sum val System.out.println("The sum
is " sum)
8// Read a double and display its square
root import java.io. public class DoubleIO
public static void main(String arg) throws
IOException InputStreamReader is new
InputStreamReader(System.in) BufferedReader
br new BufferedReader(is)
9 double x System.out.println("Enter a
double and I'll compute the square root")
String inputString br.readLine() x
Double.parseDouble(inputString) //
displays NAN if x lt 0 System.out.println("The
square root of "x" is " Math.sqrt(x))