0
伊馬初學者在機器人......我想知道爲什麼在我的代碼FOS成爲空這裏是我的主要activity.java文件FileOutputStream中和寫入方法
public class MainActivity extends AppCompatActivity {
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FileOutputStream fos = null;
TextView tv = (TextView) findViewById(R.id.tv);
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
try {
File root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
File dir = new File(root.getAbsolutePath() + "/musics");
dir.mkdir();
File file = new File(dir, "myData.txt");
fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fos.write("good morning".getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Log.e("fos", "null");
}
}
} else {
Toast.makeText(MainActivity.this, "permission not granted", Toast.LENGTH_LONG).show();
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 101);
}
tv.setText(fos + "");
}
@Override
public void onRequestPermissionsResult(int requestCode,String[] permissions,int[] grantResults) {
FileOutputStream fos = null;
if (requestCode == 101 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
try {
File root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
File dir = new File(root.getAbsolutePath() + "/musics");
dir.mkdir();
File file = new File(dir, "myData.txt");
fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fos.write("good morning".getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Log.e("fos", "null");
}
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
,這裏是日誌味精
05-25 16:37:06.311 21858-21858/com.example.kalyan.musicextra E/FOS:空
發佈ur清單文件plzz –
已在清單中添加了WRITE_EXTERNAL_STORAGE權限並處理了運行時權限https://developer.android.com/training/permissions/requesting.html – Pavan
您是否看到任何異常stacktraces?它看起來不是因爲興奮而被創建的,這就是爲什麼它是空的 –