Сначала добавьте эти правила;
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Запросите разрешения у действия;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//ASK HERE...
if (shouldAskPermissions()) {
askPermissions();
}
}
-
//// ASK METHODS
protected boolean shouldAskPermissions() {
return (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1);
}
protected void askPermissions() {
String[] permissions = {
"android.permission.READ_EXTERNAL_STORAGE",
"android.permission.WRITE_EXTERNAL_STORAGE"
};
int requestCode = 200;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(permissions, requestCode);
}
}
, затем для создания файла используйте этот код;
File directory = new File(Environment.getExternalStorageDirectory()+java.io.File.separator +"AppName");
try{
if(!directory.exists()) {
System.out.println("Directory created");
directory.mkdirs();
} else {
System.out.println("Directory is not created");
}
File f = new File(directory.getPath()+"/"+ "ENTER_FILE_NAME" + ".jpg");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
System.out.println("FILE PATH:" + f.getPath());
}catch(Exception e){
e.printStackTrace();
}