- How to Read a Text File in Android?
- Step by Step Implementation
- How to read text file in android – Read from any folder internal & external
- How to Read Text file in android
- Login & Download the Code
- Step by Step Process
- Add run time permission
- activity-main.xml
- MainActivity.java run time permission code
- Select file from gallery
- Get actual file path from URI
- Read text file in android
- Run the code
- Android Read Write Internal Storage File Example
- 1. Android Read Write Data To Internal File.
- 1.1 Where Your Android App Internal Data File Saved In?
- 1.2 Read Write Android File Code Snippets.
- 2. Android Internal File Operation Example.
- 2.1 Layout XML File.
- 2.2 Activity Java File.
- 3. Question & Answer.
- 3.1 Can not write text file to android internal storage.
- Reading from text file android
- Android Read Write File Operations
- Example
- VIDEO DEMO
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.
Источник
How to read text file in android – Read from any folder internal & external
Read text file . How to read text file in android app? Some time developer think that it is very difficult to read text file in android, but truth is – it is very easy. You can read any text file and excel sheet from android app whether file located in internal storage or external storage. If you want to know how to read excel file from asset folder, please read this tutorial.
To read any file from android app, you must take permission to read external storage. otherwise app will crash at run time. In this tutorial, I am going to show you, how to select text file from gallery OR internal storage OR external storage and read text file. I am using a simple textview to display the text written on selected text file.
So in this tutorial the process is as follow. First I am writing the code for run time permission, then code for select file from gallery then read the text written in text file. If you want work with PDF file than you can read this tutorial – How to create PDF file, write text and image
How to Read Text file in android
Login & Download the Code
Step by Step Process
- Add run time permission in Androidmanifest.xml
- MainActivity.java run time permission code
- Add select file from gallery or file manager
- Get actual file path from file URI
- Read file using bufferreader
- Run the code
Add run time permission
First, add run time permission in androidmanifest.xml file.
activity-main.xml
MainActivity.java run time permission code
Because we are trying to read text file from phone storage, so you must add the code for run time permission in android app. Android introduce run time permission in api 24 marshmallow. So first check user phone’s android version is greater than or equal to marshmallow.
If android version is greater than marshmallow than user will see a alert dialog to accept permission to read text file. Once user will click on allow/ denied button the response will be received in onRequestPermissionsResult() method. There if it is positive response (means allow) than you should start function to choose file from gallery, otherwise show error massage to user.
Select file from gallery
It is the best way to give complete control to user to select any file from the gallery. You have to use intent to open gallery option. The response of the intent will be receive in onActivityResult() method. The onActivityResult will return the intent data.
NOTE- you can only get the URI of the file using intent, not the actual file path. to get the actual file path, you have to write different functions. Actually the URI is a index of file not the exact path. The text file can be located into any folder, so we need to write multiple condition to get file path. below is the table of URI path according to folder location.
Get actual file path from URI
You must check auth of each file. auth is parent folder name, using this name you can identify which condition will be correct to get file path.
below is the code to get actual file path from gallery file. Please watch the above video to understand why you must check multiple condition to get file path.
Read text file in android
Now you have file path, use this file path to read file using buffer reader. below is the complete code of MainActivity.java
Run the code
Now every thing has setup. Please run the code, select file from gallery. You will see the text read from the text file will be display on screen.
If you have any question, please contact me or use chat box.
Please comment below, if this tutorial help you. Your feed back is more important for me to create new videos and tutorial.
Источник
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.
- Android is based on Linux, the android file system is Linux-based also.
- 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?
- All android app internal data files are saved in the /data/data/ folder.
- 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.
- From the youtube video, we can see that there are files and cache subfolders under the package name folder.
- files folder — android.content.Context’sgetFilesDir() method can return this folder. This folder is used to save general files.
- cache folder — android.content.Context’sgetCacheDir() method can return this folder. This folder is used to save cached files.
- 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.
- Android application is written in java, so the file operation uses java classes also.
- 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.
- Call android.content.Context‘s openFileInput(userEmalFileName) method to get FileInputStream object.
- The input parameter is just the file name.
- This file should be saved in the files folder.
- Then use the FileInputStream object to read data.
1.2.2 Read Android File In The Package cache Folder.
- The below source code will read the android files in the package cache folder.
1.2.3 Write File To The Package files Folder.
- Method 1: Use Context’s getFilesDir() to get the package files folder, then write file into it.
- Method 2: Call Context’s openFileOutput(userEmalFileName, Context.MODE_APPEND) method to get FileOutputStream object.
- The first parameter is the file name, the second parameter’s value can be one of the below values.
- 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.
- 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.
- Use Context’s getCacheDir() to get cache folder.
2. Android Internal File Operation Example.
- You can watch the example demo video on youtube https://youtu.be/HqbRR6TQVvY.
- There are one input text box and five buttons on the android example app main screen.
- The buttons’ function can be easily understood by the button’s label text.
- 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.
- 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.
- 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.
2.1 Layout XML File.
- activity_write_read_file.xml
2.2 Activity Java File.
- WriteReadFileActivity.java
- 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.
- 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.
- 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;
Источник
Reading from text file android
Android Read Write File Operations
Reading and Writing files in Android will be helpful if you want to read data from SD Card, store your application data as a text file. In this tutorial we are going to learn same. Below are some points that we are going to learn in today’s tutorial:
1. Write File – Write user input data into TextFile.
2. Read File – Read data from saved user data file.
3. Delete File – Delete saved file from SD Card.
4. TimeStamp – Fetching current time stamp and saved in shared preferences when file is saved.
5. File Path – Display file path to locate where the Text File is saved.
Prerequisites required for this tutorial –
- SD Card Mount –Check if SD Card is mounted or not.
- Create Directory – How to create directory in SD Card.
- SharedPreferences – To store timestamp of saved file.
We are going to use two classes for writing and reading file to SD Card –
1. FileWriter – A specialised Writer that writes to a file in the file system. All write requests made by calling methods in this class are directly forwarded to the equivalent function of the underlying operating system. Since this may induce some performance penalty, in particular if many small write requests are made, a FileWriter is often wrapped by a BufferedWriter.
2. FileReader – A specialised Reader that reads from a file in the file system. All read requests made by calling methods in this class are directly forwarded to the equivalent function of the underlying operating system. Since this may induce some performance penalty, in particular if many small read requests are made, a FileReader is often wrapped by a BufferedReader.
Example
In this tutorial, we are going to learn how to write, read and delete File operations in Android.
VIDEO DEMO
Источник