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");
Related
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();
}
}
developer data-storage-files
String filename = "myfile";
String string = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
private String readfile(){
String content="";
try{
InputStream inputStream=openFileInput(myfile);
if(inputStream!=null){
InputStreamReader inputStreamReader=new InputStreamReader(inputStream);
BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
String receiveString="";
StringBuilder stringBuilder=new StringBuilder();
while((receiveString=bufferedReader.readLine())!=null){
stringBuilder.append(receiveString);
}
inputStream.close() ;
content=stringBuilder.toString();
}
}
catch (FileNotFoundException e){
Log.e(FILENAME1, "File Not Found"+e.toString());
}catch (IOException e){
Log.e(FILENAME1,"Cannot read file"+e.toString());
}
return content;
}
I try to write a txt file according to this website, say i want to save the data like this way: ever day i save one number after the date
line 1 2014-12-23 3
line 2 2014-12-24 6
line 3 2014-12-25 10
.
.
.
.
But for every time I write data into this file, it seems that the file is overwritten and every time i read the file, this returns me the most update number. I want to save the date and get the data on one specific line. Any suggestions? Thanks a lot!!
Try changing this
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
to
outputStream = openFileOutput(filename, Context.MODE_APPEND);
Also you might have to check if files exists. If it doesn't exist use your original statement and if it does exist then use the statement I have mentioned.
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.
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 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();