Read all text from file android

How to Read a Text File in Android?

A text file is a type of file that can store a sequence of characters or text. These characters can be anything that is human-readable. Such kind of files does not have any formatting for the text like Bold, Italics, Underline, Font, Font Size, etc. A Text file in Android can be used for accessing or reading the information or text present in it. Meaning, information could be stored in a text file and could be accessed whenever required in the run-time. So, through this article, we will show you how you could read or fetch text from a text file in Android.

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.

Step 2: Create an asset folder

Please refer to Assets Folder in Android Studio to create an assets folder in Android Studio. We shall be creating a text file in the assets folder.

Step 3: Create a text file in the asset folder

We can create a text file by simply right-clicking on the assets folder, drag the mouse on new, and click on File. Now type in some desired name, add “.txt” extension, and press Enter. Another way of doing the same is creating a text file on Desktop and simply copying it into the assets folder. This is how our text file looks like:

MyText.txt:

Step 4: Add a TextView in the layout file (activity_main.xml)

We will add a TextView in the layout to display the text from the text file.

Источник

Android Read Write Internal Storage File Example

Android data can be saved in internal storage ( ROM ), external storage(SD card), shared preferences, or SQLite database. This article will introduce how to read and write data in internal storage via a java file.

1. Android Read Write Data To Internal File.

  1. Android is based on Linux, the android file system is Linux-based also.
  2. Android studio provides the android device monitor tool for you to monitor and transfer files between Android devices and your PC. Please refer Android Device Monitor Cannot Open Data Folder Resolve Method.

1.1 Where Your Android App Internal Data File Saved In?

  1. All android app internal data files are saved in the /data/data/ folder.
  2. In this example, my app data internal file is saved in /data/data/com.dev2qa.example folder. You can watch the youtube video https://youtu.be/AJBgBBMKO5w to see the android app’s internal data files saved directory.
  3. From the youtube video, we can see that there are files and cache subfolders under the package name folder.
  4. files folder — android.content.Context’sgetFilesDir() method can return this folder. This folder is used to save general files.
  5. cache folder — android.content.Context’sgetCacheDir() method can return this folder. This folder is used to save cached files.
  6. When the device’s internal storage space is low, cache files will be removed by android os automatically to make internal storage space bigger. Generally, you need to delete the unused cache files in the source code timely, the total cache file size is better not more than 1 MB.

1.2 Read Write Android File Code Snippets.

  1. Android application is written in java, so the file operation uses java classes also.
  2. Below are the code snippets for read/write data from/to the file in android.
1.2.1 Read Android File In The Package files Folder.
  1. Call android.content.Context‘s openFileInput(userEmalFileName) method to get FileInputStream object.
  2. The input parameter is just the file name.
  3. This file should be saved in the files folder.
  4. Then use the FileInputStream object to read data.
1.2.2 Read Android File In The Package cache Folder.
  1. The below source code will read the android files in the package cache folder.
1.2.3 Write File To The Package files Folder.
  1. Method 1: Use Context’s getFilesDir() to get the package files folder, then write file into it.
  2. Method 2: Call Context’s openFileOutput(userEmalFileName, Context.MODE_APPEND) method to get FileOutputStream object.
  3. The first parameter is the file name, the second parameter’s value can be one of the below values.
  4. Context.MODE_PRIVATE: This means this file can only be read/write by this android app that creates it. This mode will overwrite an existing file, if not exist then create it.
  5. Context.MODE_APPEND: This mode will append data to an existing file. If not exist it will create a new one.
1.2.4 Write File To The Package cache Folder.
  1. Use Context’s getCacheDir() to get cache folder.

2. Android Internal File Operation Example.

  1. You can watch the example demo video on youtube https://youtu.be/HqbRR6TQVvY.
  2. There are one input text box and five buttons on the android example app main screen.
  3. The buttons’ function can be easily understood by the button’s label text.
  4. The button’s label text is WRITE TO FILE, READ FROM FILE, CREATE CACHED FILE, READ CACHED FILE, CREATE TEMP FILE from up to bottom.
  5. After you run the example, you can see the below files in the android device monitor. You can pull down the file to your local PC to see the file contents also.
  6. If you meet any problem in using the android device monitor, please refer to Android Device Monitor Cannot Open Data Folder Resolve Method. This article will tell you how to resolve those errors.
Читайте также:  Карты для geonet навигатор для андроид

2.1 Layout XML File.

  1. activity_write_read_file.xml

2.2 Activity Java File.

  1. WriteReadFileActivity.java
  2. If you meet the error message Instant Run requires ‘Tools | Android | Enable ADB integration’ to be enabled when you run this example. You can click Tools —> Android menu, and check Enable ADB integration option in the popup menu to resolve it.

3. Question & Answer.

3.1 Can not write text file to android internal storage.

  1. My android app is very simple, I just want to write some text to a file and save the text file to the internal storage. I follow this article to write source code, but I can not find the text file in both the android physical device and the simulator. I can not read the file content out in java source code. Can you tell me why? Thanks a lot.
  2. Android 11 has announced a new policy when you want to manage storage. The internal storage root folder can not be used to store files unless you add the below permission in your AndroidManifest.xml file.

And when you run the application, you can request this permission to the user with the below code.

Then you can process user response in the onRequestPermissionsResult() method in the activity.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Thanks.Great Article Guys.

I am a beginner of android programming, and I want to write some data to a file saved in android internal storage device. I found this article and write the source code as below. But I found after I write the data to internal storage file with the method writeToFile, I can not read the written file content in android internal storage device in the readFileButton method. Can you tell me what wrong in my source code? Thanks a lot.

public void writeToFile(String fileName, String fileContent)<

try <
// Create a FileOutputStream object with the provided file name.
FileOutputStream fos = openFileOutput(fileName , Context.MODE_PRIVATE);

// Write the file content to the file.
fos.write(fileContent.getBytes());

// Close the file output stream to flush the data to the file.
fos.close();
> catch (Exception e) <
e.printStackTrace();
>
>

public void readFileButton(View v) <
// Read the file text content.
try <

// Define the internal stored file name.
String fileName = “test.txt”;

// Create a FileInputStream object.
FileInputStream fis =openFileInput(fileName);

// Create a InputStreamReader object.
InputStreamReader isr = new InputStreamReader(fis);

// Define the char array.
char[] ib= new char[1024];

// Store read out file data.
String fileData = “”;

// Read 1024 character data from file.
int charRead = isr.read(ib);

// While not end of the file.
while (charRead>0) <

// Convert the char array to a string object.
String readstring = String.copyValueOf(inputBuffer,0,charRead);

// Add the read out file data.
fileData +=readstring;

Источник

Android File IO Tutorial with Internal and External Storage

In this tutorial I will cover how to create files in various methods in Android such as Internal Storage, External Storage, the MediaStore API and the Storage Access Framework.

I will explain the differences between each of these file storage methods and provide some context on when to use each.

I will also cover some details on the Scoped Storage privacy feature released in Android 10 and enhanced in Android 11 for files created by your app in external storage.

I will share code samples in this tutorial and I have also published all the code from this tutorial in the GitHub repository in the link below.

Android Internal File Storage Tutorial

This section of the post contains a tutorial on how to use internal storage in Android. We will cover the following topics in our tutorial on the use of internal storage in Android.

  • What is Internal Storage in Android?
  • How to Create a Text File Programmatically in Internal Storage in Android
  • How to Write Text to a File Programmatically in Internal Storage in Android
  • How to Read Text from a File Programmatically in Internal Storage in Android
  • How to Delete a Text File Programmatically from Internal Storage in Android
  • How to View Files in Internal Storage using the Android Device File Explorer
  • How to Remove Files from Internal Storage using the Android Storage Utility

Please see a screen capture below of the Android app of what we will be creating in this tutorial.

What is Internal Storage in Android?

Internal Storage in Android is used for storing files that are only visible to your app. No permissions are required to read or write files to internal storage for your app. If your app is uninstalled with files in internal storage, these files will be deleted as a part of the uninstallation process.

Files in internal storage in Android can either be persistent files or cache files.

Cache files are stored in internal storage as temporary files, they will get deleted when the user uninstalls the app but they can also be deleted before then by the Android system clearing space in storage or by deleting the cache file programmatically. Unlike cache files, persistent files in internal storage cannot be deleted by the Android system automatically.

How to Create a Text File Programmatically in Internal Storage in Android

To create a text file programmatically in internal storage in Android we will be using the File class from the java.io.File package.

In the code sample I have created, I am allowing the user to enter the name of the file inside an EditText as well as allowing them to use a ToggleButton to choose if they want a persistent file or a cache file to be created in internal storage.

We will use the File constructor and provide two parameters, the first is of the data type File which refers to the directory where the File we create will reside and the second parameter is of the data type String which will be the name of the file.

Читайте также:  Android tv hdmi arc

For persistent files in internal storage we need to use the “files” directory inside the internal storage directory. To obtain this directory use the getFilesDir() method on the application context which will return a File object pointing the “files” directory.

For cache files in internal storage we need to use the “cache” directory inside the internal storage directory. To obtain this directory use the getCacheDir() method on the application context which will return a File object pointing the “cache” directory.

Before we create the file, I will first check whether it already exists using the exists() method on the File object which will return true if the File already exists or false if it does not exist.

If the file doesn’t exist, I will proceed to create the file using the createNewFile() method on the File object.

Please see the code excerpt below for programmatically creating either a persistent or cache file in internal storage in Android.

How to Write Text to a File Programmatically in Internal Storage in Android

To write text to a file residing in the internal storage of our app programmatically we will be using the FileOutputStream class from the java.io.FileOutputStream package.

In our code sample, we will be writing the file name that has been entered in the EditText by the user and will determine if the file is a persistent file or a cache file based on the checked status of the ToggleButton.

Also in our code sample, the user will enter the text they wish to write into the file in an EditText and select the “Write File” button when they are ready to write the text to the file.

To set up the FileOutputStream for writing the text to the file, we will first check if the file is a persistent file or cache file in internal storage.

If it is a persistent file then we will set up the FileOutputStream using the openFileOutput(String, int) method on the application context passing the file name and the Context.MODE_PRIVATE flag as parameters. The Context.MODE_PRIVATE flag for the file creation mode means the created file can only be accessed by the calling application.

If the file is a cache file then we will set up the FileOutputStream by passing a File object pointing to the cache file as a parameter to the FileOutputStream constructor.

Then to write the text to the file using the FileOutputStream we will call the write(byte[]) method by passing a byte array as a parameter that consists of the text from the file contents EditText encoded using the UTF-8 format into a byte array.

Please see the code excerpt below for programmatically writing text to either a persistent or cache file in internal storage in Android.

How to Read Text from a File Programmatically in Internal Storage in Android

To read the text from a file residing in the internal storage of our app programmatically we will be using the FileInputStream class from the java.io.FileInputStream package.

In our code sample, we will overwrite the file contents EditText with the text read from the file entered into file name EditText when the user selects the “Read File” button.

To set up the FileInputStream for reading the text from the file, we will first check if the file is a persistent file or a cache file in internal storage.

If it is a persistent file then we will set up the FileInputStream using the openFileInput(String) method on the application context passing the file name as a parameter.

If the file is a cache file then we will set up the FileInputStream by passing a File object pointing to the cache file as a parameter to the FileInputStream constructor.

Then we create will an InputStreamReader from the FileInputStream and use that to create a BufferedReader which allows us to read from the file one line at a time. We will create an empty ArrayList of Strings to store each line of text from the file.

Next we will use the BufferedReader inside a while loop to extract each line of text one at a time until there is no more text. Each line of text read using the BufferedReader will be inserted into the ArrayList sequentially.

Once all of the lines of text have been read from the file we will use the join(…) method from the TextUtils class to create a single String of text by joining all of the lines of text in the ArrayList together with a new line character between all lines of text. This will allow the text to be formatted correctly when displayed in the EditText containing the file contents.

Please see the code excerpt below for programmatically reading text from a either a persistent or cache file in internal storage in Android.

How to Delete a Text File Programmatically from Internal Storage in Android

To delete a file residing in the internal storage of our app programmatically we will be using the File class from the java.io.File package.

First we will create File object pointing the File we want to delete by using the file name entered by the user and selecting the appropriate file directory based on whether the file is a persistent file or a cache file.

Then we will use the exists() method on the File object to confirm that it exists, and if it does exist we will proceed to delete using the delete() method on the File object.

Please see the code excerpt below for programmatically deleting either a persistent or cache file in internal storage in Android.

How to View Files in Internal Storage using the Android Device File Explorer

The Device File Explorer is a tool available in Android Studio that allows you to view all of the files on the Android device connected to Android Studio.

The Device File Explorer can be used to read both the persistent and cache files inside internal storage of your Android app.

To access the Device File Explorer in Android Studio select the “View” menu, hover over “Tool Windows” and select the “Device File Explorer” menu item.

The Device File Explorer will load on the right side of Android Studio and will display a file tree of all of the directories and files on the Android device.

Читайте также:  Чем miui лучше чистого android

To locate persistent files in internal storage of your app navigate through to the following directory.

data/data/ /files

To locate cache files in internal storage of your app navigate through to the following directory.

data/data/ /cache

You can also open any file to read inside Android Studio by double clicking on the file name.

How to Remove Files from Internal Storage using the Android Storage Utility

It is possible to use a storage utility an Android device to remove persistent and cache files from the internal storage of your app.

In the storage utility shown in the GIF below. The total amount of storage used by your Android app broken down by the App size, User data and Cache is shown along with a button to “Clear storage” and a button to “Clear cache”.

Selecting the “Clear storage” button will delete all persistent and cache files from the internal storage of your app.

Selecting the “Clear cache” button will delete only the cache files from the internal storage of your app leaving the persistent files in internal storage.

Android External File Storage Tutorial

What is External Storage in Android?

In Android External Storage is used for storing files that other apps are able to access. External storage is better for storing larger files that need to be shared with other apps.

Files in external storage can be app specific, meaning that when the app is uninstalled these files in external storage will be deleted. App specific files in external storage can be persistent files or cache files.

For Android 4.4 (API level 19) and higher, no storage related permissions are required to access app specific directories with external storage.

For apps the target Android 10 (API level 29) or higher, a new feature called scoped storage is applied by default to external storage which will prevent other apps from accessing your app specific files in external storage.

To learn more about scoped storage check out the YouTube video below.

Media files such as images, audio and video can be exposed to other apps in external storage through the use of the Android MediaStore API.

Other files you want to share to other apps in external storage such as documents can be shared using the Storage Access Framework.

How to Store Persistent and Cache Files in External Storage in Android

App specific persistent files in external storage reside in a directory accessible using the getExternalFileDirs() method.

App specific cache files in external storage reside in a directory accessible using the getExternalCacheDirs() method.

The code sample below contains code for writing a persistent file or a cache file into external storage in Android.

The code sample below contains code for reading a persistent file or a cache file from external storage in Android.

Below is a screenshot of an Android app creating a persistent file in app specific external storage.

Below is a screenshot of the Device File Explorer in Android Studio showing the persistent file created in app specific external storage.

Below is a screenshot of an Android app creating a cache file in app specific external storage.

Below is a screenshot of the Device File Explorer in Android Studio showing the cache file created in app specific external storage.

How to Store Media Files in External Storage in Android

Media files such as images, videos and audio can be shared in external storage with other apps using the Android Media Store API providing they have the READ_EXTERNAL_STORAGE permission. Media files shared using the Media Store API will not be deleted when the app is uninstalled.

On Android 10 (API level 29) or higher, READ_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE permissions are required to access media files created by other apps via the Media Store API. On Android 9 (API level 28) or lower permissions are required for accessing all media files via the Media Store API.

To demonstrate how to storage media files in external storage in Android using the MediaStore API, I created a sample app that loads an image from the internet using the Glide library then stores it into the Pictures directory in external storage using the MediaStore API for images.

The app also will display a RecyclerView in a grid layout of all images in the Pictures directory retrieved using the MediaStore API.

If you would like to learn more about how to set up and use Glide for image loading in your Android app including how to download the Glide using Gradle and how to set up the manifest to include internet permissions, check out the tutorial I wrote on how to use Glide at the link below.

For this section of the tutorial first we will be creating a class modelling an image retrieved from the Media Store API. See the code sample for the Image class below.

Next we will be creating a RecyclerViewHolder class for the Image to display the Image in the RecyclerView. See the code sample for the ImageViewHolder class below which sets the name of the Image in the TextView and loads the ImageView with Glide inside the bind(Image) method.

For the next step we will create a RecyclerViewAdapter for the RecyclerView. See the code sample for the GalleryRecyclerAdapter class below.

In the final step in this section of the tutorial we will create an Activity class that includes code for inserting an Image into the Media Store API and querying Images from the Media Store API into the RecyclerViewAdapter to be shown in the RecyclerView.

How to Store Documents in External Storage in Android

Documents and other files can be shared with other apps in external storage using the Storage Access Framework.

No permissions are required read or write files in external storage to the Storage Access Framework. Files created using your app via the Storage Access Framework will not automatically be deleted when you uninstall your app.

Please see the code sample for the activity class below that can read and write files to external storage using the Storage Access Framework.

See the screen capture below showing the user experience of creating and writing to a text document generating using the Storage Access Framework.

Источник

Оцените статью