Friday, 22 November 2013

How to read and write text files in Android (Updated with androidx package)

Reading and writing txt files stored in device are very easy and doesn't need too much work.

Please note: You need to provide the Write Permission in the device.

--------------------------This will go in the file_handling_activity.xml file.-----------------------------
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#339949"
android:orientation="vertical"
android:weightSum="10">

<EditText
android:id="@+id/fha_dataET"
android:layout_width="match_parent"
android:layout_height="0dp"
android:singleLine="false"
android:hint="Type here"
android:textColor="#ffffff"
android:textSize="25sp"
android:layout_weight="9"/>

<Button
android:id="@+id/fha_closeBTN"
android:background="#005f00"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity="center"
android:text="Close"
android:textSize="25sp"
android:textColor="#ffffff"
android:layout_weight="1"/>

</LinearLayout>
----------------------------------------------------------------------

-----------------------------The FileHandlingActivity.java code---------------------------

package com.app.yourappname;

import android.os.Bundle;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;

import androidx.appcompat.app.AppCompatActivity;

public class FileHandlingActivity extends AppCompatActivity {
private EditText myData;
private String myFilePath = "MyFilePath";
private File myNewDir = new File(Environment.getExternalStorageDirectory(), "MyNewDir");

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.file_handling_activity);
myData = findViewById(R.id.fha_dataET);
Button btn = findViewById(R.id.fha_closeBTN);

btn.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) { finish(); }
});
}

@Override
protected void onResume() {

if(!myNewDir.exists())
myNewDir.mkdir();

File file = new File(myNewDir, myFilePath);
try {
FileReader inputFile = new FileReader(file);
BufferedReader bufferReader = new BufferedReader(inputFile);

String line, wholeText="";

while ((line = bufferReader.readLine()) != null) {
wholeText = wholeText + line;
}

byte[] decodedBytes = Base64.decode(wholeText, Base64.DEFAULT);
String decodeByteArray = new String(decodedBytes);
myData.setText(decodeByteArray);
bufferReader.close();
}catch(Exception e){
System.out.println("Could not read file line by line:"+ e.getMessage());
}
super.onResume();
}

@Override
protected void onPause() {
byte[] encodedBytes = Base64.encode(myData.getText().toString().getBytes(), Base64.DEFAULT);
String encodeByteArray = new String(encodedBytes);
File file = new File(myNewDir, myFilePath);
if(!file.exists())
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream f = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(f);
pw.println(encodeByteArray);
pw.flush();
pw.close();
f.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.i("Please check", "WRITE_EXTERNAL_STORAGE permission manifest is missing.");
} catch (IOException e) {
e.printStackTrace();
}
super.onPause();
}
}
-----------------------------------------------------------------------------

------- Add write external storage permission and Declare Activity name in Manifest ---------------
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.app.yourappname">

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

<supports-screens
android:smallScreens="true"
android:normalScreens="true"
android:largeScreens="true"
android:xlargeScreens="true"
android:anyDensity="true" />

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".FileHandlingActivity" android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
-----------------------------------------------------------------------------

No comments:

Post a Comment