I have a text file in folder res/raw name "pass.txt" and some data in it i want to delete this data and enter new data in it.... is it possible to write data on it?? otherwise what is correct path to store my text file so i can easily read/write data on it.... and what is the code to read and write data from it?? below is the code through which i can only read data from this text file
InputStream fr = getResources().openRawResource(R.raw.pass);
BufferedReader br = new BufferedReader(new InputStreamReader(fr));
String s=br.readLine().toString().trim();
Resources contained in your raw directory in your project will be packaged inside your APK and will not be writeable at runtime.
Look at Internal or External Data Storage APIs to read write files.
https://developer.android.com/training/basics/data-storage/files.html
you can use Android internal storage to Read and write file ... as res/raw is only Read only..you can not change content at runtime.
Here is the code:
Create file
String MY_FILE_NAME = “mytextfile.txt”;
// Create a new output file stream
FileOutputStream fileos = openFileOutput(MY_FILE_NAME, Context.MODE_PRIVATE);
// Create a new file input stream.
FileInputStream fileis = openFileInput(My_FILE_NAME);
Read from file:
public void Read(){
static final int READ_BLOCK_SIZE = 100;
try {
FileInputStream fileIn=openFileInput("mytextfile.txt");
InputStreamReader InputRead= new InputStreamReader(fileIn);
char[] inputBuffer= new char[READ_BLOCK_SIZE];
String s="";
int charRead;
while ((charRead=InputRead.read(inputBuffer))>0) {
// char to string conversion
String readstring=String.copyValueOf(inputBuffer,0,charRead);
s +=readstring;
}
InputRead.close();
Toast.makeText(getBaseContext(), s,Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
Write to file:
public void Write(){
try {
FileOutputStream fileout=openFileOutput("mytextfile.txt", MODE_PRIVATE);
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write("TEST STRING..");
outputWriter.close();
//display file saved message
Toast.makeText(getBaseContext(), "File saved successfully!",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
Related
so im trying to write data that I recieve from a socket into text file and then read those data.
I have these 2 methods in my MainActivity (just tests to see how read and write from/into a file works) :
public void WriteBtn() {
// add-write text into file
try {
FileOutputStream fileout=openFileOutput("mytextfile.txt", MODE_PRIVATE);
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write("Test");
outputWriter.close();
//display file saved message
Toast.makeText(getBaseContext(), "File saved successfully!",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
public void ReadBtn() {
//reading text from file
try {
FileInputStream fileIn=openFileInput("mytextfile.txt");
InputStreamReader InputRead= new InputStreamReader(fileIn);
char[] inputBuffer= new char[256];
String s="";
int charRead;
while ((charRead=InputRead.read(inputBuffer))>0) {
// char to string conversion
String readstring=String.copyValueOf(inputBuffer,0,charRead);
s +=readstring;
}
InputRead.close();
Toast.makeText(getBaseContext(), s,Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
I call them with buttons but I was wondering, where does it save my "mytextfile.txt" ???
Take a look at Context.getExternalFilesDir() and pass it Environment.DIRECTORY_DOCUMENTS. That should give you the default output path for text files.
https://developer.android.com/reference/android/content/Context.html#getExternalFilesDir(java.lang.String)
EDIT
I just tested this. It looks like Context.openFileOutput() dumps everything, regardless of file type, to Conext.getFilesDir()
https://developer.android.com/reference/android/content/Context.html#getFilesDir()
I have searched a lot but it seems older answers are wrong as storage seems to have changed from data/data and permission WRITE_INTERNAL_MEMORY is no longer available. I am using Eclipse.
I have a multi-choice test and want to store the status of the answers a user has given:
N = not attepmpted, C = Correct last time, I = Incorrect last attempt
Therefore the file needs to be re-writeable - will be read as an array and then the array with new status will be over-written.
The code to write the file on first run is - you can see I've just changed it to write "N" now rather than lines of "N" as needed. There is also a single-line txt file to store the user id:
public void RunFirst(View view) throws IOException{
//need to initialise file as a list of N's:
count = 0;
StringBuilder sb = new StringBuilder();
while(count<4){
sb.append("N");
sb.append("\n");
count = count +1;
};
NsString = sb.toString();
String progfile = "userprogress.txt";
try {
FileOutputStream fos = new FileOutputStream(progfile);
fos = openFileOutput(progfile, Context.MODE_PRIVATE);
fos.write(NsString.getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
// read userID
TextView usrID = (TextView) findViewById(R.id.editTextUserNameInput);
userID = usrID.getText().toString();
Toast.makeText(getApplicationContext(), "Welcome" + userID,
Toast.LENGTH_LONG).show();
//save userID
String usridfile = "userid.txt";
try{
FileOutputStream fosuserid = new FileOutputStream(usridfile);
fosuserid = openFileOutput(usridfile, Context.MODE_PRIVATE);
fosuserid.write(userID.getBytes());
fosuserid.close();
Toast.makeText(getApplicationContext(), "filesaved",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
To read from the file:
private void readprogressfile(){
//#Override
try
{
Toast.makeText(getApplicationContext(), "b4 file",
Toast.LENGTH_LONG).show();
InputStream input = openFileInput("userprogress.txt");
InputStreamReader isr = new InputStreamReader(input);
BufferedReader buffrdr = new BufferedReader(isr);
userprog = new String [4];
int size = input.available();
byte[] buffer = new byte[size];
count = 0;
line = null;
while(count <4){
input.read(buffer);
line = new String(buffer);
userprog[count]= line;
Toast.makeText(getApplicationContext(), "status:" + count + userprog[count],
Toast.LENGTH_LONG).show();
};
input.close();
// byte buffer into a string
String text= new String(buffer);
//txtContent.setText(text);
Toast.makeText(getApplicationContext(), "after file",
Toast.LENGTH_LONG).show();
TextView showfile = (TextView)findViewById(R.id.textViewShowAns);
showfile.setText("Q status:"+ userprog[qno]);
}catch (IOException e) {
e.printStackTrace ();}
}
;
}
the fact that WRITE_INTERNAL_MEMORY permission is deprecated don't mean that you can't write to internal memory anymore. actually, it's the opposite - Google decided there is no need in any permission to write / create files in your private internal folder.
you can get path to your private application storage folder by the method getFilesDir()
this is the perfect place to write your private files, and made especially for that purpose.
as Google wrote in the documentation:
You don’t need any permissions to save files on the internal storage. Your application always has permission to read and write files in its internal storage directory.
source and more info on - http://developer.android.com/training/basics/data-storage/files.html
I have a layout where I have an Edit Text field where I enter my data.
I have 2 buttons.Save and Plot.
When I press save I want to save the data (in xls format) from edittext field and the current date in sd card.
When I press the plot ,I want to plot them.
To save data:
case R.id.savebtn:
savefunc();
break;
...
public void savefunc(){
//saving
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File (sdCard, "MyFiles");
directory.mkdirs();
File file = new File(directory, filename);
try {
FileOutputStream fOut = new FileOutputStream(file);
DataOutputStream os = new DataOutputStream(fOut);
os.writeUTF(thedata);
os.writeUTF(mydate);
os.close();
} catch (FileNotFoundException e) {
// handle exception
} catch (IOException e) {
// handle exception
}
}
For reading:
public void readfunc(){
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File (sdCard, "MyFiles");
File file = new File(directory, filename);
try{
FileInputStream fIn = new FileInputStream(file);
DataInputStream is = new DataInputStream(fIn);
String name = is.readUTF();
String content = is.readUTF();
is.close();
} catch (FileNotFoundException e) {
// handle exception
} catch (IOException e) {
// handle exception
}
}
and :
case R.id.savebtn:
savefunc();
break;
case R.id.graphicsbtn:
readfunc();
...
But the xls file asks me format , I choose UTF8 and it is empty.
If I leave it shows chinese characters.
I am not sure about the "reading" part of the code.
Read this documentation here have more information about save data to external storage and read it is:
Saving and Reading file from External storage
Ok, I found this and works fine!
I am new in android development, and I'm trying to create a simple application which reads some data from a text file and displays it in a ListView. The problem is my reader doesn't find my file. I've debugged my application and that is the conclusion I've come up with. So, where does the text file have to placed in order for the reader to find it?
Heres some code:
try
{
FileInputStream fstream = new FileInputStream("movies.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null)
{
filme.add(strLine);
Log.d(LOG_TAG,"movie name:" + strLine);
}
in.close();
}
catch (Exception e)
{
System.err.println("Error: " + e.getMessage());
}
Thanks!
Put the file named movies.txt in res/raw, then use the following code
String displayText = "";
try {
InputStream fileStream = getResources().openRawResource(
R.raw.movies);
int fileLen = fileStream.available();
// Read the entire resource into a local byte buffer.
byte[] fileBuffer = new byte[fileLen];
fileStream.read(fileBuffer);
fileStream.close();
displayText = new String(fileBuffer);
} catch (IOException e) {
// exception handling
}
FileInputStream fstream = new FileInputStream("movies.txt");
where is the path for movies.txt ?? You must need to give the path as sd card or internal storage wherever you have stored.
As if, it is in sd card
FileInputStream fstream = new FileInputStream("/sdcard/movies.txt");
Usually when you want to open a file you put it into the res folder of your project.
When you want to open a text file, you can put it into the res/raw directory. Your Android eclipse plugin will generate a Resource class for you containing a handle to your textfile.
To access your file you can use this in your activity:
InputStream ins = getResources().openRawResource(R.raw.movies);
where "movies" is the name of your file without the filetype.
If you store your files on the SD card, then you can get the root of the SD card with Environment.getExternalStorageDirectory().
Note, that you might not be able to access the SD card, if it is mounted to the computer for example.
You can check the state of the external storage like this:
boolean externalStorageAvailable = false;
boolean externalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
externalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
externalStorageAvailable = true;
externalStorageWriteable = false;
} else {
externalStorageAvailable = mExternalStorageWriteable = false;
}
if(externalStorageAvailable && externalStorageWriteable){
File sdRoot = Environment.getExternalStorageDirectory();
File myFile = new File(sdRoot, "path/to/my/file.txt");
}
I want to save a file in internal storage.The next step is i want to read the file.
The file is created in the internal storage using FileOutputStream but there is problem in reading the file.
Is it possible to access internal storage to read the file?
Yes you can read file from internal storage.
for writing file you can use this
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
to read a file use the below:
To read a file from internal storage:
Call openFileInput() and pass it the name of the file to read. This returns a FileInputStream. Read bytes from the file with read(). Then close the stream with close().
Code:
StringBuilder sb = new StringBuilder();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
is.close();
} catch(OutOfMemoryError om) {
om.printStackTrace();
} catch(Exception ex) {
ex.printStackTrace();
}
String result = sb.toString();
Refer this link
It is possible to write and read the text file from internal storage. In case of internal storage there is no need to create the file directly. Use FileOutputStream to write to file. FileOutputStream will create the file in internal storage automatically. There is no need to provide any path, you only need to provide the file name. Now to read the file use FileInputStream. It will automatically read the file from internal storage. Below I am providing the code to read and write to file.
Code to write the file
String FILENAME ="textFile.txt";
String strMsgToSave = "VIVEKANAND";
FileOutputStream fos;
try
{
fos = context.openFileOutput( FILENAME, Context.MODE_PRIVATE );
try
{
fos.write( strMsgToSave.getBytes() );
fos.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
CODE TO READ THE FILE
int ch;
StringBuffer fileContent = new StringBuffer("");
FileInputStream fis;
try {
fis = context.openFileInput( FILENAME );
try {
while( (ch = fis.read()) != -1)
fileContent.append((char)ch);
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String data = new String(fileContent);
This thread seems to be exactly what you are looking for Read/write file to internal private storage
Has some good tips.
Absolutely Yes,
Read this http://developer.android.com/guide/topics/data/data-storage.html#filesInternal
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();