I want to add a Text file in my android app in package itself so that no one can re-edit or delete it. I am using BufferedReader and FileReader functions to access it but I am facing problem in giving the path of the file as it shows my laptop path which will change when app is installed on phones. So require some better option to specify the path of file. I have created a folder in src of app and using android studio to code. 
            Asked
            
        
        
            Active
            
        
            Viewed 213 times
        
    0
            
            
         
    
    
        Suren Srapyan
        
- 66,568
- 14
- 114
- 112
 
    
    
        Chandraman Patil
        
- 25
- 5
1 Answers
0
            Just put your text file in asset folder of android refer this answer for the example https://stackoverflow.com/a/5771369/5409229
Example Code
XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView  
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:text="@string/hello"
/>
</LinearLayout>
Android Code
 package com.javasamples;
//reading an embedded RAW data file
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
import java.io.*;
public class FileDemo1 extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
    PlayWithRawFiles();
} catch (IOException e) {
    Toast.makeText(getApplicationContext(), 
                 "Problems: " + e.getMessage(), 1).show();
}
  }// onCreate
public void PlayWithRawFiles() throws IOException {      
String str="";
StringBuffer buf = new StringBuffer();          
InputStream is = this.getResources().openRawResource(R.myfolder.text_file);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
if (is!=null) {                         
    while ((str = reader.readLine()) != null) { 
        buf.append(str + "\n" );
    }               
}       
is.close(); 
Toast.makeText(getBaseContext(), 
        buf.toString(), Toast.LENGTH_LONG).show();              
}// PlayWithSDFiles
} // FilesDemo4
 
    
    
        Community
        
- 1
- 1
 
    
    
        Hemant Sangle
        
- 282
- 3
- 19
- 
                    @Chandraman Patil check if this is what you want if yes then accept the answer – Hemant Sangle Jan 10 '17 at 06:45
- 
                    1This worked, but just had to change the line "R.drawable.my_base_data" to "R.myfolder.text_file" as drawable folder doesn't store .txt files so i made a new directory in res folder. Thanks a lot. – Chandraman Patil Jan 10 '17 at 07:06
- 
                    Thanks and up vote this answer so other get the benefits – Hemant Sangle Jan 10 '17 at 07:23