Android - read and write simple text files to internal memory - android

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

Related

write text file in res/raw folder

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();
}
}

How to save (forever) a file in android, and restore the data later?

I literally looked through stackoverflow trying to find the right answer... maybe I am doing something wrong.
I am making my first more elaborate app, that is quizz app for children. I want the scores to be saved in the highscorestable.txt, that will be later opened, updated, read, etc. The file should exist after closing the application to reuse it with the next game and so on.
I was using http://developer.android.com/guide/topics/data/data-storage.html . I want the file to be saved on the phone memory.
I have the following code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_high_scores);
Intent intent = getIntent();
String userData;
scores =(EditText)findViewById(R.id.scores);
if(intent.getStringExtra(EndScreen.EXTRA_MESSAGE)!=null)
{
userData = intent.getStringExtra(EndScreen.EXTRA_MESSAGE);
}
else
{
userData="";
}
String temp = "";//to widzi przy zaladowaniu
String output = "";
String g="";
//FIRST READING not necessary?
try{
FileInputStream fin = openFileInput("highscorestable.txt");
int c;
while( (c = fin.read()) != -1){
temp = temp + Character.toString((char)c);
}
fin.close();
}
catch (Exception e) {
// e.printStackTrace();
}
if(temp.equals(null))
{
temp = "";
}
//output = userData; //+ temp;
FileOutputStream fos;//WRITING
try {
fos = openFileOutput("highscorestable.txt", Context.MODE_PRIVATE);
fos.write(userData.getBytes());
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
//READING2
try{
FileInputStream fin = openFileInput("highscorestable.txt");
int c;
while( (c = fin.read()) != -1){
g = g + Character.toString((char)c);
}
fin.close();
output= output+g;
scores.setText(output);
}
catch (Exception e) {
}
The intent itself works, actually everything works, however the fileitself does not last. I mean, when I start a new game, the old data is not restored. How to fix it?
Try using sharedPrefrences: http://developer.android.com/training/basics/data-storage/shared-preferences.html
They are stored permanently in the app as XML and are only readable to the app if configured properly. (unless you NEED text, read here: http://developer.android.com/training/basics/data-storage/files.html . Remember to add the permissions to your manifest)
EDIT:
try appending to the file not writing

Android very slow to read file from internal storage

On my application I need save and load a small xml file. I'd like save and load it on internal storage but I have speed problem for read this file.
This file is very small (about 20/30 lines).
I have try this code:
try {
FileInputStream file = openFileInput("map.xml");
int c;
String xml = "";
while( (c = file.read()) != -1){
xml = xml + Character.toString((char)c);
}
readXMLdata(xml);
mapRestore = true;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
then I have try to save and load the same file to external storage with this code:
String data = "";
try {
File myFile = new File(file_xml);
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
data = aBuffer;
myReader.close();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
return data;
I have do all test on my Nexus S. If use internal storage I get a lag to read file (some seconds), if I use external storage I don't have it.
Any solution?
Solution is pretty obvious - just use BufferedReader. In your second sample use you use it, but in the first you don't. That's why you have difference in reading performance.
When you have just FileInputStream and make calls to read method it will actually read data each time from internal storage which is not so fast.
When you use BufferedReader or BufferedInputStream data will be read into memory buffer first and then when you call readLine data is read from this buffer. It dramatically decrease the number of IO operations on internal storage and performs a lot faster.

changing byte when copy file not working

changing byte when copy file form one location to another not working whats wrong in my code please help me if i remove string s1; then its work perfect just duplicate original file when i alter bytes using s1 string its not work
samplet.text file contain numbers
3434214280
3044559080
3154356865
3312430124
3334491537
package com.example.copyfilefromdirectorytoanother;
ublic class MainActivity extends Activity {
private static final String TAG = "MainActivity.java";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// your sd card
String sdCard = Environment.getExternalStorageDirectory().toString();
// the file to be moved or copied
File sourceLocation = new File (sdCard + "/sample.txt");
// make sure your target location folder exists!
File targetLocation = new File (sdCard + "/MyNewFolder/sample.txt");
// just to take note of the location sources
Log.v(TAG, "sourceLocation: " + sourceLocation);
Log.v(TAG, "targetLocation: " + targetLocation);
try {
// 1 = move the file, 2 = copy the file
int actionChoice = 2;
// moving the file to another directory
if(actionChoice==1){
if(sourceLocation.renameTo(targetLocation)){
Log.v(TAG, "Move file successful.");
}else{
Log.v(TAG, "Move file failed.");
}
}
// we will copy the file
else{
// make sure the target file exists
if(sourceLocation.exists()){
InputStream in = new
FileInputStream(sourceLocation);
OutputStream out = new
FileOutputStream(targetLocation);
// Copy the bits from instream to outstream
String s1;
// byte[] theByteArray ;
byte[] buf = new byte[1024];
byte[] theByteArray = new byte[1024];
int len;
int n =1;
while ((len = in.read(buf)) > 0) {
s1= "BEGIN:VCARD \n VERSION:2.1 \n N:;UNKNOWN "+n+";;; \n FN:UNKNOWN "+n+"
\n TEL;CELL;PREF:+92"+buf+" \n END:VCARD ";
theByteArray=s1.getBytes();
out.write(theByteArray, 0, len);
n=n+1;
}
in.close();
out.close();
Log.v(TAG, "Copy file successful.");
}else{
Log.v(TAG, "Copy file failed. Source file
missing.");
}
}
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Well, you're reading in len bytes, appending data to it, then writing out len bytes. That's wrong, you need to do out.write(theByteArray, 0, theByteArray.length); I can see other possible problems there too, but your file may be small enough to avoid them.

Android - read internal data

I'm trying to make app, and I need to save string, just like TinyDB in AppInventor. So, I found there http://developer.android.com/guide/topics/data/data-storage.html#filesInternal that what I'm looking for is saving data to internal storage, but I don't know how to read it. They say:
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()
But I don't know how, my code never works. So I googled how to read from internal storage, and no code worked. Can you please tell me, how to read text from internal storage? :)
This is the code:
EditText tagbox = (EditText)findViewById(R.id.editText1);
String tag = tagbox.toString();
Context context = getApplicationContext();
FileInputStream fis = context.openFileInput( tag );
InputStreamReader in = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(in);
String data = br.readLine();
Toast.makeText(getApplicationContext(), data, Toast.LENGTH_LONG).show();
Ok, so I found the solution. The easiest way to store data ,like TinyDB in AppInventor, is using SharedPreferences:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
Edtior editor = preferences.edit();
To store data:
editor.putString("key", "value");
To read data:
String value = preferences.getString("key");
File selectedFile = new File(path + "/" + selectedFromList + ".txt");
FileInputStream fstream = null;
ArrayList sal = new ArrayList();
try {
fstream = new FileInputStream(selectedFile);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
sal.add(strLine);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Close the input stream
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Ok, so I found the solution. The easiest way to store data ,like TinyDB in AppInventor, is using SharedPreferences:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
Edtior editor = preferences.edit();
To store data:
editor.putString("key", "value");
To read data:
String value = preferences.getString("key");

Categories

Resources