Skip to main content

In this tutorial, I will show how can I save String Android Internal Storage .txt file 








Nested Class:

1.File file
2.FileOutputStream fileOutputStream
3.OutputStreamWriter outputStreamWriter

Step 1: Android Manifest.xml Permission Add

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ruhul.string_save_txt_format">

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<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/Theme.String_save_txt_format">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>


Step 2: Layout design:  activity_main.xml 




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:textColor="@color/black"
android:textStyle="bold"
android:textSize="18sp"
android:id="@+id/text_id"
android:layout_marginTop="100dp"
android:textAlignment="center"
android:text="String save .txt format"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal">

</TextView>

<com.google.android.material.textfield.TextInputEditText
android:layout_centerInParent="true"
android:id="@+id/input_edttxt_id"
android:layout_width="match_parent"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_height="150dp">

</com.google.android.material.textfield.TextInputEditText>

<com.google.android.material.button.MaterialButton
android:layout_marginTop="15dp"
android:layout_below="@id/input_edttxt_id"
android:text="Save File"
android:id="@+id/button_save_id"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:backgroundTint="#0288D1"
android:layout_width="match_parent"
android:layout_height="wrap_content">

</com.google.android.material.button.MaterialButton>

</RelativeLayout>



Step 3: Go to Java File: MainActivity

private static final int REQUEST_CODE = 1;
private MaterialButton save_btn;
private TextInputEditText input_edt_txt;

save_btn=findViewById(R.id.button_save_id);
input_edt_txt=findViewById(R.id.input_edttxt_id);



TextInputEditText smoothly Scroll:

input_edt_txt.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (v.getId()==R.id.input_edttxt_id)
{
v.getParent().requestDisallowInterceptTouchEvent(true);
switch (event.getAction() & MotionEvent.ACTION_MASK)
{
case MotionEvent.ACTION_UP:
{
v.getParent().requestDisallowInterceptTouchEvent(false);
}

}
}
return false;
}
});



permission Check : WRITE_EXTERNAL_STORAGE: 

if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)== PackageManager.PERMISSION_GRANTED)
{
filesave_internal();



}
else {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},REQUEST_CODE);
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
{
super.onRequestPermissionsResult(requestCode, permissions, grantResults);

if (requestCode==REQUEST_CODE)
{
if (grantResults.length==-1)
{
Toast.makeText(this, "no permission", Toast.LENGTH_SHORT).show();
}
else {

grantResults[0]=PackageManager.PERMISSION_GRANTED;
filesave_internal();

}
}
}





public void filesave_internal()
{
String text=input_edt_txt.getText().toString();

if (!TextUtils.isEmpty(text))
{
File file=new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/Textfile/");
if (file.exists())
{
Log.d("file_exists","File exists already");


//alert Edittext uses input file name---
AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this);
builder.setTitle("file save");
builder.setMessage("Input File name");


EditText alerteditText=new EditText(MainActivity.this);
alerteditText.setHint("please enter file name..");
builder.setView(alerteditText);


Date date=new Date(System.currentTimeMillis());
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy:MM:dd hh:mm:ss a", Locale.getDefault());
String datetime=simpleDateFormat.format(date);





builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {

String filename=alerteditText.getText().toString();

if (TextUtils.isEmpty(alerteditText.getText().toString()))
{
alerteditText.setError("enter file name");
}
else {
File file1=new File(file,filename+"_"+datetime+".txt");
FileOutputStream fileOutputStream=null;
try {
fileOutputStream=new FileOutputStream(file1);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
OutputStreamWriter outputStreamWriter=new OutputStreamWriter(fileOutputStream);
try {
outputStreamWriter.write(text);
} catch (IOException e) {
e.printStackTrace();
}
try {
outputStreamWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
outputStreamWriter.close();
} catch (IOException e) {
e.printStackTrace();
}

}
}
});
builder.setNegativeButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {

dialog.cancel();
}
});

AlertDialog alertDialog=builder.create();
alertDialog.show();

}
else {
file.mkdir();

//alert Edittext uses input file name---
AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this);
builder.setTitle("file save");
builder.setMessage("Input File name");


EditText alerteditText=new EditText(MainActivity.this);
alerteditText.setHint("please enter file name..");
builder.setView(alerteditText);


Date date=new Date(System.currentTimeMillis());
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy:MM:dd hh:mm:ss a", Locale.getDefault());
String datetime=simpleDateFormat.format(date);


builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String filename=alerteditText.getText().toString();

if (TextUtils.isEmpty(alerteditText.getText().toString()))
{
alerteditText.setError("enter file name");
}
else {
File file1=new File(file,filename+"_"+datetime+".txt");
FileOutputStream fileOutputStream=null;
try {
fileOutputStream=new FileOutputStream(file1);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
OutputStreamWriter outputStreamWriter=new OutputStreamWriter(fileOutputStream);
try {
outputStreamWriter.write(text);
} catch (IOException e) {
e.printStackTrace();
}
try {
outputStreamWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
outputStreamWriter.close();
} catch (IOException e) {
e.printStackTrace();
}

}
}
});
builder.setNegativeButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {

dialog.cancel();
}
});

AlertDialog alertDialog=builder.create();
alertDialog.show();








}


}
else {
input_edt_txt.setError("please input text..");

}

}







Full Source Code :



package com.ruhul.string_save_txt_format;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.material.button.MaterialButton;
import com.google.android.material.textfield.TextInputEditText;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {

private static final int REQUEST_CODE = 1;
private MaterialButton save_btn;
private TextInputEditText input_edt_txt;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

save_btn=findViewById(R.id.button_save_id);
input_edt_txt=findViewById(R.id.input_edttxt_id);

input_edt_txt.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (v.getId()==R.id.input_edttxt_id)
{
v.getParent().requestDisallowInterceptTouchEvent(true);
switch (event.getAction() & MotionEvent.ACTION_MASK)
{
case MotionEvent.ACTION_UP:
{
v.getParent().requestDisallowInterceptTouchEvent(false);
}

}
}
return false;
}
});

save_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)== PackageManager.PERMISSION_GRANTED)
{
filesave_internal();



}
else {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},REQUEST_CODE);
}

}
});

}

public void filesave_internal()
{
String text=input_edt_txt.getText().toString();

if (!TextUtils.isEmpty(text))
{
File file=new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/Textfile/");
if (file.exists())
{
Log.d("file_exists","File exists already");


//alert Edittext uses input file name---
AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this);
builder.setTitle("file save");
builder.setMessage("Input File name");


EditText alerteditText=new EditText(MainActivity.this);
alerteditText.setHint("please enter file name..");
builder.setView(alerteditText);


Date date=new Date(System.currentTimeMillis());
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy:MM:dd hh:mm:ss a", Locale.getDefault());
String datetime=simpleDateFormat.format(date);





builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {

String filename=alerteditText.getText().toString();

if (TextUtils.isEmpty(alerteditText.getText().toString()))
{
alerteditText.setError("enter file name");
}
else {
File file1=new File(file,filename+"_"+datetime+".txt");
FileOutputStream fileOutputStream=null;
try {
fileOutputStream=new FileOutputStream(file1);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
OutputStreamWriter outputStreamWriter=new OutputStreamWriter(fileOutputStream);
try {
outputStreamWriter.write(text);
} catch (IOException e) {
e.printStackTrace();
}
try {
outputStreamWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
outputStreamWriter.close();
} catch (IOException e) {
e.printStackTrace();
}

}
}
});
builder.setNegativeButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {

dialog.cancel();
}
});

AlertDialog alertDialog=builder.create();
alertDialog.show();

}
else {
file.mkdir();

//alert Edittext uses input file name---
AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this);
builder.setTitle("file save");
builder.setMessage("Input File name");


EditText alerteditText=new EditText(MainActivity.this);
alerteditText.setHint("please enter file name..");
builder.setView(alerteditText);


Date date=new Date(System.currentTimeMillis());
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy:MM:dd hh:mm:ss a", Locale.getDefault());
String datetime=simpleDateFormat.format(date);


builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String filename=alerteditText.getText().toString();

if (TextUtils.isEmpty(alerteditText.getText().toString()))
{
alerteditText.setError("enter file name");
}
else {
File file1=new File(file,filename+"_"+datetime+".txt");
FileOutputStream fileOutputStream=null;
try {
fileOutputStream=new FileOutputStream(file1);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
OutputStreamWriter outputStreamWriter=new OutputStreamWriter(fileOutputStream);
try {
outputStreamWriter.write(text);
} catch (IOException e) {
e.printStackTrace();
}
try {
outputStreamWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
outputStreamWriter.close();
} catch (IOException e) {
e.printStackTrace();
}

}
}
});
builder.setNegativeButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {

dialog.cancel();
}
});

AlertDialog alertDialog=builder.create();
alertDialog.show();








}


}
else {
input_edt_txt.setError("please input text..");

}

}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
{
super.onRequestPermissionsResult(requestCode, permissions, grantResults);

if (requestCode==REQUEST_CODE)
{
if (grantResults.length==-1)
{
Toast.makeText(this, "no permission", Toast.LENGTH_SHORT).show();
}
else {

grantResults[0]=PackageManager.PERMISSION_GRANTED;
filesave_internal();

}
}
}
}

Step 4: Output Check :





















Comments

Post a Comment

Popular posts from this blog

 Firebase Cloud Messaging With  push notification with Image  public class ImageDownload extends AsyncTask < String , Void , Bitmap >{ @Override protected Bitmap doInBackground ( String ... strings ) { InputStream inputStream ; try { URL url = new URL( strings [ 0 ]) ; try { HttpURLConnection connection = ( HttpURLConnection ) url .openConnection() ; connection .connect() ; inputStream = connection .getInputStream() ; return BitmapFactory . decodeStream ( inputStream ) ; } catch ( IOException e ) { e .printStackTrace() ; } } catch ( MalformedURLException e ) { e .printStackTrace() ; } return null; } @Override protected void onPostExecute ( Bitmap bitmap ) { ShowNotification( bitmap ) ; } }
 phone authentication in android using Firebase Step 1:    Add Firebase to your Android project Step 2: Add this line build.Gradle(project) // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { google() jcenter() } dependencies { classpath "com.android.tools.build:gradle:4.1.1" classpath 'com.google.gms:google-services:4.3.5' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { google() jcenter() } } task clean( type : Delete) { delete rootProject . buildDir } Step 3: Add this dependency build.Gradle (app level) plugins { id 'com.android.application' } android { compileSdkVersion 30 buildToolsVersion "30.0.3" defaultConfig { applicationId "com.ruhul.firebasephone