write and read file order nature android - android

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.

Related

Android, Why Can't I Read the File I Just Wrote?

I am using the first snippet to write a file.
String fileName = "Test6.txt";
String outputString="Text for File";
try {
FileOutputStream outputStream = openFileOutput(fileName, Context.MODE_PRIVATE);
outputStream.write(outputString.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
And the second to read it.
try{
FileInputStream InputStream = openFileInput("Text6.txt");
InputStreamReader inputStreamReader = new InputStreamReader(InputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String lineData = bufferedReader.readLine();
}catch(FileNotFoundException ex)
{
Log.d(TAG, ex.getMessage());
}
catch(IOException ex) {
Log.d(TAG, ex.getMessage());
}
But I can't read it, I get:
java.io.FileNotFoundException: /data/user/0/com.example.android.buildingmarque2/files/Text6.txt (No such file or directory)
I can also get a list of the files and Test6.txt is in the list.
Also, Android Studio Device File Explorer shows it.
It could be a problem with the path.
Device Explorer, "Copy Path" gives me
/data/data/com.example.android.buildingmarque2/files/Test6.txt
But the Log says:
/data/user/0/com.example.android.buildingmarque2/files/Text6.txt
I'm confused?
Typo. One is "Text6" the other is "Test6". Use a constant for both names to avoid this in the future

How to create a file from google glass application?

I have an application that runs on glass. I want my application to create files at run time and be able to write/read data to/from those files. Can anyone show me a way to do this? Does Android's openFileOutput() work in glass?
(In case if anyone else has the same question)
Okay I figured out a way to do this. It looks like Java i/o libraries works fine with android and also for glass. The following works fine in glass.
String filename = "sensorData";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_APPEND);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter (outputStream);
outputStreamWriter.write(content);
outputStreamWriter.close();
}
catch (Exception e) {
e.printStackTrace();
}
//Printing the file in logcat just to verify the contents
FileInputStream inputStream;
try
{
inputStream = openFileInput(filename);
InputStreamReader inputStreamReader = new InputStreamReader (inputStream);
char[] buffer = new char[content.length()];
inputStreamReader.read(buffer);
String input = buffer.toString();
Log.i(input);
}
catch (Exception e)
{
e.printStackTrace();
}

What's wrong with my read and write of the file in Android app's assets?

Code first:
AssetManager mgr = DeviceListActivity.this.getApplicationContext().getAssets();
try {
Log.e("Glenn:", address);
FileOutputStream fout = mgr.openFd("device/device_address.txt").createOutputStream();
PrintWriter _fout = new PrintWriter(fout);
_fout.println(address);
Log.e("Glenn", address);
_fout.close();
fout.close();
InputStream fin = mgr.open("device/device_address.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fin));
address = br.readLine();
try {
Log.e("Glenn:", address);
} catch (NullPointerException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
Log.e("Glenn", "error with OutputStream");
}
The value of address printed by the first two Log.e() calls is the right value, which actually is a device MAC address. However, when I was trying to test the value of address read from the file, which had just been written, NullPointerException has been caught within the Log.e() call. This means the value read from the file is NULL. Can anyone point out what's wrong with the code?
You cannot write in your app's asset file. You have only read but not write permissions. AssetManager only provides methods to read the files from your app's asset folder.

Is it possible to read a file from internal storage (Android)?

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

write and read strings to/from internal file

I see a lot of examples how to write String objects like that:
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
but not how to read them back from internal application file. Most of examples assume specific string length to calculate byte buffer but I do not know what the length will be. Is there an easy way to do so? My app will write up to 50-100 strings to the file
Writing strings this way doesn't put any sort of delimiters in the file. You don't know where one string ends and the next starts. That's why you must specify the length of the strings when reading them back.
You can use DataOutputStream.writeUTF() and DataInputStream.readUTF() instead as these methods put the length of the strings in the file and read back the right number of characters automatically.
In an Android Context you could do something like this:
try {
// Write 20 Strings
DataOutputStream out =
new DataOutputStream(openFileOutput(FILENAME, Context.MODE_PRIVATE));
for (int i=0; i<20; i++) {
out.writeUTF(Integer.toString(i));
}
out.close();
// Read them back
DataInputStream in = new DataInputStream(openFileInput(FILENAME));
try {
for (;;) {
Log.i("Data Input Sample", in.readUTF());
}
} catch (EOFException e) {
Log.i("Data Input Sample", "End of file reached");
}
in.close();
} catch (IOException e) {
Log.i("Data Input Sample", "I/O Error");
}

Categories

Resources