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;
}
Related
I am a newbie working with Android. A file is already created in the location data/data/myapp/files/hello.txt; the contents of this file is "hello". How do I read the file's content?
Take a look this how to use storages in android http://developer.android.com/guide/topics/data/data-storage.html#filesInternal
To read data from internal storage you need your app files folder and read content from here
String yourFilePath = context.getFilesDir() + "/" + "hello.txt";
File yourFile = new File( yourFilePath );
Also you can use this approach
FileInputStream fis = context.openFileInput("hello.txt");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
Read a file as a string full version (handling exceptions, using UTF-8, handling new line):
// Calling:
/*
Context context = getApplicationContext();
String filename = "log.txt";
String str = read_file(context, filename);
*/
public String read_file(Context context, String filename) {
try {
FileInputStream fis = context.openFileInput(filename);
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line).append("\n");
}
return sb.toString();
} catch (FileNotFoundException e) {
return "";
} catch (UnsupportedEncodingException e) {
return "";
} catch (IOException e) {
return "";
}
}
Note: you don't need to bother about file path only with file name.
Call To the following function with argument as you file path:
private String getFileContent(String targetFilePath) {
File file = new File(targetFilePath);
try {
fileInputStream = new FileInputStream(file);
} catch (FileNotFoundException e) {
Log.e("", "" + e.printStackTrace());
}
StringBuilder sb;
while (fileInputStream.available() > 0) {
if (null == sb) {
sb = new StringBuilder();
}
sb.append((char) fileInputStream.read());
}
String fileContent;
if (null != sb) {
fileContent = sb.toString();
// This is your file content in String.
}
try {
fileInputStream.close();
} catch (Exception e) {
Log.e("", "" + e.printStackTrace());
}
return fileContent;
}
String path = Environment.getExternalStorageDirectory().toString();
Log.d("Files", "Path: " + path);
File f = new File(path);
File file[] = f.listFiles();
Log.d("Files", "Size: " + file.length);
for (int i = 0; i < file.length; i++) {
//here populate your listview
Log.d("Files", "FileName:" + file[i].getName());
}
I prefer to use java.util.Scanner:
try {
Scanner scanner = new Scanner(context.openFileInput(filename)).useDelimiter("\\Z");
StringBuilder sb = new StringBuilder();
while (scanner.hasNext()) {
sb.append(scanner.next());
}
scanner.close();
String result = sb.toString();
} catch (IOException e) {}
For others looking for an answer to why a file is not readable especially on a sdcard, write the file like this first.. Notice the MODE_WORLD_READABLE
try {
FileOutputStream fos = Main.this.openFileOutput("exported_data.csv", MODE_WORLD_READABLE);
fos.write(csv.getBytes());
fos.close();
File file = Main.this.getFileStreamPath("exported_data.csv");
return file.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
return null;
}
Hi i'm trying to create a file if the file not already exists. Then I want to write 11 zeros in 11 rows if the file not already existed and then read it to an 2d array. But the app crashes and i got the message "java.io.FileNotFoundException: /FILENAME: open failed: ENOENT (No such file or directory)" in logcat. I would really appreciate if someone could help me.
Here is my code:
public void empt(String fileName) {
File file = getBaseContext().getFileStreamPath(fileName);
if(file.exists()){
return 1;
}
else return 2;
}
public int[][] readFile2(String fileName) {
empt(fileName);
if(empty == 1){
FileOutputStream outputStream;
String row = "0 0 0 0 0 0 0 0 0 0 0";
String newline = "\n";
try {
outputStream = openFileOutput(fileName, Context.MODE_PRIVATE);
for(int i = 0; i <11; i++)
{
if(i == 10){
outputStream.write(row.getBytes());
}
else {
outputStream.write(row.getBytes());
outputStream.write(line.getBytes());
}
}
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
String line = "";
int[][] data = new int [11][11];
try {
BufferedReader br = new BufferedReader(new FileReader(fileName));
int i = 0;
while((line = br.readLine()) != null) { // line becomes the whole line ( 11 numbers on a row)
String[] theline = line.split(" "); // theline becomes an array with 11 numbers
for(int k = 0; k<11; k++)
{
data[i][k] = (Integer.parseInt(theline[k]));
}
i++;
}
br.close();
}
catch(FileNotFoundException fN) {
fN.printStackTrace();
}
catch(IOException e) {
System.out.println(e);
}
return data;
}
to read from the internal storage you have to use openFileInput.
Change
BufferedReader br = new BufferedReader(new FileReader(fileName));
with
FileInputStream fstream = openFileInput(fileName);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
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
I am a newbie working with Android. A file is already created in the location data/data/myapp/files/hello.txt; the contents of this file is "hello". How do I read the file's content?
Take a look this how to use storages in android http://developer.android.com/guide/topics/data/data-storage.html#filesInternal
To read data from internal storage you need your app files folder and read content from here
String yourFilePath = context.getFilesDir() + "/" + "hello.txt";
File yourFile = new File( yourFilePath );
Also you can use this approach
FileInputStream fis = context.openFileInput("hello.txt");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
Read a file as a string full version (handling exceptions, using UTF-8, handling new line):
// Calling:
/*
Context context = getApplicationContext();
String filename = "log.txt";
String str = read_file(context, filename);
*/
public String read_file(Context context, String filename) {
try {
FileInputStream fis = context.openFileInput(filename);
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line).append("\n");
}
return sb.toString();
} catch (FileNotFoundException e) {
return "";
} catch (UnsupportedEncodingException e) {
return "";
} catch (IOException e) {
return "";
}
}
Note: you don't need to bother about file path only with file name.
Call To the following function with argument as you file path:
private String getFileContent(String targetFilePath) {
File file = new File(targetFilePath);
try {
fileInputStream = new FileInputStream(file);
} catch (FileNotFoundException e) {
Log.e("", "" + e.printStackTrace());
}
StringBuilder sb;
while (fileInputStream.available() > 0) {
if (null == sb) {
sb = new StringBuilder();
}
sb.append((char) fileInputStream.read());
}
String fileContent;
if (null != sb) {
fileContent = sb.toString();
// This is your file content in String.
}
try {
fileInputStream.close();
} catch (Exception e) {
Log.e("", "" + e.printStackTrace());
}
return fileContent;
}
String path = Environment.getExternalStorageDirectory().toString();
Log.d("Files", "Path: " + path);
File f = new File(path);
File file[] = f.listFiles();
Log.d("Files", "Size: " + file.length);
for (int i = 0; i < file.length; i++) {
//here populate your listview
Log.d("Files", "FileName:" + file[i].getName());
}
I prefer to use java.util.Scanner:
try {
Scanner scanner = new Scanner(context.openFileInput(filename)).useDelimiter("\\Z");
StringBuilder sb = new StringBuilder();
while (scanner.hasNext()) {
sb.append(scanner.next());
}
scanner.close();
String result = sb.toString();
} catch (IOException e) {}
For others looking for an answer to why a file is not readable especially on a sdcard, write the file like this first.. Notice the MODE_WORLD_READABLE
try {
FileOutputStream fos = Main.this.openFileOutput("exported_data.csv", MODE_WORLD_READABLE);
fos.write(csv.getBytes());
fos.close();
File file = Main.this.getFileStreamPath("exported_data.csv");
return file.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
return null;
}