fileNotFoundException: EROFS in android - android

I'm trying to create a .csv file in an android app. The app is supposed to create the file if there is none, or replace the file if it already exist. I tried to use the FileWriter, but it doesn't create the file and throws the 'FileNotFoundException: open failed: EROFS' exception.
I've already done some research, but I really can't find it. I have the permission in the manifest file (<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />) and the app folder is not open in any other app.
(I know there is opencsv, but since this is the only thing I need to do, I don't think I really need it.)
Here's my code:
FileWriter writer;
try {
writer = new FileWriter("data.csv");
for(Answer answer: answerList) {
writer.append(answer.getName());
writer.append(',');
writer.append(answer.getTime());
writer.append('\n');
}
writer.flush();
writer.close();
}
catch (Exception e) {
e.printStackTrace();
}
Thank you!

Change
writer = new FileWriter("data.csv");
to
writer = new FileWriter(getFilesDir()+File.separatorChar+"data.csv");
This will create the file in the internal storage.
You need to give the full path to where you want to create the file or where it exists already.

Related

How can I write a file to a folder of the internal storage on Android?

I have written a method which creates a file and writes data to the file and stores in the internal storage. When I get the absolute path or path of the file [I have added log messages to experiment with the operations on the File], it shows me that the file is getting created under the root directory and its under the /data/data/mypackagename/files/filename.txt. Nevertheless, I could find these folders on the DDMS where I could find the file which has been created by the method which I have written. But I am unable to open that file too as I don't have permissions.
When I look at my Android device, I can't find these directories. I looked up on stack overflow and some have answered that the /data/data folders in the internal storage are hidden and to access them I have to root the device which I don't want to do.
Next approach: There is a folder called as MyFiles on the android device [I am using Galaxy Tab 4 running Android 4.4 for testing]. Under this folder there is Device Storage directory which has various folders like Documents, Pictures, Music, Ringtones, Android, etc, etc.. So, the apps like camera, spread sheet apps, are able to write or save pictures into the pictures folder or txt files in the documents folder. Similarly, how could I write the file which I am creating in the function to the Documents folder or any other folder which could be accessible over the device. Please help me how could I do it, any help is appreciated.
The following is the code which I have written:
public void addLog(String power_level){
// creates a logFile in the root directory of the internal storage of the application.
// If the file does not exists, then it is created.
Log.d("AppendPower", "In addLog method");
//File logFile = new File(((Context)this).getFilesDir(), "logFile.txt");
File logFile = new File(getFilesDir(), "logFile.txt");
Log.d("FilesDir Path", getFilesDir().getAbsolutePath());
Log.d("FilesDir Name", getFilesDir().getName());
Log.d("Path on Android", logFile.getPath());
Log.d("Absolute Path on Android", logFile.getAbsolutePath());
Log.d("Parent", logFile.getParent());
if(!logFile.exists()){
try{
logFile.createNewFile();
}catch(IOException io){
io.printStackTrace();
}
}
try{
BufferedWriter writer = new BufferedWriter(new FileWriter(logFile, true));
writer.write("Battery level reading");
writer.append(power_level);
Log.d("Power_Level in try", power_level);
writer.newLine();
writer.close();
}catch(IOException e){
e.printStackTrace();
}
}
As you have figured out writing to root directories in Android is impossible unless you root the device. Thats why even some apps in Play-store asking for root permissions before installing the app. Rooting will void your warranty so i don't recommend it if you don't have serious requirement.
Other than root directories you can access any folder which are visible in your Android file manager.
Below is how you can write into sd with some data - Taken from : https://stackoverflow.com/a/8152217/830719
Use these code you can write a text file in SDCard along with you need to set permission in android manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
this is the code :
public void generateNoteOnSD(String sFileName, String sBody){
try
{
File root = new File(Environment.getExternalStorageDirectory(), "Notes");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
e.printStackTrace();
importError = e.getMessage();
iError();
}
}
.
1) If your purpose is debugging, you may just write to the /sdcard/. It always works.
2) Again, if your purpose is debugging, you may try to set read permissions on your app's directories. A while ago it worked for me on some Android devices (but did not work on at least one device).
Add this permission in your AndroidManifest.xml file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Then use this shortest recipe:
try
{
FileOutputStream fos =
openFileOutput("myfile.txt", getApplicationContext().MODE_PRIVATE);
fos.write("my text".getBytes());
fos.close();
}
catch (Exception exception)
{
// Do something, not just logging
}
It will be saved in "/data/data/my.package.name/files/" path.

Append to file outside external storage default folder in Android

I want to build a TXT file and add new lines to it every time.
I don't want it to be in the app data folder in external storage (default folder used in openFileOutput()) since it's erased as the app uninstalled (This is a log meant for these issues).
How can it be done ?
Use FileWriter. The constructor's second argument defines whether an existing file should be opened and appended.
FileWriter writer;
try {
writer = new FileWriter(yourFilePathHere, true);
writer.write("Hello World");
writer.flush();
writer.close();
} catch (IOException e) {
//Error handling
}
yourFilePathHere might be new File(getExternalStorageDirectory(), "log.txt").getAbsolutePath();

Robotium - Write to file in eclipse workspace or computer file system

I'm running some tests using Robotium on an Android application that interacts with a web-portal.
I'd like to save some information to file; for example I need to save the id of the username I created from the app and I want to make it read from Selenium to run tests on web-portal to verify a webpage for that user has been created.
Is it possible?
Could someone suggest me a solution or a work-around?
This is an example of code, but it doesn't work (I want to write to a file for example on c:\myworkspace\filename.txt a string):
public void test_write_file(){
if(!solo.searchText("HOME")){
signIn("39777555333", VALID_PASSWORD);
}
try {
String content = "This is the content to write into file";
File file = new File("filename.txt");
// 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(content);
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
assertTrue(solo.searchText("HOME"));
}
This code should write to file on device; my goal is to write on a file on machine from which I'm launching the script; the application under test should have permission to write to memory card; but I ask how to go out from Android Environment and get my Desktop environment.
For tests I suppose you will need xml format to be saved: Create xml file and save it in internal storage android
And then you will need to copy saved file from your device, see this How to copy selected files from Android with adb pull
You could be not so lazy and search it yourself.
For reading from a file or writing to file you would have to use normal java method. There you can create a separate method to read/write, which can be called whenever needed. you can see examples here for normal text file and excel file.

How to save file on external SDCARD on android MotorolaARTIX2 device?

I would like to save a file on external SdCard.I have implemented an application for save a file on external sdcard.But my Android MotorolaARTIX2 device contains internal sdcard.When i am trying to save file on external sdcard it always saving to internal sdcard in my device.
I have implemented my application as follows:
try {
File root = Environment.getExternalStorageDirectory();
if (root.canWrite()){
File file = new File(root, "myfile.txt");
FileWriter gpxwriter = new FileWriter(file);
BufferedWriter out = new BufferedWriter(gpxwriter);
out.write("Hello world");
out.close();
}
} catch (IOException e) {
Log.e("Exception", "Could not write file " + e.getMessage());
}
From the above code my application always saving myfile.txt file on internal sdcard but not external sdcard-ext.And my application is support all devices with same code.
How can i save myfile.txt on sdcard-ext(external) not on sdcard(internal) in my device?
please any body help me....
Motorola has an API for this. Look here: http://developer.motorola.com/docs/motorola-external-storage-api/ But that's not a good generic solution. You probably need to scan the filesystem for a more generic solution that will work on all devices.
Take a look at the answer from this question, especially the one from Baron

Write to SDCard file fails without exception

I have gone through multiple threads about SDcard file writing problems, but could not see a answer that would help me.
I have used
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
in my manifest for node.
2. Following code creates a file but doesn't write to it. Writer never throws an exception either. When I go back to SDCard and see the file created is of 0 kb. ( which is due to createnew function)
3. SDCard shows the file created with these permissions ----rwxr-x ( write not being there for others )
4. The behaviour is same on emulator or devices liek ASUS pad or Acer Iconia devices.
What is the regular way applications create files with content on SDCard from an Android application ?
if(isExternalStorageWritable()) {
File testFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),Filename);
try {
if (testFile.createNewFile()) {
Log.i(TAG + ": createSdcardFile","Empty file on external storage created");
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
openFileOutput(Filename, MODE_APPEND)));
out.write(Content);
out.close();
Log.i(TAG + ": createSdcardFile","Content to new file created");
created = true;
}
} catch(IOException e) {
Log.e(TAG,"Unable to create/write to new file on external storage. Terminating testCDMReadPositive");
Log.e(TAG,e.getMessage());
}
}
4.Using mode MODE_WORLD_WRITABLE gives same result i.e. a 0kb file on SDCard
5. Anyone with experience in writing files on externalstorage ( /mnt/sdcard ) would know how to do this. Any help or direction, highly appreciated. Thank you
Maybe a stupid suggestion, but did you delete the old testfile before the new run? Because your if clause will prevent writing to the file if it already existed.

Categories

Resources