250 likes | 396 Views
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
E N D
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 • There are couple of other streams as well.
DataOutputStream • DyteArrayOutputStreambaos = 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();
DataInputStream • When reading back the data: • byteArrayInputStreambais = 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.
The other 2 streams (2) • input is a little harder, since InputStreamReader read() returns one character at a time and it's an integer value fc= (FileConnection) Connector.open(fs,Connector.READ); InputStreamReader in = new InputStreamReader(fc.openInputStream()); t = ""; //now read in the text file, one character at a time. inti = 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);
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.
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);
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.
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.
Internal Storage • FileOutputStreamopenFileOutput(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.
Internal Storage (2) • FileInputStreamopenFileInput(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 command Since it is methods come from context, which a fragment doesn’t have directly.
Internal Example • Output dos = new DataOutputStream( openFileOutput("FileExample", Context.MODE_PRIVATE)); dos.writeUTF("First line of the file"); dos.writeUTF(“Second line of the file"); dos.close(); • Input String 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(); }
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.
External files • Before accessing files on external storage, you’ll need to check to see if the media is available. • Code to check booleanmExternalStorageAvailable = false;booleanmExternalStorageWriteable = false;String state = Environment.getExternalStorageState();if (Environment.MEDIA_MOUNTED.equals(state)) { // We can read and write the mediamExternalStorageAvailable = mExternalStorageWriteable = true;} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { // We can only read the mediamExternalStorageAvailable = 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 writemExternalStorageAvailable = mExternalStorageWriteable = false;}
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.
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.
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.
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.
BufferedWriter /Reader stream. • You can use the Buffered, but not completely implemented. • Examples: • Write a file BufferedWriterbW = new BufferedWriter(new FileWriter(file,true)); //append bW.write("Hi There"); //some some text bW.newLine(); //write out a newLine, no writeLinemethed bW.flush(); //flush may not be necessary, but good practice bW.close(); and close • Reading a file BufferedReaderin = new BufferedReader(new FileReader(file)); line = in.readLine(); while (line != null) { //null means end of file logger.append(line+"\n"); //logger is a TextView line = in.readLine(); } in.close();
Additional notes. Strings
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.
Example code • Filesystem.zip • 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.
Q A &