Working with Files

Basic Tutorials concerning: GUI, Views, Activites, XML, Layouts, Intents, ...

Working with Files

Postby plusminus » Tue Nov 27, 2007 12:45 am

Working with Files


What you learn: You will learn how to access file (read and write) and why we cannot use standard Java file-access.

:?: Problems/Questions: Write them right below...

Difficulty: 1 of 5 :)

What it will look like:
:lol: This is the first tutorial without a screenshot :lol:


Description:
To understand why we cannot use standard java file access, like:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. FileWriter f = new FileWriter("impossible.txt");
  2. // throws: 'java.io.FileNotFoundException: /impossible.txt '
Parsed in 0.031 seconds, using GeSHi 1.0.8.4

, we have to understand the Security-Model of Android.
Each *.apk File that is installed on the Emulator/Device gets its own User-ID from the Linux System. This ID is the key to the sandbox of the application. This 'sandbox' protects the application (and its files) from other bad :twisted: apps, that i.e. want to manipulate the files we created in a bad manner (Like writing into them: "Whos reads this is... dumb ! Hhahaha").
Note wrote:But, writing to SD-Cards is still possible with 'normal' Java methods :!:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. FileWriter f = new FileWriter("/sdcard/download/possible.txt");
Parsed in 0.032 seconds, using GeSHi 1.0.8.4

will work without any problem, you just need to add virtual sdcard to your emulator.


Every file that you generate with your code gets is 'signed' with the User-ID of the Application that created it. One From within your app you can set flags to make the file accessible (read and/or write) for other applications with other User-IDs (Flags: MODE_WORLD_READABLE and/or MODE_WORLD_WRITEABLE).

There is a way to make two applications use the same userid (look here).



1.Writing a file...
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.         try { // catches IOException below
  2.                         final String TESTSTRING = new String("Hello Android");
  3.                        
  4.                         // ##### Write a file to the disk #####
  5.                         /* We have to use the openFileOutput()-method
  6.                          * the ActivityContext provides, to
  7.                          * protect your file from others and
  8.                          * This is done for security-reasons.
  9.                          * We chose MODE_WORLD_READABLE, because
  10.                          *  we have nothing to hide in our file */             
  11.                         FileOutputStream fOut = openFileOutput("samplefile.txt",
  12.                                                                 MODE_WORLD_READABLE);
  13.                         OutputStreamWriter osw = new OutputStreamWriter(fOut); 
  14.  
  15.                         // Write the string to the file
  16.                         osw.write(TESTSTRING);
  17.                         /* ensure that everything is
  18.                          * really written out and close */
  19.                         osw.flush();
  20.                         osw.close();
Parsed in 0.036 seconds, using GeSHi 1.0.8.4

2.Reading the file back...
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.                         // ##### Read the file back in #####
  2.                        
  3.                         /* We have to use the openFileInput()-method
  4.                          * the ActivityContext provides.
  5.                          * Again for security reasons with
  6.                          * openFileInput(...) */
  7.                         FileInputStream fIn = openFileInput("samplefile.txt");
  8.                         InputStreamReader isr = new InputStreamReader(fIn);
  9.                         /* Prepare a char-Array that will
  10.                          * hold the chars we read back in. */
  11.                         char[] inputBuffer = new char[TESTSTRING.length()];
  12.                         // Fill the Buffer with data from the file
  13.                         isr.read(inputBuffer);
  14.                         // Transform the chars to a String
  15.                         String readString = new String(inputBuffer);
  16.                        
  17.                         // Check if we read back the same chars that we had written out
  18.                         boolean isTheSame = TESTSTRING.equals(readString);
  19.  
  20.                         // WOHOO lets Celebrate =)
  21.                         Log.i("File Reading stuff", "success = " + isTheSame);
  22.  
  23.                 } catch (IOException ioe) {
  24.                         ioe.printStackTrace();
  25.                 }
Parsed in 0.038 seconds, using GeSHi 1.0.8.4


The file is now located in the following folder on your emulator:
"/data/data/your_project_package_structure/files/samplefile.txt"
How to browse the FileSystem of the Emulator watch 3 posts below.


:idea: You delete a file with the following method coming from ApplicationContext:

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  public boolean deleteFile(String name)
  2. // Delete the given private file associated with this Context's application package.
Parsed in 0.035 seconds, using GeSHi 1.0.8.4


Regards,
plusminus
Last edited by plusminus on Mon Dec 17, 2007 4:34 pm, edited 5 times in total.
Image
Image | Android Development Community / Tutorials
User avatar
plusminus
Site Admin
Site Admin
 
Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

Top

Postby fresco » Tue Nov 27, 2007 4:56 pm

You forgot to add that we can use the regular java methods like you mentioned "FileWriter f = new FileWriter("impossible.txt");" when you workind with sdcard.

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. FileWriter f = new FileWriter("/sdcard/download/impossible.txt");
Parsed in 0.036 seconds, using GeSHi 1.0.8.4
will work without any problem, you just need to add virtual sdcard to your emulator.
fresco
Junior Developer
Junior Developer
 
Posts: 24
Joined: Sun Nov 18, 2007 10:36 am

Postby plusminus » Tue Nov 27, 2007 6:08 pm

Thanks fresco,

added it above :!:

Regards,
plusminus
Image
Image | Android Development Community / Tutorials
User avatar
plusminus
Site Admin
Site Admin
 
Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

where's the log written at?

Postby rtheman » Fri Nov 30, 2007 10:56 pm

So where can I find and view the log entry? Better yet, where is the .txt file that's written? I'm doing this on a XP box
rtheman
Freshman
Freshman
 
Posts: 4
Joined: Wed Nov 28, 2007 9:46 pm

Postby plusminus » Sat Dec 01, 2007 11:00 am

Hello rtehman,

This way to get to the DDMS-Perspective in Eclipse (if A isn't visible, do B):
Image

On the Bottom you will see the so called "LOGCAT"-View appear where the Logs are written to.

Here switch to the File Explorer.
Image


The file is now located in the following folder on your emulator: "/data/data/your_project_package_structure/files/samplefile.txt"
(added it above)

Regards,
plusminus
Image
Image | Android Development Community / Tutorials
User avatar
plusminus
Site Admin
Site Admin
 
Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

Other file operations?

Postby Gamby » Wed Dec 12, 2007 11:28 pm

Hi, thanks for the tutorial.

But, what about deleting and asking the existence of a file? How should I perform that operations?

I tried in this way:

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. if (files[i].equals("samplefile.txt")) {
  2.                     File f = new File("files", files[i]);
  3.                    
  4.                     if (f.exists()) {
  5.                         Log.v(TAG, "File exists! " + f.getAbsolutePath());
  6.                     }
  7.                     else {
  8.                         Log.v(TAG, "File NOT exists! " + f.getAbsolutePath());
  9.                     }
  10.                    
  11.                     if (f.delete()) {
  12.                         Log.v(TAG, "File deleted!");
  13.                     }
  14.                     else {
  15.                         Log.v(TAG, "File NOT deleted! " + f.getAbsolutePath());
  16.                     }
  17.                 }
  18.  
Parsed in 0.038 seconds, using GeSHi 1.0.8.4


But the Log says:
File NOT exists! /files/samplefile.txt
File NOT deleted! /files/samplefile.txt

If i go in adb shell or in file explorer I can see that file located inside files folder

And what about "files" folder? Is it a standard unchangeble folder?
Should I put my files inside that folder if I want my app is able to load them?

Thanks and best regards!
Gamby
Gamby
Freshman
Freshman
 
Posts: 7
Joined: Mon Nov 26, 2007 3:16 pm
Location: Italy

Top

Postby plusminus » Wed Dec 12, 2007 11:36 pm

Hello gamby,

you delete a file with the following method coming from ApplicationContext:

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  public boolean deleteFile(String name)
  2. // Delete the given private file associated with this Context's application package.
Parsed in 0.035 seconds, using GeSHi 1.0.8.4


Added it above, too.

Regards,
plusminus
Image
Image | Android Development Community / Tutorials
User avatar
plusminus
Site Admin
Site Admin
 
Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

Postby Gamby » Wed Dec 12, 2007 11:41 pm

Thank you very much plusminus!

And what about these other quqestions, can you help me to understand?
And what about "files" folder? Is it a standard unchangeble folder?
Should I put my files inside that folder if I want my app is able to load them?


Thanks again best regard.
Gamby
Gamby
Freshman
Freshman
 
Posts: 7
Joined: Mon Nov 26, 2007 3:16 pm
Location: Italy

Postby plusminus » Wed Dec 12, 2007 11:47 pm

:) should have had a closer look ^^

it depends on how you have created the file :!:
Creating a file with the procedures Android provides "marks" the files to the "User-ID" of the specific *.apk-File (Application).

When you create a file with MODE_WORLD_WRITEABLE it will be writable ( probably also readable ) by other Applications. MODE_PRIVATE will disallow them to do so.

Regards,
plusminus
Image
Image | Android Development Community / Tutorials
User avatar
plusminus
Site Admin
Site Admin
 
Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

Postby Gamby » Wed Dec 12, 2007 11:56 pm

That file i'm talking about, I haven't created it from code, but I have pushed it with "adb push".

A pushed file, I think, it is a private file for the application(MODE_PRIVATE)

Reapting with other words, m question is:

If I want my application was able to read the files that I push inside (for example) /data/data/my/package/ahyeah_folder
which apis should I use to read them?

Downloaded files from web do they finish? in which folder by default?

Thanks, regards!
Gamby
Gamby
Freshman
Freshman
 
Posts: 7
Joined: Mon Nov 26, 2007 3:16 pm
Location: Italy

Thanks - more example for pulling in data?

Postby rtheman » Thu Dec 20, 2007 3:54 pm

Thanks for the 'extra' tutorials to locate such file...

I haven't been able to look though this whole site yet, but what I'd like to do is be able to pull in files with data (encoded in XML) such as weather, stock, other custom data; then display it on android such as weather front on google map rendering Rain, Snow, Wind, temp data on the xml file with some sort of graphics on android using g-map.

Is there something similar to this exist as tutorial? I'm really a newbie w/ Java and step by step is what I need... Thanks!

plusminus wrote:Hello rtehman,

This way to get to the DDMS-Perspective in Eclipse (if A isn't visible, do B):
Image

On the Bottom you will see the so called "LOGCAT"-View appear where the Logs are written to.

Here switch to the File Explorer.
Image


The file is now located in the following folder on your emulator: "/data/data/your_project_package_structure/files/samplefile.txt"
(added it above)

Regards,
plusminus
rtheman
Freshman
Freshman
 
Posts: 4
Joined: Wed Nov 28, 2007 9:46 pm

Postby plusminus » Thu Dec 20, 2007 4:34 pm

Hello rtheman,

we already have:

Let us know if your are still missing sth. :)

Regards,
plusminus
Last edited by plusminus on Thu Dec 20, 2007 11:43 pm, edited 1 time in total.
Image
Image | Android Development Community / Tutorials
User avatar
plusminus
Site Admin
Site Admin
 
Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

error and can't parse from XML

Postby rtheman » Thu Dec 20, 2007 11:23 pm

Thanks "+ -",

Sorry if this is a dumb question, but I'm getting the following error, "ctx cannot be resolved"

Lastly, can you direct me or a sample parse statement? I tried following the code in http://www.anddev.org/viewtopic.php?p=1091#1091, but no luck

Thanks and hope you can shed some light for this newbie.

Code for Import_XML.java
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package caasd.mitre.Import_XML;
  2.  
  3. import org.xmlpull.v1.XmlPullParser;
  4.  
  5. import android.app.Activity;
  6. import android.os.Bundle;
  7.  
  8.  
  9. public class Import_XML extends Activity {
  10.     // Called when the activity is first created.
  11.     @Override
  12.     public void onCreate(Bundle icicle) {
  13.         super.onCreate(icicle);
  14.         setContentView(R.layout.main);
  15.        
  16.         // Get XML
  17.         XmlPullParser xpp = ctx.getResource().getXml(R.xml.sample);
  18.        
  19.         int eventType = xpp.getEventType();
  20.        
  21.         while (eventType != XmlPullParser.END_DOCUMENT)
  22.         {
  23.                 if (eventType == XmlPullParser.START_TAG)
  24.                         {
  25.                                 // parse stuff
  26.                         }
  27.                 else if (eventType == XmlPullParser.END_TAG)
  28.                         {
  29.                                 // parse stuff
  30.                         }
  31.                 eventType = xpp.next();
  32.         }
  33.     }
  34. }
  35.  
Parsed in 0.039 seconds, using GeSHi 1.0.8.4



plusminus wrote:Hello rtheman,

we already have:

Let us know if your are still missing sth. :)

Regards,
plusminus viewtopic.php?p=1091#1091
rtheman
Freshman
Freshman
 
Posts: 4
Joined: Wed Nov 28, 2007 9:46 pm

Postby plusminus » Thu Dec 20, 2007 11:49 pm

Hey rtheman,

I recently used a SAX-Parser which worked perfect. Used it to do some cool Google-API stuff, which I will release in a Tutorial tomorrow. As it is a tiny bit more code than those before :)

But I love it :!: :!: :!:

Used code like this:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.         SAXParserFactory spf = SAXParserFactory.newInstance();
  2.  
  3.         SAXParser sp = spf.newSAXParser();
  4.  
  5.                                        
  6.  
  7.         XMLReader xr = sp.getXMLReader();
  8.  
  9.         xr.setContentHandler(new CUSTOMHANDLER());
  10.  
  11.         xr.parse(new InputSource(INPUT_STREAM));
Parsed in 0.036 seconds, using GeSHi 1.0.8.4


Regards,
plusminus[syntax="java"]
Image
Image | Android Development Community / Tutorials
User avatar
plusminus
Site Admin
Site Admin
 
Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

read file

Postby igal » Thu Dec 27, 2007 10:18 pm

When I write and read file in the same activity everything is OK.
But when I try to read file from another activity I get "File not found" error.
I do use MODE_WORLD_READABLE option when I write the file, and I do see the file:
"/data/data/com.myname.android/files/JScript.htm"
I use
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. FileInputStream fIn = openFileInput("/data/data/com.myname.android/files/JScript.htm")
Parsed in 0.035 seconds, using GeSHi 1.0.8.4

statement.
Help, please, to find mistake.
Thanks in advance.
igal
Freshman
Freshman
 
Posts: 2
Joined: Sun Dec 16, 2007 7:51 pm

Top
Next

Return to Novice Tutorials

Who is online

Users browsing this forum: No registered users and 6 guests