110 likes | 354 Views
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
E N D
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
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.
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: • import java.awt.*; okay • import java.awt.E* no good. • import java.awt.*; does not import java.awt.Event.*
Input and Output Streams • Streams handle Java input and output. • File transfer moves data to/from disk rather than to/from keyboard or screen
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.
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.
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); intvar = in.readInt();out.writeDouble(3.5); double val = in.readDouble();out.flush(); in.close(); out.close(); • UTF stands for Unicode Text Format for writing and reading strings • DataOutputStreamwrapsFileOutputStreato provide more methods for different data types.
Random File Read and Write RandomAccessFileraf = 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
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();
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(); }
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");