the package statement

11
The Package Statement Group related interfaces and classes together Purpose: encapsulation and reduces name conflicts private package classes not visible outside the package Classes in different packages can have the same names Creating a package class file The first statement: package <package name>; Where do we store a package’s class files? In sub-folders of the parent package folder Name the sub-folder: <package name> – Alternatives • Create jar file and add to classpath environment variable • Put into the lib/ext folder of JVM • Package and sub packages only related by where they are stored

Upload: decker

Post on 05-Jan-2016

34 views

Category:

Documents


0 download

DESCRIPTION

The Package Statement. Group related interfaces and classes together Purpose: encapsulation and reduces name conflicts private package classes not visible outside the package Classes in different packages can have the same names Creating a package class file - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: The Package Statement

The Package Statement• Group related interfaces and classes together• Purpose: encapsulation and reduces name conflicts

– private package classes not visible outside the package– Classes in different packages can have the same names

• Creating a package class file– The first statement: package <package name>;

• Where do we store a package’s class files?– In sub-folders of the parent package folder– Name the sub-folder: <package name> – Alternatives

• Create jar file and add to classpath environment variable• Put into the lib/ext folder of JVM• Package and sub packages only related by where they are stored

Page 2: The Package Statement

The Import Statement

• Example: import java.awt.event.*;• Java automatically imports the package, java.lang • The import statement allows references to package

classes that are not fully qualified. It doesn’t actually load anything

• Sub packages are referenced using dot notation. Example: java.awt.Button. Button is a sub-package of java.awt

• Fully qualified names are always needed if the same class name appears in two or more packages.

Page 3: The Package Statement

Notes on the Import Statement• Import can reference either a single package class or

all classes of a package.

• Wildcard references do not apply to sub-packages.• Import java.awt.Button allows us to WRITE

b = new Button(“Clear”);instead of

b = new java.awt.Button(“Clear”);

• Legal uses of import:a. import java.awt.*; okay

b. import java.awt.E* no good.

c. import java.awt.*; does not import java.awt.Event.*

Page 4: The Package Statement

Input and Output Streams

• Streams handle Java input and output.• File transfer moves data to/from disk rather than

to/from keyboard or screen

Page 5: The Package Statement

File I/O Concepts• Files allow programs to access persistent data.

• Key terms: database, file, record, and field

• File access operations: open, read, write, close.

• Handle exceptions when dealing with files.– FileNotFoundException, IOException, EOFException

• File types are: Sequential and Random

• Data types are: Text, Binary, and Object

• File class: File file = new File(“pathname”) if (!file.exists()) file doesn’t exist.

Page 6: The Package Statement

Sequential Text File Streams• Stream: Flow of source to sink• Operations: sequential reads and writes of Strings

BufferedReader in = new BufferedReader( new FileReader(“path”));

strVar = in.readLine();in.close();PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(“path”)));out.println(“data”);out.close();

• BufferedReader wraps FileReader – Reads entire line instead of a character at a time– The readLine() method returns null if at the end of file.

• PrintWriter contains print and println methods.

Page 7: The Package Statement

Binary Files Streams

Operations: Reads and Writes of binary or text data

DataOutputStream out=new DataOutputStream(new FileOutputStream(“path”));DataInputStream in=new DataInputStream(new FileInputStream(“path”));

out.writeUTF(“data”); str = in.readUTF();out.writeInt(x); int var = in.readInt();out.writeDouble(3.5); double val = in.readDouble();out.flush(); in.close();

out.close();

1. UTF stands for Unicode Text Format for writing and reading strings

2. DataOutputStream wraps FileOutputStrea to provide more methods for different data types.

Page 8: The Package Statement

Random File Read and WriteRandomAccessFile raf = new RandomAccessFile(“path”,”access”);

Read(byte[]), readBoolean(), readChar(), readDouble(), readFloat(), readInt(), readLine(), readLong(), readShort(), readUTF(), length(), setLength(), getFilePosition(), writeBoolean(), writeChar(), writeDouble(), writeFloat(), writeInt(), writeLine(), writeLong(), writeShort(), writeUTF(),seek(long), close().

• “access” notes– Can be “rw”, “r”, “w”.

– If “r”, the file must pre-exist.

– If “rw” or “w” and the file doesn’t exist, it will be created.

– “rwd” writes with immediate updates to storage.

• Seek first and then use the various methods

Page 9: The Package Statement

Writing objects to files• Make the object serializable

– Add Implements java.io.Serializable onto class signature line of any object that can be written to disk.

– Place the keyword transient on any instance variables that are not to be serialized (ex: private transient int x;);

• Which streams?– ObjectOutputStream stream = new ObjectOutputStream(

new BufferedOutputStream(newFileOutputStream(name)));– ObjectInputStream stream = new ObjectInputStream(

new BufferedInputStream(new FileInputStream(name)));

• Which methods?stream.writeObject(objVariable);objVariable = (ObjectClassName)stream.readObject();stream.close();

Page 10: The Package Statement

Check if File is Readable

Boolean isReadable(String fileName)

{ File file = new File(fileName);

if (!file.exists())

throw new FileNotFoundException();

if (!file.canRead())

throw new IOException();

}

Page 11: The Package Statement

Dialog for Choosing a File

String str = System.getProperty ("user.dir"); JFileChooser chooser = new JFileChooser(str);int result = chooser.showOpenDialog(null);

if (result == JFileChooser.APPROVE_OPTION) {

File file = chooser.getSelectedFile();String fileName = file.getName();System.out.println("You selected " + fileName);

// Insert code here to open and access data from file} else System.out.println("You cancelled the file dialog");