andbook!.pdf - Learning Android Get an anddev.org - Android-Shirt Back to index
anddev.org Header Logo
FAQ Search Top rated articles Browse Feeds anddev.org - Authors Contact Details Register Log in

Working with Files

Goto page 1, 2, 3, 4, 5  Next
 
       anddev.org - Android Development Community | Android Tutorials | Index -> Novice Tutorials
Author Message
plusminus
Site Admin
Site Admin


Joined: 14 Nov 2007
Posts: 2660
Location: College Park, MD

PostPosted: Tue Nov 27, 2007 12:45 am    Post subject: Working with Files Reply with quote

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.

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

Difficulty: 1 of 5 Smile

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


Description:
To understand why we cannot use standard java file access, like:
Java:
FileWriter f = new FileWriter("impossible.txt");
// throws: 'java.io.FileNotFoundException: /impossible.txt '

, 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 Evil 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 Exclamation
Java:
FileWriter f = new FileWriter("/sdcard/download/possible.txt");

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...
Java:
       try { // catches IOException below
               final String TESTSTRING = new String("Hello Android");
               
               // ##### Write a file to the disk #####
               /* We have to use the openFileOutput()-method
                * the ActivityContext provides, to
                * protect your file from others and
                * This is done for security-reasons.
                * We chose MODE_WORLD_READABLE, because
                *  we have nothing to hide in our file */
        
               FileOutputStream fOut = openFileOutput("samplefile.txt",
                                        MODE_WORLD_READABLE);
               OutputStreamWriter osw = new OutputStreamWriter(fOut)

               // Write the string to the file
               osw.write(TESTSTRING);
               /* ensure that everything is
                * really written out and close */

               osw.flush();
               osw.close();

2.Reading the file back...
Java:
               // ##### Read the file back in #####
               
               /* We have to use the openFileInput()-method
                * the ActivityContext provides.
                * Again for security reasons with
                * openFileInput(...) */

               FileInputStream fIn = openFileInput("samplefile.txt");
               InputStreamReader isr = new InputStreamReader(fIn);
               /* Prepare a char-Array that will
                * hold the chars we read back in. */

               char[] inputBuffer = new char[TESTSTRING.length()];
               // Fill the Buffer with data from the file
               isr.read(inputBuffer);
               // Transform the chars to a String
               String readString = new String(inputBuffer);
               
               // Check if we read back the same chars that we had written out
               boolean isTheSame = TESTSTRING.equals(readString);

               // WOHOO lets Celebrate =)
               Log.i("File Reading stuff", "success = " + isTheSame);

          } catch (IOException ioe) {
               ioe.printStackTrace();
          }


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:

Java:
public boolean deleteFile(String name)
// Delete the given private file associated with this Context's application package.


Regards,
plusminus

_________________
Download my apps Idea
Please remember, that this board is give & take Smile


| Android Development Community / Tutorials


Last edited by plusminus on Mon Dec 17, 2007 4:34 pm; edited 5 times in total
Back to top
View user's profile Send private message Send e-mail Visit poster's website
fresco
Junior Developer
Junior Developer


Joined: 18 Nov 2007
Posts: 24

PostPosted: Tue Nov 27, 2007 4:56 pm    Post subject: Reply with quote

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.

Java:
FileWriter f = new FileWriter("/sdcard/download/impossible.txt");
will work without any problem, you just need to add virtual sdcard to your emulator.
Back to top
View user's profile Send private message
plusminus
Site Admin
Site Admin


Joined: 14 Nov 2007
Posts: 2660
Location: College Park, MD

PostPosted: Tue Nov 27, 2007 6:08 pm    Post subject: Reply with quote

Thanks fresco,

added it above Exclamation

Regards,
plusminus

_________________
Download my apps Idea
Please remember, that this board is give & take Smile


| Android Development Community / Tutorials
Back to top
View user's profile Send private message Send e-mail Visit poster's website
rtheman
Freshman
Freshman


Joined: 28 Nov 2007
Posts: 4

PostPosted: Fri Nov 30, 2007 10:56 pm    Post subject: where's the log written at? Reply with quote

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
Back to top
View user's profile Send private message
plusminus
Site Admin
Site Admin


Joined: 14 Nov 2007
Posts: 2660
Location: College Park, MD

PostPosted: Sat Dec 01, 2007 11:00 am    Post subject: Reply with quote

Hello rtehman,

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


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

Here switch to the File Explorer.


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

_________________
Download my apps Idea
Please remember, that this board is give & take Smile


| Android Development Community / Tutorials
Back to top
View user's profile Send private message Send e-mail Visit poster's website
Gamby
Freshman
Freshman


Joined: 26 Nov 2007
Posts: 7
Location: Italy

PostPosted: Wed Dec 12, 2007 11:28 pm    Post subject: Other file operations? Reply with quote

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:

Java:

if (files[i].equals("samplefile.txt")) {
                    File f = new File("files", files[i]);
                   
                    if (f.exists()) {
                        Log.v(TAG, "File exists! " + f.getAbsolutePath());
                    }
                    else {
                        Log.v(TAG, "File NOT exists! " + f.getAbsolutePath());
                    }
                   
                    if (f.delete()) {
                        Log.v(TAG, "File deleted!");
                    }
                    else {
                        Log.v(TAG, "File NOT deleted! " + f.getAbsolutePath());
                    }
                }


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
Back to top
View user's profile Send private message MSN Messenger
plusminus
Site Admin
Site Admin


Joined: 14 Nov 2007
Posts: 2660
Location: College Park, MD

PostPosted: Wed Dec 12, 2007 11:36 pm    Post subject: Reply with quote

Hello gamby,

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

Java:
public boolean deleteFile(String name)
// Delete the given private file associated with this Context's application package.


Added it above, too.

Regards,
plusminus

_________________
Download my apps Idea
Please remember, that this board is give & take Smile


| Android Development Community / Tutorials
Back to top
View user's profile Send private message Send e-mail Visit poster's website
Gamby
Freshman
Freshman


Joined: 26 Nov 2007
Posts: 7
Location: Italy

PostPosted: Wed Dec 12, 2007 11:41 pm    Post subject: Reply with quote

Thank you very much plusminus!

And what about these other quqestions, can you help me to understand?
Quote:
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
Back to top
View user's profile Send private message MSN Messenger
plusminus
Site Admin
Site Admin


Joined: 14 Nov 2007
Posts: 2660
Location: College Park, MD

PostPosted: Wed Dec 12, 2007 11:47 pm    Post subject: Reply with quote

Smile should have had a closer look ^^

it depends on how you have created the file Exclamation
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

_________________
Download my apps Idea
Please remember, that this board is give & take Smile


| Android Development Community / Tutorials
Back to top
View user's profile Send private message Send e-mail Visit poster's website
Gamby
Freshman
Freshman


Joined: 26 Nov 2007
Posts: 7
Location: Italy

PostPosted: Wed Dec 12, 2007 11:56 pm    Post subject: Reply with quote

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
Back to top
View user's profile Send private message MSN Messenger
rtheman
Freshman
Freshman


Joined: 28 Nov 2007
Posts: 4

PostPosted: Thu Dec 20, 2007 3:54 pm    Post subject: Thanks - more example for pulling in data? Reply with quote

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):


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

Here switch to the File Explorer.


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
Back to top
View user's profile Send private message
plusminus
Site Admin
Site Admin


Joined: 14 Nov 2007
Posts: 2660
Location: College Park, MD

PostPosted: Thu Dec 20, 2007 4:34 pm    Post subject: Reply with quote

Hello rtheman,

we already have:


Let us know if your are still missing sth. Smile

Regards,
plusminus

_________________
Download my apps Idea
Please remember, that this board is give & take Smile


| Android Development Community / Tutorials


Last edited by plusminus on Thu Dec 20, 2007 11:43 pm; edited 1 time in total
Back to top
View user's profile Send private message Send e-mail Visit poster's website
rtheman
Freshman
Freshman


Joined: 28 Nov 2007
Posts: 4

PostPosted: Thu Dec 20, 2007 11:23 pm    Post subject: error and can't parse from XML Reply with quote

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
Java:

package caasd.mitre.Import_XML;

import org.xmlpull.v1.XmlPullParser;

import android.app.Activity;
import android.os.Bundle;


public class Import_XML extends Activity {
    // Called when the activity is first created.
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
       
        // Get XML
        XmlPullParser xpp = ctx.getResource().getXml(R.xml.sample);
       
        int eventType = xpp.getEventType();
       
        while (eventType != XmlPullParser.END_DOCUMENT)
        {
          if (eventType == XmlPullParser.START_TAG)
               {
                    // parse stuff
               }
          else if (eventType == XmlPullParser.END_TAG)
               {
                    // parse stuff
               }
          eventType = xpp.next();
        }
    }
}



plusminus wrote:
Hello rtheman,

we already have:


Let us know if your are still missing sth. Smile

Regards,
plusminus http://www.anddev.org/viewtopic.php?p=1091#1091
Back to top
View user's profile Send private message
plusminus
Site Admin
Site Admin


Joined: 14 Nov 2007
Posts: 2660
Location: College Park, MD

PostPosted: Thu Dec 20, 2007 11:49 pm    Post subject: Reply with quote

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 Smile

But I love it Exclamation Exclamation Exclamation

Used code like this:
Java:
     SAXParserFactory spf = SAXParserFactory.newInstance();
     SAXParser sp = spf.newSAXParser();
                         
     XMLReader xr = sp.getXMLReader();
     xr.setContentHandler(new CUSTOMHANDLER());
     xr.parse(new InputSource(INPUT_STREAM));


Regards,
plusminus[syntax="java"]

_________________
Download my apps Idea
Please remember, that this board is give & take Smile


| Android Development Community / Tutorials
Back to top
View user's profile Send private message Send e-mail Visit poster's website
igal
Freshman
Freshman


Joined: 16 Dec 2007
Posts: 2

PostPosted: Thu Dec 27, 2007 10:18 pm    Post subject: read file Reply with quote

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
Java:
FileInputStream fIn = openFileInput("/data/data/com.myname.android/files/JScript.htm")

statement.
Help, please, to find mistake.
Thanks in advance.
Back to top
View user's profile Send private message
Display posts from previous:   
       anddev.org - Android Development Community | Android Tutorials | Index -> Novice Tutorials All times are GMT + 1 Hour
Goto page 1, 2, 3, 4, 5  Next
Page 1 of 5

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You cannot attach files in this forum
You can download files in this forum


© 2007, Android Development Community
All rights reserved.
Powered by phpBB.