Write data continuously to file in external storage - Android App - android

I am writing the data to the file in an external storage (SD card) on my android. The issue that I am facing is that it just makes one entry and does not go beyond that. I have looked up a number of Q/As here. Could someone please point me in the write direction? TIA!
FileOutputStream outputstream;
try {
file1 = new File(Environment.getExternalStorageDirectory(), "MyData.txt");
outputstream = new FileOutputStream(file1);
OutputStreamWriter oswriter = new OutputStreamWriter(outputstream);
BufferedWriter bwriter = new BufferedWriter (oswriter);
bwriter.append(entry);
bwriter.newLine();
bwriter.close();
outputstream.close();
} catch (Exception e) {
e.printStackTrace();
}

You have to tell FileOutputStream to append the data. By default it just overwrites all contents there. For this you only need to use a different constructor FileOutputStream(File, boolean):
outputstream = new FileOutputStream(file1, true);

Related

Why does OutputStream returned by DriveContents.getOutputStream() not act as expected?

I have been playing with Google Drive API for Android and I have stumbled across a bit of a problem. In particula I am interested in App Folder fro saving and synchronizing app data across devices.
I can query if a file with certain filename exists in app folder.
I can get file via
driveFile = metadata.getDriveId().asDriveFile();
I can open file via
driveFile.open( mGoogleApiClient,
DriveFile.MODE_WRITE_ONLY,
new DownloadProgressListener() {...} )
.setResultCallback(...);
And in the later callback I can get OutputStream with:
OutputStream outputStream = dcr.getDriveContents().getOutputStream();
But the problem is that if I try to write to that OutpustStream nothing is written to file. I have used code like that:
OutputStream outputStream = result.getDriveContents().getOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(outputStream);
try {
writer.write("Just some strinh I want to save to Google Drive.");
} catch (IOException e) {
throw new RuntimeException(e);
}
Status status = dcr.getDriveContents().commit(mGoogleApiClient, null).await();
Using this OutputStream nothing is ever written to GoogleDrive. But if I use code from https://developers.google.com/drive/android/files#making_modifications it works as expected.
A copied snippet of that code from google for reference:
try {
ParcelFileDescriptor parcelFileDescriptor = contents.getParcelFileDescriptor();
FileOutputStream fileOutputStream = new FileOutputStream(parcelFileDescriptor
.getFileDescriptor());
Writer writer = new OutputStreamWriter(fileOutputStream);
writer.write("hello world");
} catch (IOException e) {
e.printStackTrace();
}
Why does OutputStream accesible by DriveContents.getOutputStream() not work as expected? Why is it even provided? Or am I missing something?
Version of Google Play Services Library is r29.
Close the OutputStreamWriter - writer.close() to commit the output.

Appending data to a text file in Android

I am trying to add data to a text file in android using the code below but it only overwrites the data with one line of data.
private void copyImageToMemory(File outFile , Float number) {
try {
BufferedOutputStream fos = new BufferedOutputStream(
new FileOutputStream(outFile));
PrintWriter pw = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(fos)));
pw.append("result"+number);
pw.close();
maxSpeed=0;
} catch (FileNotFoundException e) {
Log.e(TAGFile, "FileNotFoundException");
}
}
The FileOutputStream constructor allows to specify whether it should append to an already existing file or not:
new FileOutputStream(file, true);
will create a stream that appends to the given file.

Android Studio Data Collection

I am designing an app for my job to collect data on dog training. I need to be able to access the data on my computer to analyze it. I have completed the front end of the app and organized all of the information into a single string that I would like to save into a file for later analysis. I run the app and can not find the data anywhere on the tablet that runs the app. The code that saves the app is:
String output="Example, Data";
File file = new File(Environment.getExternalStoragePublicDirectory(DIRECTORY_DOCUMENTS),"TrainingData.txt");
try {
FileOutputStream fout = new FileOutputStream(file);
OutputStreamWriter outputStream = new OutputStreamWriter(fout);
outputStream.write(output);
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
Is there something wrong with the saving part of the code listed or is it correct and I'm just failing to find the file on the tablet. Any help would be greatly appreciated.
Try this instead:
File path = context.getFilesDir();
File file = new File(path, "the-file.txt");
and then:
FileOutputStream stream = new FileOutputStream(file);
try {
stream.write(output".getBytes());
} finally {
stream.close();
}

Android : How to write into internal memory

I made this code to write on a sdcard, now how can I transform it to write into the internal memory ?
//private String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/liste.txt"; Path used to write on sdcard
try{
File file = new File(path);
BufferedWriter bw = new BufferedWriter(new FileWriter(file,true));
bw.write("something");
bw.flush();
bw.close();
catch(Exception e) {...}
In android each application has its own folder under /data/data/package/
this dir is only accessable by your app and the root if the device is rooted
to access this dir and read/write to it, you can use:
getApplicationContext().openFileOutput(name, mode);
and
getApplicationContext().openFileInput(name);
more about this here : Docs
USe this code:
FileOutputStream fos;
fos = context.openFileOutput(FILENAME, Context.MODE_WORLD_READABLE);
fos.write(data.getBytes()); //write to application top level directory for immediate sending
fos.close();
try{
File file = new File("/data/data/com.example.packagename/files/");
BufferedWriter bw = new BufferedWriter(new FileWriter(file,true));
bw.write("something");
bw.flush();
bw.close();
catch(Exception e) {...}
or
//To read file from internal phone memory
//get your application context:
Context context = getApplicationContext();
filePath = context.getFilesDir().getAbsolutePath();
File file = new File(filePath);

Android Emulator writes file but cannot find directory

I am trying to get a simple Hello World txt file to be written then read by my android application. When viewing the DDMS File Explorer it successfully creates the text file but i then get a FileNotFoundException when trying to read it.
try {
final String TESTSTRING = new String("Hello World");
FileOutputStream fOut = openFileOutput("test.txt", MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(TESTSTRING);
osw.flush();
osw.close();
FileInputStream fIn = new FileInputStream("test.txt");
InputStreamReader isr = new InputStreamReader(fIn);
char[] inputBuffer = new char[TESTSTRING.length()];
isr.read(inputBuffer);
String readString = new String(inputBuffer);
boolean isTheSame = TESTSTRING.equals(readString);
Log.i("File Reading Stuff", "success = " + isTheSame);
} catch (IOException e) {
e.printStackTrace();
}
also the error is java.io FileNotFoundException: /test.txt (No such file or directory)
Any Help Thanks.
I don't know where openFileOutput saves its files, but wouldn't you use it's input equivalent openFileInput to read such a file?
See my previous post with information about how to read/write to the external storage directory in Android:
Android how to use Environment.getExternalStorageDirectory()
-- Dan

Categories

Resources