Cosc 4730

26
Cosc 4730 Files: Internal and External storage

description

Cosc 4730. Files: Internal and External storage. Note about Streams. In Java SE We use BufferedWriter and BufferedReader streams for most io These are only sort of implemented. Generally we get InputStream and OutputStream And pass them to DataInputStream and DataOutputStream - PowerPoint PPT Presentation

Transcript of Cosc 4730

Page 1: Cosc  4730

Cosc 4730

Files:Internal and External storage

Page 2: Cosc  4730

Note about Streams.

• In Java SE– We use BufferedWriter and BufferedReader

streams for most io– These are only sort of implemented.

• Generally we get InputStream and OutputStream– And pass them to DataInputStream and

DataOutputStream• There are couple of other streams as well.

Page 3: Cosc  4730

DataOutputStream• ByteArrayOutputStream baos = new ByteArrayOutputStream();• DataOutputStream dos = new DataOutputStream(baos);

– Now you write records data to dos use one or more methods• write: writes an array of bytes, with an offset and length of byte array• writeBoolean: writes a boolean to the stream• writeByte: writes one byte to the stream• writeChar: writes one character to the stream• writeChars: write a String as a sequence of characters• writeDouble: converts Double to long (doubleToLongBits) and writes long to stream• writeFloat: converts float to a int (floatToIntBits) and writes the int to the stream• writeInt: writes an integer to the stream• writeLong: writes a long to the stream• writeShort: writes a short intger to the stream• writeUTF: writes a String using UTF-8 encoding to the stream

• Once that's done, use baos variable to create the byte variable– byte[] bytes = boas.toByteArray();

Page 4: Cosc  4730

DataInputStream• When reading back the data:

– byteArrayInputStream bais = new ByteArrayInputStream(bytes); – DataInputStream dis = new DataINputStream(bais);– Now read it back the same way it written, using:

• read: Reads an array of bytes from the stream• readBoolean: Reads a boolean from the stream• readByte: Reads a single byte from the stream• readChar: Reads a character from the stream• readDouble: Reads a long from the stream and converts it to a double• readFloat: reads an int from the stream and converts it to a float• readInt: reads an integer from the stream• readLong: reads long integer from the stream• readShort: read a short integer from the stream• readUTF: reads a string in UTF-8 enconding.

Page 5: Cosc  4730

The other 2 streams (2)• input is a little harder, since it’s InputStream read() returns one character at

a time and it's an integer valueFileInputStream f = new FileInputStream(file);DataInputStream in = new DataInputStream(new BufferedInputStream(f));t = "";//now read in the text file, one character at a time.int i = in.read();while (i !=-1) { //To stop at end of line use (i !=-1 && (char) i != '\n')

t += (char)i;i = in.read();

}fc.close();System.out.println("read from file: "+t);

Page 6: Cosc  4730

The other 2 streams (2)

• Using these can make things simpler.• But– Now you have split up the strings• String tokenizers covered at the end of this lecture.

– Convert numbers to the correct type.• Otherwise– Now you can read text files created on most

machines and write files that can be read by most computers as well.

Page 7: Cosc  4730

PrintStream

• You may also find the printStream useful as well for output.– one doesn't throw exceptions, sets a status flag– Uses print and println– Example

String t = "Hi There"; int x = 12; PrintStream out = new

PrintStream(fc.openOutputStream());out.println(t);out.print(x); out.print(" "); out.println(x);

Page 8: Cosc  4730

FILESYSTEM

Page 9: Cosc  4730

Android and data Storage

• Android has three different methods for data storage.– Private but stored in the application private area – Public but stored in the application area on the SDcard (or

internal area)• For both of the above, when you uninstall the app, the data is

already deleted (assuming SDcard is also installed).– Public stored in the public file system, normally on the

SDcard (but maybe internal area if SDcard doesn’t exist)• We can also read files from the apk as well.– Note, you can’t write to the apk.

Page 10: Cosc  4730

Internal vs External storage• Internal storage

– You can save files directly on the device's internal storage. – By default, files saved to the internal storage are private to your

application and other applications cannot access them (nor can the user).

– When the user uninstalls your application, these files are removed.• External storage

– This can be a removable storage media (such as an SD card) or an internal (non-removable) storage.

– Files saved to the external storage are world-readable and can be modified by the user when they enable USB mass storage to transfer files on a computer.

Page 11: Cosc  4730

Internal Storage

• FileOutputStream openFileOutput(String File, MODE)– File: the filename for output– MODE: Context.MODE_PRIVATE, MODE_APPEND,

MODE_WORLD_READABLE, and MODE_WORLD_WRITEABLE.• Note If the file already exists, then it will be overwritten, except

with MODE_APPEND.

• It returns a FileOutputStream, which we then send to DataOutputStream.

• Close() when you are finished with the file.

Page 12: Cosc  4730

Internal Storage (2)• FileInputStream openFileInput(String File)

– Open the files named.– Again, send it to DataInputStream for ease of reading.

• getFilesDir()– Gets the absolute path to the filesystem directory where your internal files

are saved.• getDir()

– Creates (or opens an existing) directory within your internal storage space.• deleteFile()

– Deletes a file saved on the internal storage.• String[] fileList()

– Returns an array of files currently saved by your application.

A note, in a fragment, you will need to use getActivity(). and then the commandSince it is methods come from context, which a fragment doesn’t have directly.

Page 13: Cosc  4730

Internal Example• Outputdos = new DataOutputStream( openFileOutput("FileExample", Context.MODE_PRIVATE));dos.writeUTF("First line of the file");dos.writeUTF(“Second line of the file");dos.close();

• InputString flist[] = fileList();in = new DataInputStream( openFileInput(flist[0]) ) ;while(true)

try { label1.append(in.readUTF() + "\n"); //label1 is a TextView} catch (EOFException e) { //reach end of file in.close();}

Page 14: Cosc  4730

Files in the apk

• If you have a static (read only) file to package with your application at compile time, you can save the file in your project in res/raw/myDataFile, and then open it with getResources().openRawResource (R.raw.myDataFile). – It returns an InputStream object that you can use

to read from the file.

Page 15: Cosc  4730

External files• Before accessing files on external storage, you’ll need to check to see if the media is available.• Code to checkboolean mExternalStorageAvailable = false;boolean mExternalStorageWriteable = false;String state = Environment.getExternalStorageState();

if (Environment.MEDIA_MOUNTED.equals(state)) { // We can read and write the media mExternalStorageAvailable = mExternalStorageWriteable = true;} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { // We can only read the media mExternalStorageAvailable = true; mExternalStorageWriteable = false;} else { // Something else is wrong. It may be one of many other states, but all we need // to know is we can neither read nor write mExternalStorageAvailable = mExternalStorageWriteable = false;}

Page 16: Cosc  4730

External Files (2)

• //API 8 and above– getExternalFilesDir() //public but in app data.• For none shared files• Creates the directory

/Android/data/<package_name>/files/ • Directory and all files deleted when app is uninstalled.

– getExternalStoragePublicDirectory() //public• For files that are to be shared.• Not deleted when app is uninstalled.

Page 17: Cosc  4730

Environment. directoriesDIRECTORY_ALARMS Standard directory in which to place any audio files that should be in the list of alarms

that the user can select (not as regular music).

DIRECTORY_DCIM The traditional location for pictures and videos when mounting the device as a camera.

DIRECTORY_DOWNLOADS Standard directory in which to place files that have been downloaded by the user.

DIRECTORY_MOVIES Standard directory in which to place movies that are available to the user.

DIRECTORY_MUSIC Standard directory in which to place any audio files that should be in the regular list of music for the user.

DIRECTORY_NOTIFICATIONS

Standard directory in which to place any audio files that should be in the list of notifications that the user can select (not as regular music).

DIRECTORY_PICTURES Standard directory in which to place pictures that are available to the user.

DIRECTORY_PODCASTS

Standard directory in which to place any audio files that should be in the list of podcasts that the user can select (not as regular music).

DIRECTORY_RINGTONES

Standard directory in which to place any audio files that should be in the list of ringtones that the user can select (not as regular music).

Page 18: Cosc  4730

External Files (3)

• File file = new File(getExternalFilesDir(null), “myfile.txt");– Create directory if needed and the spot for the file,

called myfile.txt– null: it’s a file for my application– If I wanted a music directory then• File file = new

File(getExternalFilesDir( Environment.DIRECTORY_MUSIC), “file.mp3");• Place in the a subdirectory of music.

Page 19: Cosc  4730

External Files (4)• Read

– in = new DataInputStream(new FileInputStream(file) );• Write

• dos = new DataOutputStream(new FileOutputStream(file) );• Append:

– dos = new DataOutputStream(new FileOutputStream(file,true) );

• Read or write as normal. Then close the file when you are done.• Other useful methods of file

– file.exists() //return true if file exists– file.delete(); //deletes the file– See http://developer.android.com/reference/java/io/File.html for more.

Page 20: Cosc  4730

external files (5)

• getExternalStoragePublicDirectory() File path = Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES);• There is no NULL version. File file = new File(path, "DemoPicture.jpg");// Make sure the directory exists.path.mkdirs(); //NOT file, other it creates the file as a directory.//Now use file just like before.

Page 21: Cosc  4730

BufferedWriter /Reader stream.• You can use the Buffered, but not completely implemented.• Examples:• Write a file BufferedWriter bW = new BufferedWriter(new FileWriter(file,true)); //append bW.write("Hi There"); //some some textbW.newLine(); //write out a newLine, no writeLine methedbW.flush(); //flush may not be necessary, but good practicebW.close(); and close• Reading a fileBufferedReader in = new BufferedReader(new FileReader(file));line = in.readLine();while (line != null) { //null means end of file

logger.append(line+"\n"); //logger is a TextViewline = in.readLine();

}in.close();

Page 22: Cosc  4730

STRINGSAdditional notes.

Page 23: Cosc  4730

Breaking up strings.

• the string.split(String RegularExpression) is included on Android. – So String[] = line.split(“ “) would break up the

string in line based on a space and put the resulting string array

• Java.util has the StringTokenizer, but considered “legacy” and should not be used.

Page 24: Cosc  4730

Example code

• Filesystem example code– Has three fragments• Each writes and reads a file in a different location

– Local private, on the SD card public and into the download directory on the SD card.

• You can click the run on each of them to have run again again, so see it work.

Page 25: Cosc  4730

Final Note.

• The sdcard is part of the main system and not the actually sdcard, which normally shows as sdcard1– And As of KitKat (4.4+) the actual Sdcard is write

protected (read only). The device has to be rooted in order to write to it.

Page 26: Cosc  4730

QA&