Vous êtes sur la page 1sur 93

Java

Xiaoqiang Wang Florida State University

Why Java?

Its almost entirely object-oriented It has a vast library of predefined objects and operations Its more platform independent

this makes it great for Web programming

Its more secure It isnt C++

Applets, Servlets and Applications


An applet is designed to be embedded in a Web page, and run by a browser Applets run in a sandbox with numerous restrictions; for example, they cant read files and then use the network A servlet is designed to be run by a web server An application is a conventional program

Building Standalone JAVA Programs (on UNIX)


Prepare the file foo.java using an editor Invoke the compiler: javac foo.java This creates foo.class Run the java interpreter: java foo

Java Virtual Machine

The .class files generated by the compiler are not executable binaries

so Java combines compilation and interpretation

Instead, they contain byte-codes to be executed by the Java Virtual Machine

other languages have done this, e.g. UCSD Pascal

This approach provides platform independence, and greater security


5

HelloWorld (standalone)
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } }

Note that String is built in println is a member function for the System.out class
6

Comments are almost like C++


/* This kind of comment can span multiple lines */ // This kind is to the end of the line /** * This kind of comment is a special * javadoc style comment */

Primitive data types are like C

Main data types are int, double, boolean, char Also have byte, short, long, float boolean has values true and false Declarations look like C, for example,

double x, y; int count = 0;

Non-Primitive types in Java

Classes

Everything is a class, defined within a package byte[] b = new byte[100]; string st = scientific computing is initialized like a primitive type, but it is not a primitive type!

Arrays

Strings

Array Operations

Subscripts always start at 0 as in C Subscript checking is done automatically Certain operations are defined on arrays of objects, as for other classes

e.g. myArray.length == 5

10

Expressions are like C


Assignment statements mostly look like those in C; you can use =, +=, *= etc. Arithmetic uses the familiar + - * / % Java also has ++ and -Java has boolean operators && || ! Java has comparisons < <= == != >= > Java does not have pointers or pointer arithmetic

11

Control statements are like C


if (x < y) smaller = x; if (x < y){ smaller=x;sum += x;} else { smaller = y; sum += y; } while (x < y) { y = y - x; } do { y = y - x; } while (x < y) for (int i = 0; i < max; i++) sum += i;

BUT: conditions must be boolean !


12

Control statements II
switch (n + 1) { case 0: m = n - 1; break; case 1: m = n + 1; case 3: m = m * n; break; default: m = -n; break; }

Java also introduces the try statement, about which more later
13

Java isn't C!

In C, almost everything is in functions In Java, almost everything is in classes There is often only one class per file There must be only one public class per file The file name must be the same as the name of that public class, but with a .java extension
14

Java program layout

A typical Java file looks like:


import java.awt.*; import java.util.*; public class SomethingOrOther { // object definitions go here . . . } This must be in a file named SomethingOrOther.java !
15

References

All variable names in java that are not primitive types are actually references

int[] a = new int[100]; int[] b = a; // b and a are references to the 100 bytes in memory b[3] = 10; System.out.println(a[3]= + a[3]); // prints 10
16

Argument Passing

methods in java pass arguments by value the dummy argument in the method is a copy of the argument passed if a primitive type is passed, it is copied if a non-primitive type is passed, its reference is passed. More precisely, the variable is a reference.

17

Argument Passing
class Refer { ... public void refer(int[] a) { a[3] = 4; int[] b = new int[10]; // redefines the reference a = b; a[3] = 12.; // the caller argument is // unchanged!! } }

... Refer ref = new Refer(); int[] d = new int[20]; ref.refer(d); ... System.out.println("d[3]= " + d[3]); // prints the value 4

18

Scoping
As in C/C++, scope is determined by the placement of curly braces {}. A variable defined within a scope is available only to the end of that scope. { int x = 12;

/* only x available */ { int q = 96; /* both x and q available */ } /* only x available */ /* q out of scope */ } }
19

This is ok in C/C++ but not in Java. { int x = 12; { int x = 96; /* illegal */ }

An array is an object

Person mary = new Person ( ); int myArray[ ] = new int[5]; int myArray[ ] = {1, 4, 9, 16, 25}; String languages [ ] = {"Prolog", "Java"}; Since arrays are objects they are allocated dynamically Arrays, like all objects, are subject to garbage collection when no more references remain

so fewer memory leaks Java doesnt have pointers!

20

Scope of Objects

Java objects dont have the same lifetimes as primitives. When you create a Java object using new, it hangs around past the end of the scope. Here, the scope of name s is delimited by the {}s but the String object hangs around until GCd
{ String s = new String("a string"); } /* end of scope */
21

Name conventions

Java is case-sensitive; maxval, maxVal, and MaxVal are three different names Class names begin with a capital letter All other names begin with a lowercase letter Subsequent words are capitalized: theBigOne Underscores are not used in names These are very strong conventions!
22

JAVA Classes

The class is the fundamental concept in JAVA (and other OOPLs) A class describes some data object(s), and the operations (or methods) that can be applied to those objects Every object and method in Java belongs to a class Classes have data (fields) and code (methods) and classes (member classes or inner classes) Static methods and fields belong to the class itself Others belong to instances
23

Example
public class Circle { // A class field public static final double PI= 3.14159; constant // A useful // A class method: just compute a value based on the arguments public static double radiansToDegrees(double rads) { return rads * 180 / PI; } // An instance field public double r; // The radius of the circle

// Two methods which operate on the instance fields of an object public double area() { // Compute the area of the circle return PI * r * r; } public double circumference() { // Compute the circumference of the circle return 2 * PI * r; 24 }

Constructors

Classes should define one or more methods to create or construct instances of the class Their name is the same as the class name note deviation from convention that methods begin with lower case Constructors are differentiated by the number and types of their arguments An example of overloading If you dont define a constructor, a default one will be created. Constructors automatically invoke the zero argument constructor of their superclass when they begin (note that this yields a recursive process!)

25

Constructor example
public class Circle { public static final double PI = 3.14159; // A constant public double r; // instance field holds circles radius // The constructor method: initialize the radius field public Circle(double r) { this.r = r; } this.r refers to the r
field of the class

// Constructor to use if no arguments public Circle() { r = 1.0; } // better: public Circle() { this(1.0); }

This() refers to a constructor for the class

// The instance methods: compute values based on radius public double circumference() { return 2 * PI * r; } public double area() { return PI * r*r; } }
26

Extending a class

Class hierarchies reflect subclass-superclass relations among classes. One arranges classes in hierarchies: A class inherits instance variables and instance methods from all of its superclasses. Tree -> BinaryTree -> BST You can specify only ONE superclass for any class. When a subclass-superclass chain contains multiple instance methods with the same signature (name, arity, and argument types), the one closest to the target instance in the subclasssuperclass chain is the one executed. All others are shadowed/overridden. Something like multiple inheritance can be done via interfaces (more on this later) Whats the superclass of a class defined without an extends clause?

27

Extending a class
public class PlaneCircle extends Circle { // We automatically inherit the fields and methods of Circle, // so we only have to put the new stuff here. // New instance fields that store the center point of the circle public double cx, cy; // A new constructor method to initialize the new fields // It uses a special syntax to invoke the Circle() constructor public PlaneCircle(double r, double x, double y) { super(r); // Invoke the constructor of the superclass, Circle() this.cx = x; // Initialize the instance field cx this.cy = y; // Initialize the instance field cy } // The area() and circumference() methods are inherited from Circle // A new instance method that checks whether a point is inside the circle // Note that it uses the inherited instance field r public boolean isInside(double x, double y) { double dx = x - cx, dy = y - cy; // Distance from center double distance = Math.sqrt(dx*dx + dy*dy); // Pythagorean theorem return (distance < r); // Returns true or false } }

28

Data hiding and encapsulation


Data-hiding

or encapsulation is an important part of the OO paradigm. Classes should carefully control access to their data and methods in order to

Hide the irrelevant implementation-level details so they can be easily changed Protect the class against accidental or malicious damage. Keep the externally visible class simple and easy to document

Java

has a simple access control mechanism to help with encapsulation


Modifiers: public, protected, private, and package (default)
29

Package

Every class name lies in a file with an identical name Every class is defined within a package

// this file is in directory /path../gordon/grid package gordon.grid class Shape {...} --------------------------------package gordon // import all classes in the package gordon.grid import gordon.grid.* class SubShape extends Shape { Shape sh1; // short name allowed since class is imported (.*) gordon.grid.Shape sh2; // fully qualified name (not necessary) public void perimeter(...); }
30

Access control

Access to packages

Java offers no control mechanisms for packages. If you can find and read the package you can access it All top level classes in package P are accessible anywhere in P All public top-level classes in P are accessible anywhere

Access to classes

Access to class members (in class C in package P)


Public: accessible anywhere C is accessible Protected: accessible in P and to any of Cs subclasses Private: only accessible within class C Package: only accessible in P (the default)
31

32

The static keyword


Java methods and variables can be declared static (to create fields and methods that belong to the class, rather than to an instance of the class. ) These exist independent of any object This means that a Classs static methods can be called even if no objects of that class have been created and static data is shared by all instances (i.e., one rvalue per class instead of one per instance
class StaticTest {static int i = 47;} StaticTest st1 = new StaticTest(); StaticTest st2 = new StaticTest(); // st1.i == st2.I == 47 StaticTest.i++; // or st1.I++ or st2.I++ // st1.i == st2.I == 48

33

Abstract classes and methods


Abstract vs. concrete classes Abstract classes can not be instantiated


public abstract class shape { }

An abstract method is a method w/o a body


public abstract double area();

(Only) Abstract classes can have abstract methods In fact, any class with an abstract method is automatically an abstract class
34

Example: abstract class


public abstract class Shape { public abstract double area(); // Abstract methods: note public abstract double circumference();// semicolon instead of body. } class Circle extends Shape { public static final double PI = 3.14159265358979323846; protected double r; // Instance data public Circle(double r) { this.r = r; } // Constructor public double getRadius() { return r; } // Accessor public double area() { return PI*r*r; } // Implementations of public double circumference() { return 2*PI*r; } // abstract methods. } class Rectangle extends Shape { protected double w, h; public Rectangle(double w, double h) { this.w = w; this.h = h; } public double getWidth() { return w; } public double getHeight() { return h; } public double area() { return w*h; } public double circumference() { return 2*(w + h); } }

// Instance data // Constructor

// // // //

Accessor method Another accessor Implementations of abstract methods.


35

Syntax Notes

No global variables

class variables and methods may be applied to any instance of an object methods may have local (private?) variables but complex data objects are referenced

No pointers

36

Single Inheritance, but

A class may extend only one class, but it may implement many others A subclass inherits the variables and methods of its superclass(es), but may override them Overrides the methods defined in the class(es) it implements

37

Classes and Interfaces

The methods of an abstract class are implemented elsewhere A final class cannot be extended

38

Interfaces

Java does not allow multiple inheritance because it introduces problems as well as benefits. Fortunately, Java allows you to impose requirements on a class from multiple class-like interfaces. An interface is like an abstract class in that it can hold abstract method definitions that force other classes to implement ordinary methods. But it is also different:

An interface does NOT have instance variables (but it can have constants) All methods in an interface are abstract (they each have a name, parameters, and a return type, but no implementation) All methods in an interface are automatically public.
39

Classes vs. Interfaces


A class definition that implements an interface must define all the methods specified in that interface. In this respect, an interface is like an abstract class. An interface differs from an abstract class, however, in several respects: An interface only imposes definition requirements; interfaces do not supply definitions. A class extends exactly one superclass; a class can implement an unlimited number of interfaces. Thus, the purpose of the interface is strictly to impose requirements via its abstract methods; there are no method implementations:
40

Interfaces

Interfaces provide no mechanism for enforcing method specifications, other than method signatures you are free to deposit descriptive comments in an interface, however. Interfaces are excellent places for descriptive comments for two reasons: Interfaces, unlike class definitions, are free of clutter from implementing code. Programmers look to interfaces for method and class documentation.
41

Interfaces

The interface mechanism is an enormously important aid to good programming practice. Interfaces allow you to shift to the Java compiler a requirement-managing responsibility Interfaces encourage you to document your classes by acting, by convention, as documentation centers. Syntax:
public class someClassName implements I1, I2 { }

42

Interfaces Example

java.lang defines a Comparable interface as: public interface Comparable {int compareTo(Object other);} // no implementation If you wantclass to provide some function, implement an appropriate interface
public class Movie3 extends Attraction implements Comparable { public int compareTo (Object otherMovie) { Movie3 other = (Movie3) otherMovie; if (rating()< other. rating()) return -1; else if (rating() > other. rating())return 1; else return 0; } }

43

Exceptions

If an error does occur, that error is said to be exceptional behavior that throws an exception. Whenever an expression has the potential to throw an exception, you can embed that expression in a trycatch statement, in which you specify explicitly what Java is to do when an exception actually is thrown. Exceptions are objects in their own right

They can be generated, caught and handled under program control Examples: IOException, ArithmeticException, etc.

44

try/catch/finally

Associates a set of statements with one or more exceptions and some handling code
try { Thread.sleep(200); } catch(InterruptedException e){ System.out.println(e); } finally { System.out.println(Wakeup); }
45

Exceptions

Java will throw an exception when unusual conditions arise during execution of programs, e.g.,

E.g., Attempt to divide an integer by zero

To handle the exception, use the following:


try {statement with potential to throw exception} catch (exception-class-name parameter) {exception-handling-code }

To catch I/O exceptions, use:

FileNotFoundException or IOException class.

46

Exceptions

Suppose, for example, that you want to open a file for reading using a FileInputStream instance. You can acknowledge that the attempt may throw an exception by embedding the reading expressions in a block following the try keyword. Java stops executing statements in the try block as soon as an exception is thrown:
try { ... <-- An attempt to attach a stream to a file occurs here }
47

Exceptions

You specify what to do in the event that the exception is an instance of the IOException class by writing the keyword catch, followed by a parameter typed by IOException, surrounded by parentheses, followed by another block:
catch (IOException e) { ... }
48

Exceptions

To shut a program down, use System.exit(0); To have a block of statements executed after a try (whether or not an exception was thrown) use: finally { clean-up statements } You can create (and throw) your own exceptions, e.g.,

public class StrangeNewException extends Exception { } throw (new StrangeNewException () ) catch ( StrangeNewException e) { }

Alternative method to handle exceptions: public static void f(params) throws Exception-class
{ }

49

variables & objects

what happens when you run this?

String a = foo; System.out.println (a);

a foo (String)

it prints

foo

what is foo?

a string literal that evaluates to a String object a variable whose value is an object reference a declaration and an assignment in one

what is a?

what is String a = foo?

50

method calls

what happens when you run this?

String a = foo; String b = a.toUpperCase (); System.out.println (a);

a foo (String) b foo (String)

it prints

foo

what is toUpperCase?

a method of class String

type is String -> String declared as public String toUpperCase () what is a.toUpperCase ()?

a method call on the object a

does it change a?

no, it creates a new string


51

null references

what happens when you run this?


String a = null; System.out.println (a);

it prints null what happens when you run this?


String a = null; String b = a.toUpperCase ();
System.out.println (b);

it throws a NullPointerException why? because a method call must have a subject


52

sharing & equality

a foo (String) b foo (String)

what happens when you run this?


String a = foo; String b = foo; System.out.println (b);

it prints
foo

is that the same as this?


String a = foo; String b = a; System.out.println (b);

a foo (String) b

yes, because String is immutable. There is no way to distinguish these cases and, in fact, Java virtual machine may produce upper or lower state in this case.

53

mutable containers
what

happens when you run this?


v (Vector)

Vector v = new Vector (); String a = foo; v.addElement (a); System.out.println (v.lastElement ());
it

prints
foo a foo (String) b foo (String)

what

happens when you run this?

Vector v = new Vector (); String a = foo; String b = foo; v.addElement (a); System.out.println (v.lastElement ()); v.addElement (b); System.out.println (v.lastElement ());
it

prints
foo foo
54

aliasing
what

about this?

Vector v = new Vector (); Vector q = v; String a = foo; v.addElement (a); System.out.println (q.lastElement ());
it

v q (Vector)

a foo (String)

prints
foo

why?

because v and q are aliased: they are names for the same object

what

if we now do this?

if (v == q) System.out.println (same object); if (v.equals (q)) System.out.println (same value);


it

prints
same object same value

Aliasing occurs when several different identifiers refer to the same object. The term 55 is very general and is used in many contexts.

aliasing & immutables

what does this do?


String a = foo; String b = a; a.toUpperCase (); System.out.println (b);

a foo (String) b

it prints
foo

a foo (String) b FOO (String)

why? because strings are immutable The objects created by the toUpperCase method is eventually GCed (garbage collected.)

56

polymorphism

v (Vector)

what does this do? Vector v = new Vector (); e Vector e = new Vector () (Vector) v.addElement (e); e.addElement (foo); (String) System.out.println ( ((Vector) v.lastElement ()).lastElement ()); foo it prints foo what kind of method is addElement?
declared as public void addElement (Object o)
57

On polymorphism

First identified by Christopher Strachey (1967) and developed by Hindley and Milner, allowing types such as a list of anything. E.g. in Haskell we can define a function which operates on a list of objects of any type a (a is a type variable).

length :: [a] -> Int

Polymorphic typing allows strong type checking as well as generic functions. ML in 1976 was the first language with polymorphic typing. Ad-hoc polymorphism (aka overloading) is the ability to use the same syntax for objects of different types, e.g. "+" for addition of reals and integers. In OOP, the term is used to describe variables which may refer at run-time to objects of different classes.
58

reference loops

v (Vector)

can i even add v to itself?


Vector v = new Vector (); v.addElement (v); System.out.println (v.lastElement ())

foo

yes, try it! and this?


v.addElement (5);

no, 5 is a primitive value, not an object


59

a pair of methods

some types

what are the types of addElement, lastElement?

addElement (Object), return void lastElement (), return Object a puzzle

how are x and e related after this?

v.addElement (e); x = v.lastElement ();


they denote the same object can the compiler infer that? no! not even that x and e have the same class
60

downcasts

what does this do?


Vector v = new Vector (); String a = foo; v.addElement (a); String b = v.lastElement (); System.out.println (b);

compiler rejects it: v.lastElement doesnt return a String! what does this do?
Vector v = new Vector (); String a = foo; v.addElement (a); String b = (String) v.lastElement (); System.out.println (b);

it prints
foo
61

upcasting and downcasting

Suppose we have object O of class C1 with superclass C2 In Java, upcasting is automatic but downcasting must be explicit. Upcasting: treating O as a C2 Downcasting: treating O as a C1

62

variable & object classes

what does this do?


Vector v = new Vector (); String a = foo; v.addElement (a); Object o = v.lastElement (); System.out.println (o.getClass ());

it prints
java.lang.String

whats going on here?


getClass returns an object representing a class o.getClass () is the class o has at runtime System.out.println prints a string representation, ie, the name
63

Some key concepts


variables & objects variables hold object references (or primitive values like 5) null is a special object reference sharing, equality & mutability distinct objects can have the same value state is held in value of instance variables an object can be mutable (state may change) or immutable two variables can point to the same object; changing one affects the other methods a method has a subject or target object may be polymorphic, ie. work on several types of object compile-time & runtime types an object has a type at runtime: the class of its constructor a variable has a declared, compile-time type or class runtime class is subclass of compile-time class

64

The Java API

java.applet

java.io

Applet class

System.out.print length method for arrays; exceptions sockets System.getProperty

java.awt

java.lang

Windows, buttons, mouse, etc.

java.awt.image

java.net

image processing

java.awt.peer

java.util

GUI toolkit

See http://java.sun.com/j2se/1.3/docs/api/ for the current APIs

65

66

67

68

The package java.lang

The class Object


The root class in Java Example methods: clone(), equals(), toString() Subclasses may override these methods Example methods: getName(), getSuperClass()
69

The class Class

Observing an objects class

void printClassName (Object obj) { System.out.println("The class of " + obj + " is " + obj.getClass().getName()); }

70

Strings in Java

Strings are not a primitive data type, but represented as objects. Many methods defined in class java.lang:

Several constructors Lots of methods: concat(), equals(), indexOf(), length() strings are concatenated with + You can concatenate two strings to produce a new, longer string, using the + operator, but you cannot add, delete, insert into, or delete from any particular string.
71

Strings are constants (immutable)

StringBuffers in Java

Several methods defined in class java.lang:

Constructors can specify length or initial value append(), insertf(), length(), toString()

72

Java.lang.system

Printstreams

System.out.err(Error message); System.in.read(inputCharacter) System.in.read(inputBuffer, 0, maxChars)

Inputstreams

73

The Cloneable Interface

A class implements the cloneable interface by overriding the Object method clone() For example, we could add a clone() method to the FIFO class, if we wanted to be able to make copies of queues.

74

The class java.util


Interface to host OS Some basic functions and data structures

BitSet, Dictionary (the superclass of Hashtable), Stack, Vector Random number generation

75

System Properties

System properties are like UNIX environment variables, but platform independent The API class java.util has methods for accessing the system properties

76

// determine environment variables import java.util.*; class envSnoop { public static void main ( String args[] ) { Properties p; String s; p = System.getProperties(); p.list(System.out); s = System.getProperty("user.name"); System.out.println("user.name="+s); s = System.getProperty("user.home"); System.out.println("user.home="+s); } }
77

Java GUI

The awt class allows you to create


frames buttons menus and menubars checkboxes text areas scrolling lists

78

Java.net

Defines several useful objects:


URLs Internet Addresses Sockets Datagrams


packets sockets

79

Java I/O

In Java, there is clear distinction between streaming in formation to and from a program (bytes, char, binary) formatting data (number of decimal places, ints, etc.) flexibility comes at the price of more coding flexibility implies generality: read from sockets, create readers/writers with more capabilities In C and Fortran this distinction is not there can read and format with little verbosity flexible in terms of formatting price to pay: cannot extend the routines provided by the language to more general situations In C++, the iostream file (cin/cout) can be extended at the cost of efficiency
80

Efficiency

scientific computing usually deals with numbers written to and read from files C++

printf/scanf/fprintf/fscanf are more efficient than cin/cout flexibility comes at the price of efficiency use buffered I/O for more efficiency ideally suited to scientific program (its main reason for being created)
81

Java

Fortran 90/95

Streams

Reader/Writer: abstract classes


cannot be instantiated meant for character streams (mostly unicode) unicode: 2 bytes/character (for most languages) for byte input and output

InputStream/OutputStream: regular class

82

Reader

Subclasses of Reader (package java.io.reader)

BufferedReader

LineNumberReader (subclass of BufferedReader)

CharArrayReader FilterReader InputStreamReader PipedReader StringReader


83

Writer

Subclasses of Writer (package java.io.writer)


BufferedWriter CharArrayWriter FilterWriter OutputStreamWriter PipedWriter PrintWriter StringWriter


84

InputStream

Subclasses of InputStream

ByteArrayInputStream FileInputStream FilterInputStream

DataInputStream

ObjectInputStream PipedInputStream SequenceInputStream StringBufferInputStream


85

OuputStream

Subclasses of OuputStream

ByteArrayInputStream FileOutputStream FilterOutputStream

DataOutputStream

ObjectOutputStream PipedOutputStream SequenceOutputStream StringBufferOutputStream


86

java.io Package

Most (if not all) of the Java I/O classes are contained in the package java.io To use these classes, simply insert at the top of your code (below any package definitions): import java.io.*

This will import all the classes (*) in the java.io package
87

Unbuffered Reading

FileInputStream os = new FileInputStream(new File(gordon));


Disk/file Read a single byte

Program Read 1 byte from the file/disk


88

Buffered Reading
Disk/file Read a single byte Buffer of n bytes

Program Read 1 byte from the buffer


BufferedInputStream(InputStream in); // constructor BufferedInputStream(InputStream in, int size); BufferedInputStream os = new BufferedInputStream(new File(gordon)); String s = os.readLine(); // s=reference, readLine specific to BufferedInputStream

89

Buffered Writing
Disk/file Read a single byte Buffer of n bytes

Program write 1 byte to the buffer


BufferedOutputStream(OutputStream out); // constructor BufferedOutputStream(OutputStream out, int size); void write(byte[] b, int off, int len) throws IOException; // particular method BufferedOutputStream os = new BufferedOuputStream(new FileInputStream(gordon));

90

Binary Data

Consider an int (or float) (4 bytes): float f; Computers can write this data to a file in one of two ways:

BIG_ENDIAN (network order: order used by DataOutputStream) byte 1 (msb), byte 2, byte 3, byte 4 (lsb) LITTLE_ENDIAN byte 4 (lsb), byte 3, byte 2, byte 1 (msb); msb: most significant bit lsb: least significantn b

http://www.netrino.com/Embedded-Systems/HowTo/Big-Endian-Little-Endian
91

Writing Binary
// public class DataOutputStream extends FilterOutputStream // implements DataOutput { // class definition // DataOutputStream(OutputStream out); // constructor DataOutputStream os = new DataOutputStream(new File(gordon.bin)); os.writeBytes(gordon); double d=4.5; os.writeDouble(d); //int j; os.writeInt(j); // will not compile: j is not defined long lg=3455; os.writeLong(lg); byte[] b = new byte[100]; initialize b offset=10; len=20; os.writeBytes(b, offset, len); // write bytes b[9] through b[29]

92

Reading Binary
//DataInputStream(InputStream out); DataInputStream is = new DataInputStream(new File(gordon.bin)); double d = os.readDouble(d); int j = os.readInt(); long lg = os.readLong(lg); int offset = 10; len = 30; byte[] b = new byte[100]; os.read(b, off, len); // read len bytes starting from b[offset] // Cannot read multiple longs, ints, etc. at a given time. // To do this, one must call writeLong(), etc. multiple times // This is inefficient since writeLong() has a cost associated with calling it // In C++, fread(char* ptr, int size, int nb, FILE* fd); // can read n bytes calling the routine once. Therefore, it is expected to be // quite a bit faster than the Java version.

93

Vous aimerez peut-être aussi