I'm using an HTC Desire 610 for Android development. I followed the examples in other answers to the same question, but all my file saves end up on internal device storage, and not the SD card. The phone definitely recognizes the SD card, and from within the phone I can transfer files to the SD card.
I tried hard-coding the file path to the SD card, and I also tried running the app while not plugged into the computer - all to no avail. It is extremely important that my app be able to save these files directly to the SD card. Any ideas?
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
writeDataToFile("2394872934729348");
}
public void writeDataToFile(String data){
BufferedWriter bufferedWriter = null;
String dataOutFileName = Environment.getExternalStorageDirectory().getAbsolutePath()+"/data.txt";
try{
bufferedWriter = new BufferedWriter(new FileWriter(dataOutFileName,true));
bufferedWriter.write(data);
bufferedWriter.flush();
}
catch (IOException e){
e.printStackTrace();
}
finally {
try {
if(bufferedWriter != null){
bufferedWriter.close();
}
} catch (IOException e){
e.printStackTrace();
}
}
MediaScannerConnection.scanFile(this,new String[]{dataOutFileName}, null,null);
}
}
EDIT: I'm now trying this. I get a FileNotFoundException unless I write directly to the package file (com.mypackage etc)
File dataDir = new File("/storage/ext_sd/Data/");
dataDir.mkdirs();
File outputFile = new File(dataDir,"data.txt");
try{
FileOutputStream fos = new FileOutputStream(outputFile);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fos);
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e){
Log.e("Exception", "File write failed: " + e.toString());
}