SlideShare ist ein Scribd-Unternehmen logo
1 von 21
Assets, Files, and Data Parsing
Sk. Arman Ali
Software Engineer at
W3Engineers Ltd.
Assets, Files, and Data Parsing
● Android offers a few structured ways to store data, notably
SharedPreferences and local SQLite databases.
● And, of course, you are welcome to store your data “in the
cloud” by using an Internet-based service.
● Beyond that, though, Android allows you to work with plain old
ordinary files, either ones baked into your app (“assets”) or
ones on so-called internal or external storage.
Assets, Files, and Data Parsing
● To make those files work — and to consume data off of the
Internet — you will likely need to employ a parser. Android
ships with several choices for XML and JSON parsing, in
addition to third-party libraries you can attempt to use.
● This session focuses on Assets,Raw, and Files.
Packaging Files with Your App
● Let’s suppose you have some static data you want to ship
with the application, such as a list of words for a spell-
checker.
● Somehow, you need to bundle that data with the
application, in a way you can get at it from Java code
later on, or possibly in a way you can pass to another
component (e.g., WebView for bundled HTML files).
● There are three main options here: raw resources, XML
resources, and assets.
Raw Resources
● One way to deploy a file like a spell-check catalog is to put the
file in the res/raw directory, so it gets put in the Android
application .apk file as part of the packaging process as a raw
resource.
● To access this file, you need to get yourself a Resources object.
InputStream inputStream = getResources().openRawResource(R.raw.activity_main);
XML Resources
● If, however, your file is in an XML format, you are better served
not putting it in res/raw/, but rather in res/xml/.
● This is a directory for XML resources – resources known to be
in XML format.
● To access that XML, you once again get a Resources object by
calling getResources() on your Activity or other Context.
XmlResourceParser xmlResourceParser = getResources().getXml(R.xml.test);
Assets
● Your third option is to package the data in the form of an asset.
● You can create an assets/ directory in your source set (e.g.,
src/main/assets), then place whatever files you want in there.
● Those are accessible at runtime by calling getAssets() on your
Activity or other Context, then calling open() with the path to
the file (e.g., assets/foo/index.html would be retrieved via
open("foo/index.html")).
InputStream inputStream = getAssets().open("foo/index.html");
Files on device storage
● Android uses a file system that's similar to disk-based file
systems on other platforms.
● All Android devices have two file storage areas: "internal" and
"external" storage.
Files on device storage
Internal storage:
● It's always available.
● Files saved here are
accessible by only your
app.
● When the user uninstalls
your app, the system
removes all your app's files
from internal storage.
External storage:
● It's not always available, because the user
can mount the external storage as USB
storage and in some cases remove it from
the device.
● It's world-readable, so files saved here
may be read outside of your control.
● When the user uninstalls your app, the
system removes your app's files from here
only if you save them in the directory from
getExternalFilesDir().
Internal Storage
● Android can save files directly to the device internal storage.
● These files are private to the application and will be removed
if you uninstall the application.
● We can create a file using openFileOutput() with parameter as
file name and the operating mode.
Internal Storage Contd…
● Similarly, we can open the file using openFileInput() passing
the parameter as the filename with extension.
● File are use to store large amount of data Use I/O interfaces
provided by java.io.* libraries to read/write files.
File Operation(Read)
● Use context.openFileInput(string name) to open a private
input file stream related to a program.
● Throw FileNotFoundException when file does not exist.
● Syntax:-
fileinputStram.in=this.openfileinput(“xyz.txt”)
. . . . .
In.close()://Close input stream
File Operation (Write)
● Use context.openFileOutput(string name,int mode ) to open a
private output file stream related to a program.
● The file will be created if it does not exist.
● Passing MODE_PRIVATE makes it private to your app.
● Output stream can be opened in append mode, which means
new data will be appended to end of the file.
File Operation (write) Contd….
● Syntax:-
String filename = "myfile";
String fileContents = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(fileContents.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
Write a cache file
● For cache some files, you should use createTempFile().
● Syntax:-
private File getTempFile(Context context, String url) {
File file;
try {
String fileName = Uri.parse(url).getLastPathSegment();
file = File.createTempFile(fileName, null, context.getCacheDir());
} catch (IOException e) {
// Error while creating file
}
return file;
}
Open a directory
● getFilesDir()
○ Returns a File representing the directory on the file system that's uniquely associated with your app.
● getDir(name, mode)
○ Creates a new directory (or opens an existing directory) within your app's unique file system directory.
● getCacheDir()
○ Returns a File representing the cache directory on the file system that's uniquely associated with your
app.
○ This directory is meant for temporary files, and it should be cleaned up regularly.
○ The system may delete files there if it runs low on disk space, so make sure you check for the
existence of your cache files before reading them.
External Storage
● Every Android-compatible device supports a shared “external
storage” that you can use to save files
○ Removable storage media (such as an SD card)
○ Internal (non-removable) storage
● File 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 computer.
● These files are private to the application and will be removed
when the application is uninstalled.
External Storage Contd...
● Must check whether external storage is available first by calling
getExternalStorageState()
○ Also check whether it allows read/write before reading/writing on it
● getExternalFilesDir() takes a parameter such as
DIRECTORY_MUSIC,DIRECTORY_RINGTONE etc,to open specific
type of subdirectories.
● For public shared directories,use
getExternalStoragePublicDirectory()
Query free space
● getFreeSpace()
○ provide the current available space
● getTotalSpace()
○ Provide the total space in the storage volume
Delete a file
● You should always delete files that your app Assets, Files,
and Data Parsing.
● The most straightforward way to delete a file is to call delete()
on the File object.
THANKS

Weitere ähnliche Inhalte

Was ist angesagt?

Chapter 10.1
Chapter 10.1Chapter 10.1
Chapter 10.1sotlsoc
 
Munching & crunching - Lucene index post-processing
Munching & crunching - Lucene index post-processingMunching & crunching - Lucene index post-processing
Munching & crunching - Lucene index post-processingabial
 
Persentation on c language
Persentation on c languagePersentation on c language
Persentation on c languageSudhanshuVijay3
 
Files & IO in Java
Files & IO in JavaFiles & IO in Java
Files & IO in JavaCIB Egypt
 
Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output ConceptsVicter Paul
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsAnton Keks
 
Information Retrieval - Data Science Bootcamp
Information Retrieval - Data Science BootcampInformation Retrieval - Data Science Bootcamp
Information Retrieval - Data Science BootcampKais Hassan, PhD
 
Ie Storage, Multimedia And File Organization
Ie   Storage, Multimedia And File OrganizationIe   Storage, Multimedia And File Organization
Ie Storage, Multimedia And File OrganizationMISY
 
Fileorganization AbnMagdy
Fileorganization AbnMagdyFileorganization AbnMagdy
Fileorganization AbnMagdyMohamed Magdy
 
File Handling
File HandlingFile Handling
File HandlingWaqar Ali
 

Was ist angesagt? (20)

File organization
File organizationFile organization
File organization
 
File structures
File structuresFile structures
File structures
 
Java I/O
Java I/OJava I/O
Java I/O
 
Chapter 10.1
Chapter 10.1Chapter 10.1
Chapter 10.1
 
Munching & crunching - Lucene index post-processing
Munching & crunching - Lucene index post-processingMunching & crunching - Lucene index post-processing
Munching & crunching - Lucene index post-processing
 
File organization
File organizationFile organization
File organization
 
Persentation on c language
Persentation on c languagePersentation on c language
Persentation on c language
 
Files & IO in Java
Files & IO in JavaFiles & IO in Java
Files & IO in Java
 
Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output Concepts
 
Handling I/O in Java
Handling I/O in JavaHandling I/O in Java
Handling I/O in Java
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
 
Lucene basics
Lucene basicsLucene basics
Lucene basics
 
Registry Forensic
Registry ForensicRegistry Forensic
Registry Forensic
 
Information Retrieval - Data Science Bootcamp
Information Retrieval - Data Science BootcampInformation Retrieval - Data Science Bootcamp
Information Retrieval - Data Science Bootcamp
 
Java IO
Java IOJava IO
Java IO
 
File handling
File handlingFile handling
File handling
 
Ie Storage, Multimedia And File Organization
Ie   Storage, Multimedia And File OrganizationIe   Storage, Multimedia And File Organization
Ie Storage, Multimedia And File Organization
 
Input output streams
Input output streamsInput output streams
Input output streams
 
Fileorganization AbnMagdy
Fileorganization AbnMagdyFileorganization AbnMagdy
Fileorganization AbnMagdy
 
File Handling
File HandlingFile Handling
File Handling
 

Ähnlich wie Assets, files, and data parsing

03 programmation mobile - android - (stockage, multithreads, web services)
03 programmation mobile - android - (stockage, multithreads, web services)03 programmation mobile - android - (stockage, multithreads, web services)
03 programmation mobile - android - (stockage, multithreads, web services)TECOS
 
Data Storage In Android
Data Storage In Android Data Storage In Android
Data Storage In Android Aakash Ugale
 
Android datastorage
Android datastorageAndroid datastorage
Android datastorageKrazy Koder
 
Windows Phone 8 - 4 Files and Storage
Windows Phone 8 - 4 Files and StorageWindows Phone 8 - 4 Files and Storage
Windows Phone 8 - 4 Files and StorageOliver Scheer
 
Windows Phone 8 - 4 Files and Storage
Windows Phone 8 - 4 Files and StorageWindows Phone 8 - 4 Files and Storage
Windows Phone 8 - 4 Files and StorageOliver Scheer
 
Cs1123 10 file operations
Cs1123 10 file operationsCs1123 10 file operations
Cs1123 10 file operationsTAlha MAlik
 
File Management and manipulation in C++ Programming
File Management and manipulation in C++ ProgrammingFile Management and manipulation in C++ Programming
File Management and manipulation in C++ ProgrammingChereLemma2
 
1 cs xii_python_file_handling text n binary file
1 cs xii_python_file_handling text n binary file1 cs xii_python_file_handling text n binary file
1 cs xii_python_file_handling text n binary fileSanjayKumarMahto1
 
WP7 HUB_Creando aplicaciones de Windows Phone
WP7 HUB_Creando aplicaciones de Windows PhoneWP7 HUB_Creando aplicaciones de Windows Phone
WP7 HUB_Creando aplicaciones de Windows PhoneMICTT Palma
 
14 file handling
14 file handling14 file handling
14 file handlingAPU
 

Ähnlich wie Assets, files, and data parsing (20)

03 programmation mobile - android - (stockage, multithreads, web services)
03 programmation mobile - android - (stockage, multithreads, web services)03 programmation mobile - android - (stockage, multithreads, web services)
03 programmation mobile - android - (stockage, multithreads, web services)
 
Data Storage In Android
Data Storage In Android Data Storage In Android
Data Storage In Android
 
Android Data Storagefinal
Android Data StoragefinalAndroid Data Storagefinal
Android Data Storagefinal
 
Android datastorage
Android datastorageAndroid datastorage
Android datastorage
 
UNIT 5.pptx
UNIT 5.pptxUNIT 5.pptx
UNIT 5.pptx
 
Memory management
Memory managementMemory management
Memory management
 
File Handling
File HandlingFile Handling
File Handling
 
File Handling
File HandlingFile Handling
File Handling
 
Windows Phone 8 - 4 Files and Storage
Windows Phone 8 - 4 Files and StorageWindows Phone 8 - 4 Files and Storage
Windows Phone 8 - 4 Files and Storage
 
Windows Phone 8 - 4 Files and Storage
Windows Phone 8 - 4 Files and StorageWindows Phone 8 - 4 Files and Storage
Windows Phone 8 - 4 Files and Storage
 
Chapter4.pptx
Chapter4.pptxChapter4.pptx
Chapter4.pptx
 
Android-data storage in android-chapter21
Android-data storage in android-chapter21Android-data storage in android-chapter21
Android-data storage in android-chapter21
 
Cs1123 10 file operations
Cs1123 10 file operationsCs1123 10 file operations
Cs1123 10 file operations
 
File Management and manipulation in C++ Programming
File Management and manipulation in C++ ProgrammingFile Management and manipulation in C++ Programming
File Management and manipulation in C++ Programming
 
1 cs xii_python_file_handling text n binary file
1 cs xii_python_file_handling text n binary file1 cs xii_python_file_handling text n binary file
1 cs xii_python_file_handling text n binary file
 
Edubooktraining
EdubooktrainingEdubooktraining
Edubooktraining
 
WP7 HUB_Creando aplicaciones de Windows Phone
WP7 HUB_Creando aplicaciones de Windows PhoneWP7 HUB_Creando aplicaciones de Windows Phone
WP7 HUB_Creando aplicaciones de Windows Phone
 
Android Data Persistence
Android Data PersistenceAndroid Data Persistence
Android Data Persistence
 
14 file handling
14 file handling14 file handling
14 file handling
 
Chapter - 5.pptx
Chapter - 5.pptxChapter - 5.pptx
Chapter - 5.pptx
 

Kürzlich hochgeladen

Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 

Kürzlich hochgeladen (20)

Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 

Assets, files, and data parsing

  • 1. Assets, Files, and Data Parsing Sk. Arman Ali Software Engineer at W3Engineers Ltd.
  • 2. Assets, Files, and Data Parsing ● Android offers a few structured ways to store data, notably SharedPreferences and local SQLite databases. ● And, of course, you are welcome to store your data “in the cloud” by using an Internet-based service. ● Beyond that, though, Android allows you to work with plain old ordinary files, either ones baked into your app (“assets”) or ones on so-called internal or external storage.
  • 3. Assets, Files, and Data Parsing ● To make those files work — and to consume data off of the Internet — you will likely need to employ a parser. Android ships with several choices for XML and JSON parsing, in addition to third-party libraries you can attempt to use. ● This session focuses on Assets,Raw, and Files.
  • 4. Packaging Files with Your App ● Let’s suppose you have some static data you want to ship with the application, such as a list of words for a spell- checker. ● Somehow, you need to bundle that data with the application, in a way you can get at it from Java code later on, or possibly in a way you can pass to another component (e.g., WebView for bundled HTML files). ● There are three main options here: raw resources, XML resources, and assets.
  • 5. Raw Resources ● One way to deploy a file like a spell-check catalog is to put the file in the res/raw directory, so it gets put in the Android application .apk file as part of the packaging process as a raw resource. ● To access this file, you need to get yourself a Resources object. InputStream inputStream = getResources().openRawResource(R.raw.activity_main);
  • 6. XML Resources ● If, however, your file is in an XML format, you are better served not putting it in res/raw/, but rather in res/xml/. ● This is a directory for XML resources – resources known to be in XML format. ● To access that XML, you once again get a Resources object by calling getResources() on your Activity or other Context. XmlResourceParser xmlResourceParser = getResources().getXml(R.xml.test);
  • 7. Assets ● Your third option is to package the data in the form of an asset. ● You can create an assets/ directory in your source set (e.g., src/main/assets), then place whatever files you want in there. ● Those are accessible at runtime by calling getAssets() on your Activity or other Context, then calling open() with the path to the file (e.g., assets/foo/index.html would be retrieved via open("foo/index.html")). InputStream inputStream = getAssets().open("foo/index.html");
  • 8. Files on device storage ● Android uses a file system that's similar to disk-based file systems on other platforms. ● All Android devices have two file storage areas: "internal" and "external" storage.
  • 9. Files on device storage Internal storage: ● It's always available. ● Files saved here are accessible by only your app. ● When the user uninstalls your app, the system removes all your app's files from internal storage. External storage: ● It's not always available, because the user can mount the external storage as USB storage and in some cases remove it from the device. ● It's world-readable, so files saved here may be read outside of your control. ● When the user uninstalls your app, the system removes your app's files from here only if you save them in the directory from getExternalFilesDir().
  • 10. Internal Storage ● Android can save files directly to the device internal storage. ● These files are private to the application and will be removed if you uninstall the application. ● We can create a file using openFileOutput() with parameter as file name and the operating mode.
  • 11. Internal Storage Contd… ● Similarly, we can open the file using openFileInput() passing the parameter as the filename with extension. ● File are use to store large amount of data Use I/O interfaces provided by java.io.* libraries to read/write files.
  • 12. File Operation(Read) ● Use context.openFileInput(string name) to open a private input file stream related to a program. ● Throw FileNotFoundException when file does not exist. ● Syntax:- fileinputStram.in=this.openfileinput(“xyz.txt”) . . . . . In.close()://Close input stream
  • 13. File Operation (Write) ● Use context.openFileOutput(string name,int mode ) to open a private output file stream related to a program. ● The file will be created if it does not exist. ● Passing MODE_PRIVATE makes it private to your app. ● Output stream can be opened in append mode, which means new data will be appended to end of the file.
  • 14. File Operation (write) Contd…. ● Syntax:- String filename = "myfile"; String fileContents = "Hello world!"; FileOutputStream outputStream; try { outputStream = openFileOutput(filename, Context.MODE_PRIVATE); outputStream.write(fileContents.getBytes()); outputStream.close(); } catch (Exception e) { e.printStackTrace(); }
  • 15. Write a cache file ● For cache some files, you should use createTempFile(). ● Syntax:- private File getTempFile(Context context, String url) { File file; try { String fileName = Uri.parse(url).getLastPathSegment(); file = File.createTempFile(fileName, null, context.getCacheDir()); } catch (IOException e) { // Error while creating file } return file; }
  • 16. Open a directory ● getFilesDir() ○ Returns a File representing the directory on the file system that's uniquely associated with your app. ● getDir(name, mode) ○ Creates a new directory (or opens an existing directory) within your app's unique file system directory. ● getCacheDir() ○ Returns a File representing the cache directory on the file system that's uniquely associated with your app. ○ This directory is meant for temporary files, and it should be cleaned up regularly. ○ The system may delete files there if it runs low on disk space, so make sure you check for the existence of your cache files before reading them.
  • 17. External Storage ● Every Android-compatible device supports a shared “external storage” that you can use to save files ○ Removable storage media (such as an SD card) ○ Internal (non-removable) storage ● File 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 computer. ● These files are private to the application and will be removed when the application is uninstalled.
  • 18. External Storage Contd... ● Must check whether external storage is available first by calling getExternalStorageState() ○ Also check whether it allows read/write before reading/writing on it ● getExternalFilesDir() takes a parameter such as DIRECTORY_MUSIC,DIRECTORY_RINGTONE etc,to open specific type of subdirectories. ● For public shared directories,use getExternalStoragePublicDirectory()
  • 19. Query free space ● getFreeSpace() ○ provide the current available space ● getTotalSpace() ○ Provide the total space in the storage volume
  • 20. Delete a file ● You should always delete files that your app Assets, Files, and Data Parsing. ● The most straightforward way to delete a file is to call delete() on the File object.