Find real sd card path and write a file - android

My device is htc one dual sim and for some reason Environment.getExternalStorageDirectory() is my memory of the phone, it's not removable sd card.
I tried to find the real sd card path using this:
public static HashSet<String> getExternalMounts() {
final HashSet<String> out = new HashSet<String>();
String reg = "(?i).*vold.*(vfat|ntfs|exfat|fat32|ext3|ext4).*rw.*";
String s = "";
try {
final Process process = new ProcessBuilder().command("mount")
.redirectErrorStream(true).start();
process.waitFor();
final InputStream is = process.getInputStream();
final byte[] buffer = new byte[1024];
while (is.read(buffer) != -1) {
s = s + new String(buffer);
}
is.close();
} catch (final Exception e) {
e.printStackTrace();
}
// parse output
final String[] lines = s.split("\n");
for (String line : lines) {
if (!line.toLowerCase(Locale.US).contains("asec")) {
if (line.matches(reg)) {
String[] parts = line.split(" ");
for (String part : parts) {
if (part.startsWith("/"))
if (!part.toLowerCase(Locale.US).contains("vold"))
out.add(part);
}
}
}
}
return out;
}
And i got
/mnt/media_rw/ext_sd
I tried to write files to /mnt/media_rw/ext_sd/downloads
but the file didn't appear to be created.
File file = new File("/mnt/media_rw/ext_sd/downloads", "test.txt");
FileWriter writer = null;
try {
writer = new FileWriter(file);
writer.write("sdfsdfsfd");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
02-11 23:12:35.236 9110-9110/www.jenyakirmiza.com.testsdcard W/System.err﹕ java.io.FileNotFoundException: /mnt/media_rw/ext_sd/downloads/test.txt: open failed: EACCES (Permission denied)
I heard smth about restriction starting from 4.4 so now we can't write files to removable sd card. But they said you can write filed to /sdcardpath/Android/data/your.package.name
ps. of course i added write_external permisssion to manifest.

You can find all external storages with Context.getExternalMediaDirs and can check whether it is removable with Environment.isExternalStorageRemovable(File). Note that Downloads directory will most likely be only in the primary (emulated) external storage.

Try using Environment.getExternalStorageDirectory() method :
File file = new File(Environment.getExternalStorageDirectory() + "/Download/", "test.txt");
and you can evaluate first if your file really exists with exists() method :
File file = new File(Environment.getExternalStorageDirectory() + "/Download/", "test.txt");
if(file.exists()){
FileWriter writer = null;
try {
writer = new FileWriter(file);
writer.write("sdfsdfsfd");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Very important to have this permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
inside your
AndroidManifest.xml

Related

Android write to file not working

I am a beginner when it comes to Android. I encountered a problem, regarding writing to a file. I want to save to a file the input I get in a form. However, the piece of code that I wrote is not writing in my file. Could anyone please help me?
The code looks like that:
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StringBuilder s = new StringBuilder();
s.append("Event name: " + editText1.getText() + "|");
s.append("Date: " + editText2.getText() + "|");
s.append("Details: " + editText3.getText() + "|");
File file = new File("D:\\config.txt");
try {
BufferedWriter out = new BufferedWriter(new FileWriter(file, true), 1024);
out.write(s.toString());
out.newLine();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
So, I have a form containing 3 fields: the name of an event, the date and the description. These I want to save to my file. I should mention that I use an emulator for testing.
Use following path for file. It will write file to your root folder of storage.
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File file= new File(extStorageDirectory, "config.txt");
writeToFile("File content".getBytes(), file);
writeToFile
public static void writeToFile(byte[] data, File file) throws IOException {
BufferedOutputStream bos = null;
try {
FileOutputStream fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(data);
}
finally {
if (bos != null) {
try {
bos.flush ();
bos.close ();
}
catch (Exception e) {
}
}
}
}
Don't forget to add following permission in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
https://github.com/rznazn/GPS-Data-Logger/blob/master/app/src/main/java/com/example/android/gpsdatalogger/StorageManager.java
Here is a... nearly complete class for writing to the documents folder on the emulated external storage of the device.
Don't forget to add the write permissions to manifest.

Can't write in a file in the external storage

I need to write a simple text in a file "test.txt".
This is my code:
String SDCARD = Environment.getExternalStorageDirectory().getAbsolutePath();
String FILENAME = "test.txt";
File outfile = new File(SDCARD+File.separator+FILENAME);
if (outfile.exists()) { Log.d("Filename","the file exists"); }
Log.d("Filename",SDCARD+File.separator+FILENAME);
FileOutputStream fos = new FileOutputStream(outfile,true);
fos.write("just a test".getBytes());
fos.close();
In the manifest there is the permission request:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.xrobot.john.texttest">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
and the targetsdkversion is 15.
Logcat display this:
12-01 12:57:26.178 29663-29663/com.xrobot.john.softkeyboard D/Filename﹕ the file exists
12-01 12:57:26.178 29663-29663/com.xrobot.john.softkeyboard D/Filename﹕ /storage/emulated/0/test.txt
and the file text.txt is always empty.
Why ?
You are perhaps missing permission for reading that file.
Also, you are missing fos.flush() between fos.write() and fos.close() , that can easily cause that unexpected behavior.
Use a buffered writer to write your string to a file
BufferedWriter writer = null;
try
{
writer = new BufferedWriter( new FileWriter(SDCARD+File.separator+FILENAME));
writer.write( "just a test");
}
catch ( IOException e)
{
}
finally
{
try
{
if ( writer != null)
writer.close( );
}
catch ( IOException e)
{
}
}

how do you read a file(media) on a users sdcard and display the media on your app (android) [duplicate]

how to read a specific file from sdcard. i have pushed the file in sdcard through DDMS and i am trying to read it though this way but this give me exception. can anybody tell me how to point exactly on that file?
my code is this.
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
FileInputStream iStream = new FileInputStream(path);
You are trying to read a directory... what you need is the file! Do something like this... then, you can read the file as you want.
File dir = Environment.getExternalStorageDirectory();
File yourFile = new File(dir, "path/to/the/file/inside/the/sdcard.ext");
To read any file(CSV in my case) from External Storage, we need a path for it,once you have path you can do like this...
void readFileData(String path) throws FileNotFoundException
{
String[] data;
File file = new File(path);
if (file.exists())
{
BufferedReader br = new BufferedReader(new FileReader(file));
try
{
String csvLine;
while ((csvLine = br.readLine()) != null)
{
data=csvLine.split(",");
try
{
Toast.makeText(getApplicationContext(),data[0]+" "+data[1],Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
Log.e("Problem",e.toString());
}
}
}
catch (IOException ex)
{
throw new RuntimeException("Error in reading CSV file: "+ex);
}
}
else
{
Toast.makeText(getApplicationContext(),"file not exists",Toast.LENGTH_SHORT).show();
}
}
/*
csv file data
17IT1,GOOGLE
17IT2,AMAZON
17IT3,FACEBOOK*/

Android: Can't find generated XML file

I am working on a method that writes an XML file to the device. I've allowed external storage in the manifest file, but I can't find the file at the location it should be.
Here is my code:
public static void write (){
Serializer serial = new Persister();
File sdcardFile = new File("/Prueba/file.xml");
Item respuestas = new Item();
try {
serial.write(respuestas, 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());
}
}
Sdcard File path problem. Here is an exaple that write string in file.xml file.
File myFile = new File("/sdcard/file.xml");
try {
File myFile = new File("/sdcard/file.xml");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append("encodedString");
myOutWriter.close();
fOut.close();
} catch (Exception e) {
}
You able to get External Storage name by this way,
String root = Environment.getExternalStorageDirectory().toString();

reading a specific file from sdcard in android

how to read a specific file from sdcard. i have pushed the file in sdcard through DDMS and i am trying to read it though this way but this give me exception. can anybody tell me how to point exactly on that file?
my code is this.
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
FileInputStream iStream = new FileInputStream(path);
You are trying to read a directory... what you need is the file! Do something like this... then, you can read the file as you want.
File dir = Environment.getExternalStorageDirectory();
File yourFile = new File(dir, "path/to/the/file/inside/the/sdcard.ext");
To read any file(CSV in my case) from External Storage, we need a path for it,once you have path you can do like this...
void readFileData(String path) throws FileNotFoundException
{
String[] data;
File file = new File(path);
if (file.exists())
{
BufferedReader br = new BufferedReader(new FileReader(file));
try
{
String csvLine;
while ((csvLine = br.readLine()) != null)
{
data=csvLine.split(",");
try
{
Toast.makeText(getApplicationContext(),data[0]+" "+data[1],Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
Log.e("Problem",e.toString());
}
}
}
catch (IOException ex)
{
throw new RuntimeException("Error in reading CSV file: "+ex);
}
}
else
{
Toast.makeText(getApplicationContext(),"file not exists",Toast.LENGTH_SHORT).show();
}
}
/*
csv file data
17IT1,GOOGLE
17IT2,AMAZON
17IT3,FACEBOOK*/

Categories

Resources