- How to write text data to files in Android: Build a ScratchPad (memo) App
- Building the interface of the scratchpad app in Android
- Widgets Required
- Creating the layout using XML
- Changing the colours of the App
- Coding the actual functionality of our Scratchpad app
- Adding widgets to the code
- How to handle file input and output operations in Android
- Writing to a private .txt file in Android
- Reading from a private .txt file in Android
- Code explanation
- Implementing the save functionality
- Testing the Scratchpad App
- How to view the contents of a private .txt file in Android?
- Complete Code for the Scratchpad App
- activity_main.xml
- colors.xml
- Java File
- Leave a Reply Cancel reply
- Write text to file android
How to write text data to files in Android: Build a ScratchPad (memo) App
What will you learn?
In this simple app, you will learn how to enter a string of text into a file and save it using a button. Next time you open the app, it will still be there.
You will also learn the concept of file handling in Android. File Handling is one of the methods to make your data ‘persist’. This saves your data to a file so that it exists even after the app is closed.
The classes and methods you will learn in this are:
- OutputStreamWriter
- InputStreamReader
- openFileInput()
- openFileOutput()
Note: Find the full code of this scratchpad project towards the end of the post. Read the entire post for further clarification and explanations.
Building the interface of the scratchpad app in Android
In this app, we’ll be working with a single activity. Let’s move forward to the designing part. As you might have observed earlier, the designing part of an activity is done using XML. Don’t worry if you don’t know XML. Android Studio provides an intuitive drag and drop interface to design app visuals. I’ll be illustrating the code part of it since it is easy to explain in a textual tutorial.
Widgets Required
This is a pretty straightforward app that allows the user to write something down and save it. So we just require two widgets:
- EditText
- Button
- The EditText allows the user to enter text input.
- The Button will be used to save the text in a txt file. If the txt file doesn’t exist, then we will create it.
Creating the layout using XML
Open up the activity_main.xml file, and head over to the Text tab (bottom left corner).
You’ll see the following default code:
Now we’ll add the widgets in between the android tag.
First, the EditText. Ideally, it should be big and have lots of space since it is the main part of our app. Write down the following:
Now, for the Button, add the following code right after the EditText code.:
We’ve added two widgets: EditText and Button. EditText allows the user to enter text input; it could be anything – email, password, numeric input etc.
Button provides a clickable interface for performing certain actions.
You’ll observe a lot of attributes here, here is a description of what they do:
- constraintBottom, constraintTop etc. : These attributes are specific to elements in a ConstraintLayout. Basically, they are used to set the constraints (boundaries), positioning of elements relative to each other. If you don’t remember the layouts, then it is highly recommended that you read about the different layouts in Android.
- marginLeft, marginRight, etc.: They are used to set the margins for the element.
- layout_width, layout_height: They are used to set the size (height and width) of the element. wrap_content is used to indicate that the size should be adjusted as per the content (text, image, etc.) of the element.
- hint: The hint attribute is used in EditText to add a placeholder. It lets the user know that that’s a clickable field.
- ID: This is used to give a unique identifier to the widget; this is important as it is used to reference these widgets in the Java code. Remember, the Java code has no knowledge of this XML code by default; we need to set it up so that it can recognize elements.
- inputType: Specifies the type of input (email, password, numeric, etc.) in the EditText. We have set the inputType attribute of the EditText to ‘textMultiLine’; this will allow the user to input multiple lines of text.
The end result of the above few lines of code will look like this: This is what the app would look like
Changing the colours of the App
Additionally, let’s change the colours to the app, these will be visible on the title bar when we run the app, and when the EditText is selected. Head over to res/values/colors.xml. Location of the colors.xml file
Replace the default code with the following:
Coding the actual functionality of our Scratchpad app
Now we’ll get down to the actual coding part. Open up the MainActivity.java file.
Adding widgets to the code
Let’s start adding our widgets to the code. Write the following code inside the main function before the onCreate() function. If you gave it a name other than MainActivity, that will be the main function:
Now we’ll reference the actual widgets from the XML file. Write this below setContentView(R.layout.activity_main); inside onCreate() function.
Remember the IDs we had assigned to the widgets in the XML file? They are used here, to connect the Java code to the XML code components. This will set up our widgets.
How to handle file input and output operations in Android
Now, we’ll define two methods to read and write data to files: readFromFile() and writeToFile().
As the name suggests, readFromFile() will be used to read the data from the file, and writeToFile() will be used to write to the file. If the file doesn’t exist, writeToFile() also creates the file in the memory.
The File that we have been talking about will be a .txt file in private mode so that only this App can access it. The code is as follows:
Writing to a private .txt file in Android
We create a new function and assign it a name. In this particular tutorial, we have given it the name writeToFile(). The code for this goes right after the onCreate() function is closed.
Reading from a private .txt file in Android
After we have written code for writing to a file, we will write the code to read from the .txt file. This is how it goes down:
Code explanation
- The file that we are reading from and writing to is ‘todolist.txt’. The methods openFileInput() and openFileOutput() are used to open the file for reading and writing, respectively.
- The method openFileOutput() has the following signature: public abstract FileOutputStream openFileOutput (String name, int mode), where name is a String indicating the file name and mode is an Integer flag that indicates how the file should be opened. This method opens a file for writing and creates a new file if it doesn’t exist. The different modes are as follows:
MODE_PRIVATE: The default mode, where the created file can only be accessed by the calling application (or all applications sharing the same user ID).
MODE_WORLD_READABLE: (Deprecated) Allows all other applications to have read access to the created file.
MODE_WORLD_WRITEABLE: (Deprecated) Allows all other applications to have write access to the created file.
MODE_APPEND: If the file already exists then write data to the end of the existing file instead of erasing it.
- In these methods, we use OutputStreamWriter and InputStreamReader classes, which are used for File I/O. These are predefined classes in Android, and that’s why we first create an object of that class. From documentation:
“An OutputStreamWriter is a bridge from character streams to byte streams: Characters written to it are encoded into bytes using a specified charset. The charset that it uses may be specified by name or maybe given explicitly, or the platform’s default charset may be accepted.
Each invocation of a write() method causes the encoding converter to be invoked on the given character(s). The resulting bytes are accumulated in a buffer before being written to the underlying output stream. The size of this buffer may be specified, but by default, it is large enough for most purposes. Note that the characters passed to the write() methods are not buffered.”
“An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset. The charset that it uses may be specified by name or maybe given explicitly, or the platform’s default charset may be accepted.
Each invocation of one of an InputStreamReader’s read() methods may cause one or more bytes to be read from the underlying byte-input stream. To enable the efficient conversion of bytes to characters, more bytes may be read ahead from the underlying stream than are necessary to satisfy the current read operation.”
Link: https://developer.android.com/reference/java/io/InputStreamReader
- These are the classes used to read from and write to files. To read from files, we use the BufferedReader class to read from files easily, without getting conversion issues.
- The write() method of OutputStreamWriter is used to write to files.
- The readLine() method of BufferedReader is used to read a line of text from the file.
- It is very important to close the Input or Output stream after I/O operations. Hence, the close() button is used to do that.
Implementing the save functionality
Now we’ll implement the saving of text written in the EditText, by clicking the save button.
We’ll also add a Toast message to let the user know that their text has been saved.
A Toast is a small popup that appears at the bottom of the screen for a short duration. Write the following in the onCreate() function in MainActivity.java:
setOnClickListener() is used to set up click events. Here, we have used it to call the method for saving the text into the file, whenever the button is clicked.
We need to read from the file as well, whenever the app opens. Write the following in the onCreate() function of MainActivity.java:
The coding part ends here. Now let us test our app.
Testing the Scratchpad App
Let’s now move forward and run the app. Hit the run icon (Green Play button on top). The app will build, and you should see the following: Final Look of the App
Type in some text, and hit the save button.
Hit the back button to close the app. After Typing Text and Hitting the Save Button
Now, reopen the app (Find the app icon in the app menu on the phone). After Reopening the App
Voila! It’s still there.
We have built a fully functional scratchpad app. Go ahead and use it to jot down some notes!
How to view the contents of a private .txt file in Android?
Since we have created the file in Private mode, it cannot be accessed directly. It will not be visible to any other application other than this App. However, if we want to view the contents of this file, we can do that in the command line. The steps are as follows:
- Run the emulator. This is very important since the commands won’t run without a running emulator instance.
- Navigate to the [android-sdk]/platform-tools folder and run the following commands (Replace your-package-name with the package name of your app, it is the first line in MainActivity.java file):
You should now see the contents of the file in your command line window. Viewing the Contents of the File using Command Line
Complete Code for the Scratchpad App
activity_main.xml
colors.xml
Java File
Don’t forget to replace the package name with your package name if you are going to copy this entire code!
Android Studio auto-generates most of the code in the beginning. So, you only need to add the additional code. No need to change the already present code.
About the author
Undergraduate student pursuing B.Tech in Information Technology from MSIT, Delhi. An aspiring Android Developer who loves to stay up to date about the latest trends in technology.
Back to course page
Share and Support
Leave a Reply Cancel reply
This site uses Akismet to reduce spam. Learn how your comment data is processed.
Источник
Write text to file android
Android supports all the standard Java file I/O APIs for create, read, update, and delete (CRUD) operations, along with some additional helpers to make accessing those files in specific locations a little more convenient. There are three main locations in which an application can work with files:
- Internal storage. Protected directory space to read and write file data. Internal storage is always located in the device’s flash memory area — part of the 8 GB or 32 GB of «storage» that your device was advertised with—under /data/data/PKG_NAME/.
- External storage. Externally mountable space to read and write file data. Requires the WRITE_EXTERNAL_STORAGE permission in API Level 4+. Often, this is a physical SD card in the device.
- Assets. Protected read-only space inside the APK bundle. Good for local resources that can’t or shouldn’t be compiled.
However, there are several complications.
First, some devices don’t have removable storage. On these, the external storage directory always exists—it is just in a different partition of the same flash memory storage as internal storage.
Second, on devices that do have removable storage, the storage might be removed at the time your application checks it. There’s no point trying to write it if it’s not there.
Read from res directory
If your application requires external file resources, you can include them in your distribution package by placing them in the res/raw folder of your project hierarchy.
To access these read-only file resources, call the openRawResource method from your application’s Resource object to receive an InputStream based on the specified file. Pass in the filename (without the extension) as the variable name from the R.raw class, as shown in the following code
Read from assets directory
Android offers one more directory where you can keep files which also will be included in package. This directory called /assets. There are some difference from res directory.
With resources, there’s built-in support for providing alternatives for different languages, OS versions, screen orientations, etc., as described here. None of that is available with assets. Also, many parts of the API support the use of resource identifiers. Finally, the names of the resources are turned into constant field names that are checked at compile time, so there’s less of an opportunity for mismatches between the code and the resources themselves. None of that applies to assets.source
Read/Write to Internal Storage
This area of storage is sort of private to the application. It is always available to the application and gets purged when the app is uninstalled by the user.
Internal storage refers to the hard drive on device. Internal storage gives you the ability to prevent other applications from accessing the files you save and are tied directly to your app.
Files stored in /data/data/packagename/files/filename.txt. There are few modes for file access
- MODE_PRIVATE — create a new file or overwrite one if it already exists with the same name
- MODE_APPEND — create the file if it doesn’t exist and allow you to append to the file if it does exist
- MODE_WORLD_READABLE — file is readable by any other application
- MODE_WORLD_WRITEABLE — file is writeable by any other application
Internal storage can be accessed using the Context methods openFileInput(String filename) , which returns a FileInputStream object, or openFileOutput(String filename, int mode) , which returns a FileOutputStream .
Write to file in internal storage
Read from file in internal storage
The Context method getFilesDir() returns the root of this directory, and you can then access it using normal java.io methods and classes.
Data is written to the file streams as bytes, so higher-level data (even strings) must be converted into and out of this format.
Following is a method to save an image to internal storage in Kotlin
Read/Write to SDCard
The key differentiator between internal and external storage is that external storage is mountable. This means that the user can connect his or her device to a computer and have the option of mounting that external storage as a removable disk on the PC. Often, the storage itself is physically removable (such as an SD card), but this is not a requirement of the platform.
External storage is typically either a removable storage media (i.e. SD Card) or an internal non-removable storage that is accessed in the same manner.
The most important thing to remember when storing files on external storage is that no security is enforced on files stored here. Any application can access, overwrite, or delete files stored on the external storage.
In order to write data to SDCard, the application need permission WRITE_EXTERNAL_STORAGE, which can be specified in the file AndroidManifest.xml.
Check external storage
Write to SDCard
Read from SDCard
Following is a method to save an image to external storage in Kotlin
Read/Write to Cache
Should your application need to cache temporary files, Android offers both a managed internal cache, and (since Android API level 8) an unmanaged external cache. You can access them by calling the getCacheDir and getExternalCacheDir methods, respectively, from the current Context.
Files stored in either cache location will be erased when the application is uninstalled. Files stored in the internal cache will potentially be erased by the system when it is running low on available storage; files stored on the external cache will not be erased, as the system does not track available storage on external media.
Read from cache dir
Write to cache dir
Read/Write to publicly readable files
Android 2.2 (API level 8) includes a convenience method, Environment.getExternalStoragePublicDirectory , that can be used to find a path in which to store your application files. The returned location is where users will typically place and manage their own files of each type. Files that’ll remain on the storage even after the application is uninstalled by the user like media (photos, videos, etc.) or other downloaded files. This is particularly useful for applications that provide functionality that replaces or augments system applications, such as the camera, that store files in standard locations.
There are 2 methods that we can use to get the public external storage directory for placing files:
- getExternalStorageDirectory() method returns the primary (top-level or root) external storage directory.
- getExternalStoragePublicDirectorty method returns a top level public external storage directory for showing files of a particular type based on the argument passed. So basically the external storage has directories like Music, Podcasts, Pictures, etc. whose paths can be determined and returned via this function by passing the appropriate environment constants.
The getExternalStoragePublicDirectory method accepts a string parameter that determines which subdirectory you want to access using a series of Environment static constants:
- DIRECTORY_DCIM — pictures and videos taken by the device
- DIRECTORY_DOWNLOADS — files downloaded by the user
- DIRECTORY_MOVIES — movies
- DIRECTORY_MUSIC — audio fi les that represent music
- DIRECTORY_PICTURES — pictures
Note that if the returned directory doesn’t exit, you must create it before writing fi les to the directory, as shown in the following snippet
External System Directories
There are additional methods in Environment and Context that provide standard locations on external storage where specific files can be written. Some of these locations have additional properties as well.
- API Level 8
- Returns a common directory where all applications store media files. The contents of these directories are visible to users and other applications. In particular, the media placed here will likely be scanned and inserted into the device’s MediaStore for applications such as the Gallery.
- Valid type values include DIRECTORY_PICTURES , DIRECTORY_MUSIC , DIRECTORY_MOVIES , and DIRECTORY_RINGTONES .
- API Level 8
- Returns a directory on external storage for media files that are specific to the application. Media placed here will not be considered public, however, and won’t show up in MediaStore .
- This is external storage, however, so it is still possible for users and other applications to see and edit the files directly: there is no security enforced.
- Files placed here will be removed when the application is uninstalled, so it can be a good location in which to place large content files the application needs that one may not want on internal storage.
- Valid type values include DIRECTORY_PICTURES , DIRECTORY_MUSIC , DIRECTORY_MOVIES , and DIRECTORY_RINGTONES .
- API Level 8
- Returns a directory on internal storage for app-specific temporary files. The contents of this directory are visible to users and other applications.
- Files placed here will be removed when the application is uninstalled, so it can be a good location in which to place large content files the application needs that one may not want on internal storage.
Context.getExternalFilesDirs() and Context.getExternalCacheDirs() .
- API Level 19
- Identical features as their counterparts described previously, but returns a list of paths for each storage volume on the device (primary and any secondary volumes)
- For example, a single device may have a block of internal flash for primary external storage, and a removable SD card for secondary external storage.
- API Level 21
- Files placed in these volumes will be automatically scanned and added to the device’s media store to expose them to other applications. These will generally also be visible to the user through core applications like the Gallery.
Sharing files via a FileProvider
Sometimes you want to share internal-storage files with another app, without the bother of putting the data into a Cursor and creating a ContentProvider.
The FileProvider class allows you to make files available to another application, usually in response to an Intent. It is simpler to set up than a ContentProvider , but is actually a subclass of ContentProvider .
This example exposes a photo.jpg file from one application to another. For this example I have created an Android Studio project called FileProviderDemo , which contains two different applications in two different packages, providerapp and requestingapp . We’ll start by discussing the Provider app since it contains the actual FileProvider . However, you have to run the Requester application first, as it will start the Provider app.
Unlike the ContentProvider case, you rarely have to write code for the provider itself; instead, use the FileProvider class directly as a provider in your AndroidManifest.xml file, as shown in following example.
The provider definition
The provider does not have to be exported for this usage, but must have the ability to grant Uri permissions as shown. The meta-data element gives the name of a simple mapping file, which is required to map «virtual paths» to actual paths, as shown.
The filepaths.xml file
Finally, there has to be an Activity to provide the Uri to the requested file. In our example this is the ProvidingActivity , shown in following example.
The important part of this code is in the provideFile() method, which:
- Creates a Uri for the actual file (in this trivial example there is only one file, with a hardcoded filename)
- Adds flags to the result Intent to let the receiving app read this one file (only) with our permissions
- Sets the MIME type of the result
- Adds the file Uri as data to the result Intent
- Sets the result Intent , and the «success» flags to Activity.RESULT_OK • Calls finish() to end the Activity
Remember that the point of the FileProvider is to share files from one application to another, running with different user permissions. Our second application also has only one Activity , the «requesting» Activity. Most of this is pretty standard boilerplate code. In onCreate() , we create the requesting Intent :
The main part of the UI is a text area, which initially suggests that you request a file by pressing the button. That button’s action listener is only one line:
This will result in a subsequent call to onActivityComplete() , which is shown in following example.
Assuming that the request succeeds, you will get called here with requestCode set to the only valid action, RESULT_OK , and the resultIntent being the one that the providing Activity set as the Activity result—that is, the Intent wrapping the Uri that we need in order to read the file! So we just get the Uri from the Intent and open that as an input stream, and we can read the «secret» file from the providing application’s otherwise — private internal storage.
How to check free and used space in internal and external storage
There is auxiliary class to get information about free and used space in internal and external storage
How to download photo from url and save to storage
To download photo from url you can use android-async-http.
How to get file extension and mime type
You can get file extension and mime type:
Method to save an image to gallery and return URI in Kotlin
Источник