I want to create a directory on "/mnt/extsd/MyFolder" this path. while calling mkdir() it returns false.I inserted the sdcard on my tablet, got the external path as "/mnt/extsd" and trying to create a folder on this path. Below is my code,
File lSDCardDirFile = new File("/mnt/extsd/MyFolder");
if (!lSDCardDirFile.exists()) {
System.out.println("Is folder created --- " + lSDCardDirFile.mkdirs());
}
I gave the permissions, .
I want to create the folder in External sd card which is removable sd card.
I am using android 4.0 ICS version device.
I created a different method for getting paths fom external SD card,
public static String[] getStorageDirectories()
{
String[] lDirs = null;
BufferedReader lBufferReader = null;
try {
lBufferReader = new BufferedReader(new FileReader("/proc/mounts"));
ArrayList list = new ArrayList();
String lStrline;
while ((lStrline = lBufferReader.readLine()) != null) {
if (lStrline.contains("vfat") || lStrline.contains("/mnt")) {
StringTokenizer lTokenizer = new StringTokenizer(lStrline, " ");
String lStrPath = lTokenizer.nextToken();
lStrPath = lTokenizer.nextToken(); // Take the second token, i.e. mount point
if (lStrPath.equals(Environment.getExternalStorageDirectory().getPath())) {
list.add(lStrPath);
}
else if (lStrline.contains("/dev/block/vold")) {
if (!lStrline.contains("/mnt/secure") && !lStrline.contains("/mnt/asec") && !lStrline.contains("/mnt/obb") && !lStrline.contains("/dev/mapper") && !lStrline.contains("tmpfs")) {
list.add(lStrPath);
}
}
}
}
lDirs = new String[list.size()];
for (int i = 0; i < list.size(); i++) {
lDirs[i] = (String) list.get(i);
}
}
catch (FileNotFoundException e) {}
catch (IOException e) {}
finally {
if (lBufferReader != null) {
try {
lBufferReader.close();
} catch (IOException e) {
}
}
}
return lDirs;
}`
From this method I got the path, but while trying to create a directory, the mkdir() returns false.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I have two folders like extSdCard and sdcard in my samsung galaxy s3.
Use the below code to choose.
private String[] mFilePaths;
File storageDir = new File("/mnt/");
if(storageDir.isDirectory()){
File[] dirList = storageDir.listFiles();
for (int i = 0; i < dirList.length; i++)
{
mFilePaths[i] = dirList[i].getAbsolutePath();
System.out.println("...................................."+mFilePaths[i]);
}
}
File Dir;
if(android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))//check if sd card is mounted
{
Dir=new File(android.os.Environment.getExternalStorageDirectory(),"your folder name");
if(!Dir.exists())// if directory is not here
Dir.mkdirs() // make directory
}
Edit
To get the paths of internal and external storage. below code works on samsung galaxy s3.
String externalpath = new String();
String internalpath = new String();
public void getExternalMounts() {
Runtime runtime = Runtime.getRuntime();
try
{
Process proc = runtime.exec("mount");
InputStream is = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
String line;
BufferedReader br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
if (line.contains("secure")) continue;
if (line.contains("asec")) continue;
if (line.contains("fat")) {//external card
String columns[] = line.split(" ");
if (columns != null && columns.length > 1) {
externalpath = externalpath.concat("*" + columns[1] + "n");
}
}
else if (line.contains("fuse")) {//internal storage
String columns[] = line.split(" ");
if (columns != null && columns.length > 1) {
internalpath = internalpath.concat(columns[1] + "n");
}
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println("Path of sd card external............"+externalpath);
System.out.println("Path of internal memory............"+internalpath);
}
Now you can use the path os external storage to create a folder.
if(android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))//check if sd card is mounted
{
Dir=new File(externalpath,"your folder name");
if(!Dir.exists())// if directory is not here
Dir.mkdirs() // make directory
}
Do you have declared permission in Manifest.xml file?
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Also I suggest you to not going for HardCoded path of /mnt/extsd/ Instead of it just use Environment.getExternalStorageDirectory().getPath().
final String PATH = Environment.getExternalStorageDirectory() + "/myfolder/";
if(!(new File(PATH)).exists())
new File(PATH).mkdirs();
include permission in manifest::
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Add permission in Manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
File sdDir = Environment.getExternalStorageDirectory();
Related
I want to know if it is possible to get all folders with pictures on smartphone.
How can I get those folders?
I don't want only the pictures on this folder (where are the photos taken with the camera):
Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+ Environment.DIRECTORY_DCIM + "/"
Thanks.
You can query all the files within your storage recursively using
file.listfile();
and then check their extensions with
public static String getExtension(File f) {
String ext = null;
String s = f.getName();
int i = s.lastIndexOf('.');
if (i > 0 && i < s.length() - 1) {
ext = s.substring(i + 1).toLowerCase();
}
return ext;
}
This way you can get all the pictures in your storage. Then you can use any string format method or file.getParent to get their folder.
you need 2 list. one for storing folders and one for files. and you must dynamically add files and folders to this list. in each directory you must search for all files and folders. if file that you searched is file then you add it to file list else you add it to the folders list. then again you do this for all folders in list of folders.
Maybe use Linux Power. I create simple example.
InputStream is = null;
ByteArrayOutputStream out = null;
String[] files = null;
try {
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
String[] command = new String[]{"ls", "-R", path, "| grep .png" };
ProcessBuilder builder = new ProcessBuilder(command);
builder.redirectErrorStream();
builder.directory(Environment.getExternalStorageDirectory());
Process process = builder.start();
is = process.getInputStream();
out = new ByteArrayOutputStream();
int count = 0;
byte[] buffer = new byte[1024];
while((count = is.read(buffer)) > 0){
out.write(buffer, 0, count);
}
out.flush();
files = new String(out.toByteArray()).split("\n");
} catch (IOException e) {
e.printStackTrace();
} finally{
if(is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(out != null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
List<String> imageFiles = new ArrayList<String>();
for(String file : files){
if(file.endsWith(".png") || file.endsWith(".jpeg") || file.endsWith(".jpg") || file.endsWith(".gif")){
imageFiles.add(file);
}
}
I am working on a app that can connect to a USB SD card reader.
The problem is the USB path is not the same for all the phones. I know that in Samsung phones the USB path is "/storage/UsbDriveA/"
My question is how can I find the USB mount path for all phone devices?
thank you
private String getAllStoragePath() {
String finalPath = "";
try {
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("mount");
InputStream inputStream = process.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
String line;
String[] pathArray = new String[4];
int i = 0;
BufferedReader br = new BufferedReader(inputStreamReader);
while ((line = br.readLine()) != null) {
String mount = "";
if (line.contains("secure"))
continue;
if (line.contains("asec"))
continue;
if (line.contains("fat")) {// TF card
String columns[] = line.split(" ");
if (columns.length > 1) {
mount = mount.concat(columns[1] + "/someFiles");
pathArray[i++] = mount;
// check directory inputStream exist or not
File dir = new File(mount);
if (dir.exists() && dir.isDirectory()) {
// do something here
finalPath = mount;
break;
}
}
}
}
for(String path:pathArray){
if(path!=null){
finalPath =finalPath + path +"\n";
}
}
} catch (Exception e) {
e.printStackTrace();
}
return finalPath;
}
How to read and write files to removable sd card in Android?
I want to store Android Id in Text file. The text file should be created on external sdcard.
Code:
PackageManager m = getPackageManager();
String s = getPackageName();
PackageInfo p = m.getPackageInfo(s, 0);
s = p.applicationInfo.dataDir;
File myFile = new File(s + "/MyDoople.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(TxtS.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),"Text Updated",Toast.LENGTH_SHORT).show();
The Second is
File sdCard = new File("file:///mnt/external_sd/");
File myFile = new File(sdCard, "test.txt");
FileWriter writer = new FileWriter(myFile);
writer.append(TESTSTRING);
writer.flush();
writer.close();
Try the below. Use Environment.getExternalStorageDirectory() to get the path
File dir =new File(android.os.Environment.getExternalStorageDirectory(),"MyFolder");
if(!dir.exists())
{
dir.mkdirs();
}
String filename= "MyDoople.txt";
try
{
File f = new File(dir+File.separator+filename);
FileOutputStream fOut = new FileOutputStream(f);
OutputStreamWriter myOutWriter = new OutputStreamWriter(
fOut);
myOutWriter.append("Mytest");
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Text Updated",
Toast.LENGTH_SHORT).show();
}
catch(Exception e)
{
e.printStackTrace();
}
To update:
try
{
FileWriter fileWritter = new FileWriter(f,true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write("Mydata");
bufferWritter.close();
}
catch(Exception e)
{
e.printStackTrace();
}
Result on my device when i opened with a text file viewer.
Edit:
The below is hackish and not the recommended way.
In my device (Samsung Galaxy s3) my internal phone memory is named sdCard0 and my external
extSdcard. This Environment.getExternalStorageDirectory() will give path of internl memory. In such cases you can use the below to get path of external memory.
String externalpath = new String();
String internalpath = new String();
public void getExternalMounts() {
Runtime runtime = Runtime.getRuntime();
try
{
Process proc = runtime.exec("mount");
InputStream is = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
String line;
BufferedReader br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
if (line.contains("secure")) continue;
if (line.contains("asec")) continue;
if (line.contains("fat")) {//external card
String columns[] = line.split(" ");
if (columns != null && columns.length > 1) {
externalpath = externalpath.concat("*" + columns[1] + "\n");
}
}
else if (line.contains("fuse")) {//internal storage
String columns[] = line.split(" ");
if (columns != null && columns.length > 1) {
internalpath = internalpath.concat(columns[1] + "\n");
}
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println("Path of sd card external............"+externalpath);
System.out.println("Path of internal memory............"+internalpath);
}
private static String getExternalStoragePath(Context mContext) {
StorageManager mStorageManager = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE);
Class<?> storageVolumeClazz = null;
try {
storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");
Method getPath = storageVolumeClazz.getMethod("getPath");
Method isRemovable = storageVolumeClazz.getMethod("isRemovable");
Object result = getVolumeList.invoke(mStorageManager);
final int length = Array.getLength(result);
for (int i = 0; i < length; i++) {
Object storageVolumeElement = Array.get(result, i);
String path = (String) getPath.invoke(storageVolumeElement);
boolean removable = (Boolean) isRemovable.invoke(storageVolumeElement);
if (removable == true) {
return path;
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
and enter this code.
It return path of SD Card path if SD card is available
and then you can use that path .
String sdCardPath = getExternalStoragePath(context);
File Path1 = new File(sdCardPath + "NewFolder");
if (!Path1.exists()) {
Path1.mkdir();
}
File file = new File(Path1, "test.txt");
Maybe you forget these permissions.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
package com.example.writeinsdcard;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import android.os.Environment;
import android.util.Log;
import android.widget.TextView;
public class MainActivity extends Activity {
private static final String TAG = "Sdcard";
private TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
tv = (TextView) findViewById(R.id.TextView01);
checkExternalMedia();
writeToSDFile();
readRaw();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/** Method to check whether external media available and writable. This is adapted from
http://developer.android.com/guide/topics/data/data-storage.html#filesExternal */
private void checkExternalMedia(){
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// Can read and write the media
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// Can only read the media
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
// Can't read or write
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
tv.append("\n\nExternal Media: readable="
+mExternalStorageAvailable+" writable="+mExternalStorageWriteable);
}
/** Method to write ascii text characters to file on SD card. Note that you must add a
WRITE_EXTERNAL_STORAGE permission to the manifest file or this method will throw
a FileNotFound Exception because you won't have write permission. */
private void writeToSDFile(){
// Find the root of the external storage.
// See http://developer.android.com/guide/topics/data/data-storage.html#filesExternal
File root = android.os.Environment.getExternalStorageDirectory();
tv.append("\nExternal file system root: "+root);
File dir = new File (root.getAbsolutePath() + "/download");
dir.mkdirs();
File file = new File(dir, "myData.txt");
try {
FileOutputStream f = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(f);
pw.println("Howdy do to you.");
pw.println("Here is a second line.");
pw.flush();
pw.close();
f.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.i(TAG, "File not found. Did you" +
" add a WRITE_EXTERNAL_STORAGE permission to the manifest?");
} catch (IOException e) {
e.printStackTrace();
}
tv.append("\n\nFile written to:\n"+file);
}
/** Method to read in a text file placed in the res/raw directory of the application. The
method reads in all lines of the file sequentially. */
private void readRaw(){
tv.append("\n\nData read from res/raw/textfile.txt:\n");
InputStream is = this.getResources().openRawResource(R.raw.textfile);
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr, 8192); // 2nd arg is buffer size
// More efficient (less readable) implementation of above is the composite expression
/*BufferedReader br = new BufferedReader(new InputStreamReader(
this.getResources().openRawResource(R.raw.textfile)), 8192);*/
try {
String test;
while (true){
test = br.readLine();
// readLine() returns null if no more lines in the file
if(test == null) break;
tv.append("\n"+" "+test);
}
isr.close();
is.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
tv.append("\n\nThat is all");
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.writesdcard"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19" />
<!--permission to write external storage -->
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.writesdcard.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
My question is solved.
I directly use the path "/mnt/external_sd/.. Path of File.".
But it was only work with my Device
i wanted to show only .xml files to user which is currently present in the sd card.i try the following but it shows all files in my sdcard including directories
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("text/xml");
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(Intent.createChooser(intent, "Select XML File"), SelectXMLFILE);
Use the following code and manipulate it according to your needs
File sdcardPath = new File(Environment.getExternalStorageDirectory().getPath() +"/SomeFolder");
List<String> list;
list = new ArrayList<String>();
list=sdcardPath.listFiles();
Now loop through the list and check each file name and apply endWith("xml"); function on the items to get all xml files. Hope it works.
Loop in it like that
List<String> XMLFiles= new ArrayList<String>();
for(int i=0; i<=list.size(); i++)
{
XMLFiles.add(list.get(i).endsWith("xml"));
}
I have samsung galaxy s3 with android 4.1.2. My internal phone memory is named sdcard0 and my external card extSdCard.
Environment.getExternalStorageDirectory()
So the above returns the path of sdcard0 which is internal phone memory
In such cases to get the actual path you can use the below
String externalpath = new String();
String internalpath = new String();
public void getExternalMounts() {
Runtime runtime = Runtime.getRuntime();
try
{
Process proc = runtime.exec("mount");
InputStream is = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
String line;
BufferedReader br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
if (line.contains("secure")) continue;
if (line.contains("asec")) continue;
if (line.contains("fat")) {//external card
String columns[] = line.split(" ");
if (columns != null && columns.length > 1) {
externalpath = externalpath.concat("*" + columns[1] + "\n");
}
}
else if (line.contains("fuse")) {//internal storage
String columns[] = line.split(" ");
if (columns != null && columns.length > 1) {
internalpath = internalpath.concat(columns[1] + "\n");
}
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println("Path of sd card external............"+externalpath);
System.out.println("Path of internal memory............"+internalpath);
}
Once you get the path.
File dir= new File(android.os.Environment.getExternalStorageDirectory());
//Instead of android.os.Environment.getExternalStorageDirectory() you can use internalpath or externalpath
Then call
walkdir(dir);
ArrayList<String> filepath= new ArrayList<String>();//contains list of all files ending with .xml
public void walkdir(File dir) {
String xmlPattern = ".xml";
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
walkdir(listFile[i]);
} else {
if (listFile[i].getName().endsWith(xmlPattern)){
//Do what ever u want
filepath.add( listFile[i].getAbsolutePath());
}
}
}
}
}
What's wrong with the code? I added the permission already. Logcat isn't printing the message it's supposed to show.
I'm guessing I have to use a filestream?
public class Run {
int abc = 2;
int[] myIntArray = {1,2,3};
String texts = "abcabac";
//Person p = new Person();
Paragraph p = new Paragraph(abc, texts, myIntArray);
Serializer serializer = new Persister();
File file = new File("paragraphs.xml");
private final static String TAG = Run.class.getCanonicalName();
String a = "writeing something nothing";
// Now write the level out to a file
Serializer serial = new Persister();
//File sdDir = Environment.getExternalStorageDirectory(); should use this??
//File sdcardFile = new File("/sdcard/paragraphs.xml");
File sdcardFile = new File(Environment.getExternalStorageDirectory().getPath());
{
try {
serial.write(p, sdcardFile);
} catch (Exception e) {
// There is the possibility of error for a number of reasons. Handle this appropriately in your code
e.printStackTrace();
}
Log.i(TAG, "XML Written to File: " + sdcardFile.getAbsolutePath());
}
I have samsung galaxy s3 with android 4.1.2. My internal phone memory is named sdcard0 and my external card extSdCard.
Environment.getExternalStorageDirectory()
So the above returns the path of sdcard0 which is internal phone memory
In such cases to get the actual path you can use the below
String externalpath = new String();
String internalpath = new String();
public void getExternalMounts() {
Runtime runtime = Runtime.getRuntime();
try
{
Process proc = runtime.exec("mount");
InputStream is = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
String line;
BufferedReader br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
if (line.contains("secure")) continue;
if (line.contains("asec")) continue;
if (line.contains("fat")) {//external card
String columns[] = line.split(" ");
if (columns != null && columns.length > 1) {
externalpath = externalpath.concat("*" + columns[1] + "\n");
}
}
else if (line.contains("fuse")) {//internal storage
String columns[] = line.split(" ");
if (columns != null && columns.length > 1) {
internalpath = internalpath.concat(columns[1] + "\n");
}
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println("Path of sd card external............"+externalpath);
System.out.println("Path of internal memory............"+internalpath);
}
Once you get the path you can use the below.
Try the below
String filename = "filename.xml";
File file = new File(Environment.getExternalStorageDirectory(), filename);
//Instead of Environment.getExternalStorageDirectory() you can use internalpath or externalpath from the above code.
FileOutputStream fos;
byte[] data = new String("data to write to file").getBytes();
try {
fos = new FileOutputStream(file);
fos.write(data);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
// handle exception
} catch (IOException e) {
// handle exception
}
//to get sdcard path
String sdcardpath = Environment.getExternalStorageDirectory().getPath();
//to write a file in sd card
File file = new File("/sdcard/FileName.txt");
if (!file.exists()) {
file.mkdirs();
}
Permission to add in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
you have to do
filename is test.xml,text.jpg or test.txt
File sdcardFile = new File(Environment.getExternalStorageDirectory()+"/"+filename);
cehck this link.
for more detail about External Storage