Create Text File and also Read data from

package com.bhadreshtech.Activity;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;

import com.bhadreshtech.R;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class DemoClass extends Activity {

    private String name_file = "demo.txt";

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

    }

    private void readFile() {
        File dir = new File(Environment.getExternalStorageDirectory().getPath() + "/" + "TestDemo");
        if (!dir.exists()) dir.mkdirs();
        File file = new File(dir, "" + name_file);
        if (!file.exists()) try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //Log.d("newRandomeFileName is Final", "" + new_id);        FileWriter writer = null;
        try {
            writer = new FileWriter(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        for (int i = 0; i < 50; i++) {
            try {
                writer.append("Item number -> " + i);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void crateFile() {


        File file = new File(Environment.getExternalStorageDirectory().getPath() + "/" + "TestDemo", name_file);
        try {
            InputStream instream = openFileInput(Environment.getExternalStorageDirectory().getPath() + "/" + "TestDemo" + "/" + name_file);
            InputStreamReader inputreader = new InputStreamReader(instream);
            BufferedReader buffreader = new BufferedReader(inputreader);
            String line = null;
            //We initialize a string "line" 
            while ((line = buffreader.readLine()) != null) {
                System.out.println("line " + line);    //to display the text in text line        
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}

No comments: