Как создать папку на SdCard и как копировать файлы из одного в другой - PullRequest
0 голосов
/ 30 марта 2012

В этом проекте я пытаюсь скопировать файлы с SDCard (например, изображения в DICM) в папку корзины каждый раз, когда пользователь нажимает кнопку удаления.Но я столкнулся с проблемой.Я могу удалить файлы, но не могу их скопировать.

C.Java - Использование для назначения каталогов.

package com.haha.recyclebin;

public class C 
{

    public static String SDCARD = "/mnt/sdcard";
    public static String RECYCLE_BIN_ROOT = SDCARD+"/.Recycle";
}

U.Java - Использование для копирования файла из одной папки на SD-карте в Recycle Folder.

package com.haha.recyclebin;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class U 
{

    public static void copyFile(File sourceLocation, File targetLocation)
            throws FileNotFoundException, IOException 
            {

        U.debug("copying from "+sourceLocation.getAbsolutePath()+" to "+targetLocation.getAbsolutePath());

        String destDirPath = targetLocation.getParent();
        File destDir = new File(destDirPath);
        if(!destDir.exists()){
            destDir.mkdirs();
        }

        InputStream in = new FileInputStream(sourceLocation);
        OutputStream out = new FileOutputStream(targetLocation);

        // Copy the bits from instream to outstream
        byte[] buf = new byte[1024*512];
        int len;
        while ((len = in.read(buf)) > 0) {
            System.out.println("papa");
            out.write(buf, 0, len);
            System.out.println(">");
        }
        System.out.println(".");
        in.close();
        out.close();
    }

    public static void debug(Object msg){
        System.out.println(msg);
    }
}

RecycleActivity - использование U.java и C.java в этом коде: -

package com.haha.recyclebin;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.Set;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Toast;

public class RecycleActivity extends Activity {

    private OnClickListener exitListener = new OnClickListener()
    {

        @Override
        public void onClick(DialogInterface paramDialogInterface, int paramInt) 
        {
            RecycleActivity.this.finish();
        }
    };

    /**
     * need a standalone class to hold data (file name)
     */
    private final class DeleteFileListener implements OnClickListener 
    {

        String file = null;

        /**
         * @param file the file to set
         */
        public void setFile(String file)
        {
            this.file = file;
        }

        @Override
        public void onClick(DialogInterface paramDialogInterface, int paramInt)
        {

            RecycleActivity.this.prepareRecyclebin();

            File src = new File(file);
            String destPath = C.RECYCLE_BIN_ROOT+file;

            File dest = new File(destPath);


            try 
            {
                U.copyFile(src, dest); /* using U.java here */
                src.delete();
                String msg = RecycleActivity.this.getResources().getString(R.string.deleted) + destPath;
                Toast.makeText(RecycleActivity.this, msg, Toast.LENGTH_SHORT).show();
            } catch (Exception e) 
            {
                e.printStackTrace();
                Toast.makeText(RecycleActivity.this, R.string.delete_failed, Toast.LENGTH_SHORT).show();
            }


            RecycleActivity.this.finish();
        }
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);


        Intent intent = getIntent();
        debugIntent(intent);

        Bundle extras = intent.getExtras();

        /* For File Explorer */
        Object obj = extras.get(Intent.EXTRA_INTENT);
        if(null!=obj){
            Intent it2 = (Intent) obj;
            Bundle ex2 = it2.getExtras();
            Object obj2 = ex2.get(Intent.EXTRA_STREAM);
            if(null!=obj2){
                Uri uri = (Uri) obj2;
                String file = uri.getPath();
                System.out.println("file: "+file);
                toRecyclebin(file);
            }
        }

    }

    /**
     * @param file
     */
    private void toRecyclebin(String file) 
    {

        if(!file.startsWith(C.SDCARD))
        {
            promptLimit();
            return;
        }

        String conf = this.getResources().getString(R.string.confirm_delete);
        conf+="\n\n"+file;

        DeleteFileListener listener = new DeleteFileListener();
        listener.setFile(file);

        new AlertDialog.Builder(this)
        .setMessage(conf)
        .setPositiveButton(R.string.yes, listener)
        .setNegativeButton(R.string.no, exitListener)
        .show();
    }

    /**
     * 
     */
    private void promptLimit() 
    {
        new AlertDialog.Builder(this)
        .setMessage(R.string.limit)
        .setPositiveButton(R.string.ok, exitListener)
        .show();
    }

    /**
     * @param intent
     */
    private void debugIntent(Intent intent) 
    {
        System.out.println("intent: "+intent);
        Bundle extras = intent.getExtras();
        Set<String> keys = extras.keySet();
        for(String key:keys){
            Object value = extras.get(key);
            System.out.println("-["+key+"]:["+value+"]");
            if(value instanceof Intent){
                Intent intent2 = (Intent) value;
                Bundle ext2 = intent2.getExtras();
                Set<String> ks2 = ext2.keySet();
                for(String k:ks2){
                    Object v2 = ext2.get(k);
                    System.out.println("--["+k+"]:["+v2+"]");
                    if(v2 instanceof Intent){
                        Intent i3 = (Intent) v2;
                        Bundle e3 = i3.getExtras();
                        Set<String> ks3 = e3.keySet();
                        for(String kk:ks3){
                            Object v3 = e3.get(kk);
                            System.out.println("---["+kk+"]:["+v3+"]");
                        }
                    }
                }
            }
        }

        Uri data = intent.getData();

        System.out.println("data: "+data);

    }

    void prepareRecyclebin(){
        File root = new File(C.RECYCLE_BIN_ROOT);
        if(!root.exists()){
            root.mkdirs();
        }
    }
}

У меня есть файловый менеджер, который работает нормально, я могу видеть изображения и музыку на SDCard, и я могу удалить также.Но после удаления они должны перейти в папку Recycle (как указано в C.java).Я создал Recycle Folder (/ mnt / sdcard / Recycle) вручную, используя проводник в eclipse.

Но я не вижу файлов в папке recycle.

Есть ли проблемы с кодом?

Буду признателен за любую помощь.

Спасибо !!

Ответы [ 2 ]

2 голосов
/ 30 марта 2012

Отладили ли вы и убедитесь, что копировальный файл был выполнен?

И это функция My CopyFile, и они совершенно одинаковые:

public static boolean copyFile(String from, String to) {
    try {
        int bytesum = 0;
        int byteread = 0;
        File oldfile = new File(from);
        if (oldfile.exists()) {
            InputStream inStream = new FileInputStream(from);
            FileOutputStream fs = new FileOutputStream(to);
            byte[] buffer = new byte[1444];
            while ((byteread = inStream.read(buffer)) != -1) {
                bytesum += byteread;
                fs.write(buffer, 0, byteread);
            }
            inStream.close();
            fs.close();
        }
        return true;
    } catch (Exception e) {
        return false;
    }
}
0 голосов
/ 30 марта 2012

Попробуйте следующий код, он будет работать.

public void Save_To_Phone(Bitmap bitmap){    
    try {
      FileOutputStream os = new FileOutputStream(YourSDCardPath);
      bitmap.compress(CompressFormat.JPEG, 80, os);
      os.close();
    } catch (Exception e) {
      Log.w("ExternalStorage", "Error writing file", e);
    }
  }
...