View
32
Download
0
Category
Tags:
Preview:
DESCRIPTION
Data Storage, Continued. Review of FileConnection. Can read data that other apps have written to file system A traditional file system javax.microedition.io.file package Use Connector class to create the actual connection. Review Connector Class. javax.microedition.io.Connector - PowerPoint PPT Presentation
Citation preview
PROG 38448
Mobile Java Application Development
PROG 38448
Mobile Java Application Development
Data Storage, Continued
04/21/23 Wendi Jollymore, ACES 2
Review of FileConnectionReview of FileConnection
Can read data that other apps have written to file systemA traditional file systemjavax.microedition.io.file packageUse Connector class to create the actual connection
04/21/23 Wendi Jollymore, ACES 3
Review Connector ClassReview Connector Class
javax.microedition.io.ConnectorA factory class used to create connectionsFile connections, network connections, etc..
Connector.open(string) opens a connection and returns a Connection object{scheme}:[{target}][{parms}] (see docs for a list of schemes){scheme} - name of a protocol, such as http:// or file://{target} - normally some kind of network address or resourceAny {parms} are formed as a series of equates of the form ";x=y". i.e. ";type=a“
04/21/23 Wendi Jollymore, ACES 4
Review File SystemReview File System
It’s important to know the locations of the various storage locations:
store/device memory home - internal flash memory
SDCard/ sd card home
system/ internal sd card on Bold and Storm (transient data objects and runtime processes - 860MB)
04/21/23 Wendi Jollymore, ACES 5
Review Creating ConnectionReview Creating Connection
Exception is thrown if path is invalidDoesn’t have to exist - *could* existOnly the last item can be non-existentThis allows you to create new files/directories
try { FileConnection storeDirectory = FileConnection)Connector.open("file:///store/");} catch (IOException e) { Dialog.alert(e.getMessage());}
04/21/23 Wendi Jollymore, ACES 6
Review FileConnection MethodsReview FileConnection Methods
FileConnection.close()From parent interface ConnectionCloses file connection
FileConnection.isDirectory()True if the object points to a directory
FileConnection.exists() True of the directory/file exists
04/21/23 Wendi Jollymore, ACES 7
FileConnection MethodsFileConnection Methods
FileConnection.create()Creates a file corresponding to the string provided in the Connection.open() methodCreated with 0 lengthDoes not create directories in the path
Throws IOExceptionUse output streams to write data to the file
04/21/23 Wendi Jollymore, ACES 8
FileConnection MethodsFileConnection Methods
FileConnection.mkdir()Creates a directory corresponding to the string provided in the Connection.open() methodNot recursive – you must create all new dirs in a path if they don’t exist
throws IOException
04/21/23 Wendi Jollymore, ACES 9
Working with Dirs and FilesWorking with Dirs and Files
If you have a file that doesn’t exist in a directory that doesn’t exist
You have to create the directory first:
FileConnection fileConn = (FileConnection) Connector.open(aPath);if (!fileConn.exists()) { fileConn.mkdir();}
04/21/23 Wendi Jollymore, ACES 10
Working with Dirs and FilesWorking with Dirs and Files
Then you have to reset the file connection:
Then you have to create a connection to the file and create it:
fileConn.close();fileConn = null;
fileConn = (FileConnection) Connection.open(fileName);if (!fileConn.exists()) { fileConn.create();}
04/21/23 Wendi Jollymore, ACES 11
Working with Dirs and FilesWorking with Dirs and Files
If your directory and file already exist, there’s a shorter way:
This still allows you to use the same FileConnection object
But it only works when every part of the path/file exists
Throws an IOException
fileConn.setFileConnection(fileName);
04/21/23 Wendi Jollymore, ACES 12
Working with StreamsWorking with Streams
To read and write data, you need an input or output streamWe use binary steams only
more efficientcan use regular InputStream or OutputStreamDataInputStream or DataOutputStream a bit more convenient
you can read/write data types and strings (sort of)
04/21/23 Wendi Jollymore, ACES 13
Working with StreamsWorking with Streams
FileConnection.openInputStream();Opens and returns an InputStream object Connected to the file specified when the connection was createdThe file must exist, must be accessible
FileConnection.openDataInputStream();Opens and returns a DataInputStream objectSame as above
Both throw IOException
04/21/23 Wendi Jollymore, ACES 14
Working with StreamsWorking with Streams
FileConnection.openOutputStream();Opens and returns an OutputStream object File pointer positioned at start of fileThe file must exist, must be accessibleopenOutputStream(long offset) will start at byte offset
FileConnection.openDataOutputStream();Opens and returns a DataOutputTream objectSame as above but can’t use offset
All throw IOException
04/21/23 Wendi Jollymore, ACES 15
Working with StreamsWorking with Streams
Opening streams from the file connecton object:
When you are done with a stream:Close it using close() methodAssign null to stream object
DataInputStream fileIn = fileConn.openDataInputStream();
DataOutputStream fileOut = fileConn.openDataOutputStream();
04/21/23 Wendi Jollymore, ACES 16
Working with StreamsWorking with Streams
Look up DataInputStream and DataOutputStream in the api docsNote the methods to read and write data to the fileEverything must be a fixed size
E.g. ints are always 4 bytes, doubles are 8 bytes, Strings are 2 bytes per character
Remind you of Random Access Files?
04/21/23 Wendi Jollymore, ACES 17
Working with StreamsWorking with Streams
Strings are the ones you need to pay most attention to.When storing data as “records”, all records must be exact same size
So you know where to find record x
All strings must be fixed widthDefine how many characters your string fields are
Make sure they’re saved as that exact size
04/21/23 Wendi Jollymore, ACES 18
Working with StreamsWorking with Streams
Example: Field size is 25
Field is either truncated or padded to be the exact size of 25 chars
int currSize = str.length();if (currSize > size)
str = str.substring(0, size);else if (currSize < size) {
String temp = str;for (int i=currSize; i<=size; i++)
str += “ “;}
04/21/23 Wendi Jollymore, ACES 19
Working with StreamsWorking with Streams
Example: reading back the same data
Read individual chars until you build the string field
Must be the correct number of chars!
String temp = “”;for (int i=0; i<size; i++) { String c = String.valueOf(fileIn.readChar()); temp += c;}
ExerciseExercise
New ProgramAdd three EditFields
One to enter an int, one for a double, and one for a String
Add buttons Save, Clear, ReadAdd event handling stuff for buttonsAdd a display label
Save: saves the 3 valuesInfo: clears txt fieldsRead: shows some saved values
04/21/23 Wendi Jollymore, ACES 20
ExerciseExercise
We’ll set the string to 25 charsA whole record will be 62 bytes
4 for the int, 8 for the double25 * 2 for the string
We’ll need methods:Prep the string for writingRead the string from a stream
Add the same loadFile() methodDisplay file size in label, too
04/21/23 Wendi Jollymore, ACES 21
ExerciseExercise
Saving Data method: fileDataOut()Use the file connection to create a DataOutputStreamwriteInt(), writeDouble()Prep the string value and writeChars()Close stream and set to null
04/21/23 Wendi Jollymore, ACES 22
ExerciseExercise
Reading Data method: fileDataIn()Calc number of records
File size / rec sizeIf the file connection is readable and we have records:
Create a DataInputStreamFor each record:
readInt(), readDouble(), your readString() methodBuild an output string
Close stream and set to nullDisplay output from file in label
04/21/23 Wendi Jollymore, ACES 23
04/21/23 Wendi Jollymore, ACES 24
ExerciseExercise
When program exits, you must:Close file connectionAssign null to file connection object
Override the close() method:if (fileConn != null && fileConn.isOpen()) { fileConn.close(); fileConn = null;}
04/21/23 Wendi Jollymore, ACES 25
Simulator NotesSimulator Notes
If you want to start from scratch each time you debug:
Erase File System optionBe careful doing this if you’re using SDCard option!!
04/21/23 Wendi Jollymore, ACES 26
File IssuesFile Issues
What happens when you run the app multiple times?Add new data each timeWhat happens to your old data?
You can’t append with DataOutputStream
You must use OutputStreamSet the offset to the file size
04/21/23 Wendi Jollymore, ACES 27
File IssuesFile Issues
Example:long size = fileConn.fileSize();OutputStream fileOut = fileConn.openOutputStream(size);
Also:OutputStream works with data differentlyThere are no methods like writeInt()You have to convert ints and doubles to bytes!
04/21/23 Wendi Jollymore, ACES 28
File IssuesFile Issues
Converting ints and doubles to bytes:I gave you some code in the notes
Note that strings are no longer 2 bytes per character
They’re one byte eachYou’ll need to adjust your read methodYou’ll need to adjust any size constantsString.getBytes() returns byte[]
04/21/23 Wendi Jollymore, ACES 29
ExerciseExercise
Edit your program so that you can append records to the end of the file
String.getBytes() will give you the bytes for the String valueoutputStream.write(byte[]) will write an array of bytesdataInputStream.readFully(byte[]) can be used to read your string data back
Then String s = new String(bytes);
Recommended