George
George

Reputation: 5691

saving in sdcard saves file in wrong place

I have a file

String filename="MEMS.backup";

I use this to save:

InputStream myInput;

         File sdCard = Environment.getExternalStorageDirectory();
         File directory = new File (sdCard, "Myfolder"); 

            try {


 myInput = new FileInputStream(MyApplication.getAppContext().getFilesDir().getParentFile().getPath()+"/databases/MEMS");

                // Create the folder if it doesn't exist:
                if (!directory.exists()) 
                {
                    directory.mkdirs();
                } 

    OutputStream myOutput = new FileOutputStream(directory.getPath()+
                         filename);

and this to load:

OutputStream myOutput;

        File sdCard = Environment.getExternalStorageDirectory();
        File directory = new File (sdCard, "Myfolder");


        try {

myOutput= new FileOutputStream(MyApplication.getAppContext().getFilesDir().getParentFile().getPath()+"/databases/MEMS");

InputStream myInputs = new FileInputStream(directory.getPath()+filename);

The problem is that it creates "Myfolder" in sdcard but it is empty.

And the file "MEMS" goes just in sdcard (should be in Myfolder).

And the name of the file is MyfolderMEMS instead of MEMS.

I can't figure my mistake.

Upvotes: 1

Views: 126

Answers (3)

Nirali
Nirali

Reputation: 13825

Refer the below code for creating new file in myfolder

 File sdCard = Environment.getExternalStorageDirectory();
 File directory = new File (sdCard, "Myfolder"); 


if( !directory.exists() )
    directory.mkdirs();

File f = new File( directory, "my_file.jpg" );
OutputStream myOutput = new FileOutputStream(f);

Upvotes: 1

Aerrow
Aerrow

Reputation: 12134

I hope the problem is File separator is missing, try with this,

OutputStream myOutput = new FileOutputStream(directory.getPath()+File.separator+
                         filename);

or try with this,

OutputStream myOutput = new FileOutputStream(directory.getPath()+"/"+
                         filename);

Upvotes: 1

Blackbelt
Blackbelt

Reputation: 157467

Change

 OutputStream myOutput = new FileOutputStream(directory.getPath()+
                         filename);

with

File file = new File(directory, filename); 
OutputStream myOutput = new FileOutputStream(file);

Upvotes: 1

Related Questions