1

I try to read all files that are stored in /data/data. This is the way that I try to do it:

try {
        String line;
        Runtime.getRuntime().exec( "/system/bin/su -c" );
        Runtime.getRuntime().exec( "cd /data/data" );
        Process p = Runtime.getRuntime().exec( "ls -l" );

        BufferedReader in = new BufferedReader( new InputStreamReader(p.getInputStream()) );
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
            in.close();
    }
    catch (Exception e) {
        System.out.println(e.toString());
    }

as error I get:

java.io.IOException: Error running exec(). Command: [cd, /data/data] Working Directory: null Environment: null

I also try to use:

Process p = Runtime.getRuntime().exec( "ls -l /data/data" );

but it returns nothing. But if I change it to "ls -l /data/data/com.example" it will show the files in my app package

Does someone know how read the files correctly?

EDIT:

With the same way I also want to read the files in /system/app e.g.

Boe-Dev
  • 1,585
  • 2
  • 14
  • 26
  • First get all packages name using package manager then,run command for each package as you saying for com.example – IshRoid May 07 '15 at 11:47
  • You can look at it. http://stackoverflow.com/questions/5527764/get-application-directory – Tarık Yurtlu May 07 '15 at 12:19
  • I think you miss understand it, it is not about my package, it about the files in the folder, also for /system/app – Boe-Dev May 07 '15 at 12:25
  • `su` is not "sticky" but applies only to the command (if any) it runs. We have countless questions about this here and don't need another. – Chris Stratton May 07 '15 at 13:22
  • If I put everything together it works with "/system/bin/su -c ls -l" but not with "/system/bin/su -c ls -l /data/data", and it does not return a error. I search a few hours before I ask this question... – Boe-Dev May 07 '15 at 13:35

2 Answers2

0

If you need to access information about the files, it might be easier to use File, as in:

File dir = new File("/data/data");
File[] files = dir.listFiles();
... do something with the files ...

As a more direct answer to your question, you might not have access to the directory. Unless the phone is rooted, you should not.

Sebastian
  • 1,076
  • 9
  • 24
-1
public class FileDialog {
    private static final String PARENT_DIR = "..";
    private final String TAG = getClass().getName();
    private String[] fileList;
    private File currentPath;

    public interface FileSelectedListener {
        void fileSelected(File file);
    }
    public interface DirectorySelectedListener {
        void directorySelected(File directory);
    }
    private ListenerList<FileSelectedListener> fileListenerList = new ListenerList<FileDialog.FileSelectedListener>();
    private ListenerList<DirectorySelectedListener> dirListenerList = new ListenerList<FileDialog.DirectorySelectedListener>();
    private final Activity activity;
    private boolean selectDirectoryOption;
    private String fileEndsWith;    

    private ArrayList<String> convertStreamToString(InputStream is) {


        ArrayList<String> data=new ArrayList<String>();
        String line;
        BufferedReader info = new BufferedReader(new InputStreamReader(is));
        try {
            while ((line = info.readLine()) != null) {

                    data.add(line);
                    }
            return data;

        } catch (Exception e) {
            Log.v("sat", ""+e);
        }
        return null;
       }
    /**
     * @param activity 
     * @param initialPath
     */
    public FileDialog(Activity activity, File path) {
        this.activity = activity;
        if (!path.exists()) path = Environment.getExternalStorageDirectory();
        loadFileList(path);


    }

    /**
     * @return file dialog
     */
    public Dialog createFileDialog() {
        Dialog dialog = null;
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);

        builder.setTitle(currentPath.getPath());
        if (selectDirectoryOption) {
            builder.setPositiveButton("Select directory", new OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Log.d(TAG, currentPath.getPath());
                    fireDirectorySelectedEvent(currentPath);
                }
            });
        }

        builder.setItems(fileList, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                String fileChosen = fileList[which];
                File chosenFile = getChosenFile(fileChosen);
                if (chosenFile.isDirectory()) {
                    loadFileList(chosenFile);
                    dialog.cancel();
                    dialog.dismiss();
                    showDialog();
                } else fireFileSelectedEvent(chosenFile);
            }
        });

        dialog = builder.show();
        return dialog;
    }


    public void addFileListener(FileSelectedListener listener) {
        fileListenerList.add(listener);
    }

    public void removeFileListener(FileSelectedListener listener) {
        fileListenerList.remove(listener);
    }

    public void setSelectDirectoryOption(boolean selectDirectoryOption) {
        this.selectDirectoryOption = selectDirectoryOption;
    }

    public void addDirectoryListener(DirectorySelectedListener listener) {
        dirListenerList.add(listener);
    }

    public void removeDirectoryListener(DirectorySelectedListener listener) {
        dirListenerList.remove(listener);
    }

    /**
     * Show file dialog
     */
    public void showDialog() {
        createFileDialog().show();
    }

    private void fireFileSelectedEvent(final File file) {
        fileListenerList.fireEvent(new FireHandler<FileDialog.FileSelectedListener>() {
            public void fireEvent(FileSelectedListener listener) {
                listener.fileSelected(file);
            }
        });
    }

    private void fireDirectorySelectedEvent(final File directory) {
        dirListenerList.fireEvent(new FireHandler<FileDialog.DirectorySelectedListener>() {
            public void fireEvent(DirectorySelectedListener listener) {
                listener.directorySelected(directory);
            }
        });
    }

    private void loadFileList(File path) {
        this.currentPath = path;
        List<String> r = new ArrayList<String>();
        if (path.exists()) {
            if (path.getParentFile() != null) r.add(PARENT_DIR);
            FilenameFilter filter = new FilenameFilter() {
                public boolean accept(File dir, String filename) {
                    File sel = new File(dir, filename);
                    if (!sel.canRead()) return false;
                    if (selectDirectoryOption) return sel.isDirectory();
                    else {
                        boolean endsWith = fileEndsWith != null ? filename.toLowerCase().endsWith(fileEndsWith) : true;
                        return endsWith || sel.isDirectory();
                    }
                }
            };
            String[] fileList1 = path.list(filter);
            for (String file : fileList1) {
                r.add(file);
            }
        }
        fileList = (String[]) r.toArray(new String[]{});
    }

    private File getChosenFile(String fileChosen) {
        if (fileChosen.equals(PARENT_DIR)) return currentPath.getParentFile();
        else return new File(currentPath, fileChosen);
    }
//--------------------------------------------------------------
    public void setFileEndsWith(String fileEndsWith) {
        this.fileEndsWith = fileEndsWith != null ? fileEndsWith.toLowerCase() : fileEndsWith;
    }
 }

class ListenerList<L> {
private List<L> listenerList = new ArrayList<L>();

public interface FireHandler<L> {
    void fireEvent(L listener);
}

public void add(L listener) {
    listenerList.add(listener);
}

public void fireEvent(FireHandler<L> fireHandler) {
    List<L> copy = new ArrayList<L>(listenerList);
    for (L l : copy) {
        fireHandler.fireEvent(l);
    }
}

public void remove(L listener) {
    listenerList.remove(listener);
}

public List<L> getListenerList() {
    return listenerList;
}
}


import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {

    Activity activity;
    Button btn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        activity=this;

         btn= (Button) findViewById(R.id.button);

        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                MyFileReader.openDialogToReadCSV(activity, MainActivity.this);

            }
        });

    }
}


public class MyFileReader {

    public static void openDialogToReadCSV(final Activity activity,final Context context)
    {
        File mPath = new File(Environment.getExternalStorageDirectory() + "//DIR//");
        FileDialog fileDialog = new FileDialog(activity, mPath);
        fileDialog.setFileEndsWith(".txt");
        fileDialog.addFileListener(new FileDialog.FileSelectedListener() {

            @Override
            public void fileSelected(File file) {
                new ReadFileContent(context,activity,file).execute(); //execute asyncTask to import data into database from selected file.            
            }
        });
        fileDialog.showDialog();
    }

    }


import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;


public class ReadFileContent extends AsyncTask<String, String, String> {

    Activity activity;
    Context context;
    File file=null;
    private ProgressDialog dialog;

    public ReadFileContent(Context context, Activity activity,File file) {
        this.context=context;
        this.activity=activity;
        this.file=file;
    }

    @Override
    protected void onPreExecute()
    {
        dialog=new ProgressDialog(context);
        dialog.setTitle("Importing Data into SecureIt DataBase");
        dialog.setMessage("Please wait...");
        dialog.setCancelable(false);
        dialog.setIcon(android.R.drawable.ic_dialog_info);
        dialog.show();
    }

@Override
protected String doInBackground(String... params) {

            String data="";
            Log.d(getClass().getName(), file.toString());

           try{
                 BufferedReader br = new BufferedReader(new FileReader(file));
                   String nextLine;

                  //here I am just displaying the CSV file contents, and you can store your file content into db from while loop...

                    while ((nextLine = br.readLine()) != null) {

                        data=data+br.readLine()+"\n";

                      }
                   return data;

            } catch (Exception e) {
                Log.e("Error", "Error for importing file");
            }
        return data="";

  }

protected void onPostExecute(String data)
  {

    if (dialog.isShowing())
    {
        dialog.dismiss();
    }

    if (data.length()!=0)
    {
        Toast.makeText(context, "File is built Successfully!"+"\n"+data, Toast.LENGTH_LONG).show();
    }else{
            Toast.makeText(context, "File fail to build", Toast.LENGTH_SHORT).show();
         }
   }


}

And Finally add this permission into AndroidManifest.xml file

 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Easily reads file using these classes... you just have to write a code in asyncTask to read all files...
You can utilize these code... I hope this will help you!

Abdul Rizwan
  • 3,904
  • 32
  • 31