Android logging csv data to SD card - android

I have been been loitering on this site for weeks and have found it invaluable, however I am now stuck and need some pointers please. I am writing an app to create a .txt file on the sd card and then append csv data to it. Here is my code so far:
private void LogData() {
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard, "/DataLogger/my_file.txt");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
if (file.exists()) try {
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write("Example");
writer.write("\n");
writer.write("Text");
writer.write("\n");
writer.flush();
writer.close();
} catch (IOException e1) {
}
}
}
}
From the above, I anticipated that on calling "LogData()" for the first time an empty .txt file would be created and then subsequent runs would populate it. Instead nothing happens at all (no file is created). Prior to the above I have tried every piece of example code on creating a .txt file and nothing work. I am absolutely lost - please help!
And yes, I have added the following to the manifest :-)
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
For information, I am running lollipop 5.0.2 on a Moto G and I am very new to coding.
Thanks in advance.

Use the following code :
try {
file.createNewFile();
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write("Example");
writer.write("\n");
writer.write("Text");
writer.write("\n");
writer.flush();
writer.close();
} catch (IOException e)
{
...
}

Thanks everyone, I was not using the constructor correctly. Correct code:
BufferedWriter writer = new BufferedWriter(new FileWriter(file, true));
When you open a file using the FileWriter constructor that only takes in a File, it will overwrite what was previously in the file. Supplying the second parameter as true tells the FileWriter that you want to append to the end of it. Thanks to #nicholas.hauschild for his answer 4 years ago...

Related

Android Append text to file not working even if fileOutputStream appending mode setted to TRUE

I am trying to append text into a file stored in emulated/0/.. folder (external storage without SD Card)
FileOutputStream fileOutputStream = new FileOutputStream(capturesFile, true);
OutputStreamWriter writer = new OutputStreamWriter(fileOutputStream);
String data = "my data";
writer.append(data);
writer.close();
fileOutputStream.flush();
fileOutputStream.close();
This code is not working, I really do not understand why. Is the emulated location is a problem (stupid question but at this point...) I already tried many ways without any positive solution.
Is someone have an idea about this issue.
Use this code
try {
FileWriter fw = new FileWriter("path/of/file",true);
fw.write("myData");
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
First make sure you've given the required permission to write a file and that would be -
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
in Manifest file and
if (ContextCompat.checkSelfPermission(context,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_EXT_STORAGE);
}
in your activity.
Second please check your directory path. There might be some chances that you are using a wrong path. Easiest way to get a direct path for the Internal Storage is -
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data" + getApplicationContext().getPackageName();
File file = new File(path + "/File.txt");
You can use this method as per your requirement to write a file -
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(file));
outputStreamWriter.append("My Data");
outputStreamWriter.flush();
outputStreamWriter.close();
} catch (IOException e) {
e.printStackTrace();
}

Android: File Not Found Exception

I am trying to program a simple todo app for my android phone. Ive gotten far enough that I would like to save these strings that I input. However, every time I try to write the data I get a file not found exception. Here is the code I use in my onCreate method to instantiate the File.
File path = getFilesDir();
File itemFile = new File(path,"Todo_File.txt");
I then have two methods, one to write to the File, and the other to read from it. They look like this:`
public void readItems() {
try {
BufferedReader reader = new BufferedReader(new FileReader("Todo_File.txt"));
while(reader.readLine()!=null){
items.add(reader.readLine());
}
} catch(IOException e) {
e.printStackTrace();
}
}
and
public void writeItems() {
try{
BufferedWriter writer = new BufferedWriter(new FileWriter("Todo_File.txt"));
for(int i=0;i<items.size();i++){
writer.write(items.get(i));
}
} catch (IOException e){
e.printStackTrace();
}
}
items is a stringArray which holds the strings that were input. Every time that I try to write or read the files I get the following exception:
W/System.err: java.io.FileNotFoundException: Todo_File.txt (No such file or directory)
I don't understand why Android Studio cant find the file that I created, can anyone help?
You are looking for a file "Todo_File.txt".
Where have you kept this file?
Are you keeping it as a resource file in the "res/raw" directory of your app or it is lying somewhere in the phone storage?
Here you can get some idea of types of the storage
https://developer.android.com/guide/topics/data/data-storage.html
https://android.stackexchange.com/questions/112951/two-types-of-internal-storage-what-is-the-difference
Mostly likely I guess you need to correct the path of this file.
here are the way to get the "/storage/sdcard0/" path
Environment.getExternalStorageDirectory()
The standard way to do File-IO in Android is using the context-relevant IO-methods.
To write a file, use the following code. Details about the different file-modes are available here.
FileOutputStream fOut = openFileOutput("Todo_File.txt", MODE_WORLD_READABLE);
To read a file, use this:
FileInputStream fIn = openFileInput("Todo_File.txt");
Since you defined
File path = getFilesDir();
File itemFile = new File(path,"Todo_File.txt");
you can do:
public void readItems() {
try {
BufferedReader reader = new BufferedReader(new FileReader(itemFile));
while(reader.readLine()!=null){
items.add(reader.readLine());
}
} catch(IOException e) {
e.printStackTrace();
}
}
public void writeItems() {
try{
BufferedWriter writer = new BufferedWriter(new FileWriter(itemFile));
for(int i=0;i<items.size();i++){
writer.write(items.get(i));
}
} catch (IOException e){
e.printStackTrace();
}
}
You need to actually create the file before you write to it. You should do something like this:
File path = getFilesDir();
File itemFile = new File(path,"Todo_File.txt");
if (!path.exists()) {
path.mkdirs();
}
What you have done is simply tried to read from the file. The fact that you get the error:
W/System.err: java.io.FileNotFoundException: Todo_File.txt (No such file or directory)
Is an indication that the file you want to write to hasn't been created, and I don't see you creating the file anywhere.
If you are using an emulator, you need to make sure that you have an SDK card set up on your device, and then do:
File itemFile = new File(Environment.getExternalStorageDirectory(),"Todo_File.txt");
if (!path.exists()) {
path.mkdirs();
}

Write data continuously to file in external storage - Android App

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

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 App: Save a txt file that can be accessed through Explorer

I'm trying to create a txt file during the operation of my App which I then want to download onto my computer and assess the contents.
I've try both on the internal and external storage but I am still unable to find the text file after (when my tablet is plugged into my computer).
private void writeToFile(String data) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("orp.txt",Context.MODE_WORLD_WRITEABLE));
outputStreamWriter.write(data);
outputStreamWriter.close();
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),"orp2.txt");
String tempS = file.getAbsolutePath();
file.setReadable( true, false );
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(data);
bw.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
I have found been able to find either ("orp.txt" or "orp2.txt"), but also I do not receive any error during the running of the app, and the app is able to open "orp.txt" at a later time, so I know is has been created.
I cant find files created unless using Eclipse file explorer, or maybe its the media scan that has to be triggered, can be done by restarting the device. Scans the files available on the device.
It may be the directory, this is what I do in my code.
File f = new File(cxt.getExternalFilesDir(filepath), fileName);
f.createNewFile();
FileWriter writer = new FileWriter(f);
writer.append(manNo+System.getProperty("line.separator"));
writer.append(dateTime);
writer.flush();
writer.close();
Thanks for the input but I found the answer was to do with the media scanner, "orp2.txt" appeared in my download folder after I restarted the device.
This answer and blog post helped
Android: save file to downloads that can be viewed later

Categories

Resources