嗨,我在 Android Studio 上制作应用程序时遇到问题。我希望用户输入一些文本,然后单击保存按钮,这应该将文本文件保存在我的手机上。我有以下代码运行没有任何错误,但它没有做任何事情。我找不到它应该保存的文件。
public class TakeNotes extends Activity implements View.OnClickListener {
String content = "";
File file;
FileOutputStream outputStream;
TextView tv;
Button btnSave;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.take_notes);
tv = (TextView) findViewById(R.id.txtInput);
btnSave = (Button) findViewById(R.id.btnSave);
btnSave.setOnClickListener(this);
}
public void onClick(View v) {
if (v == findViewById(R.id.btnSave)) {
try {
file = new File(Environment.getExternalStorageDirectory(), "test.txt");
outputStream = new FileOutputStream(file);
outputStream.write(content.getBytes());
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
您需要在 Android 6.0(API 级别 23)及更高版本中添加运行时权限
这是代码 WRITE_EXTERNAL_STORAGE
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG,"Permission is granted");
return true;
}
像这样请求其他许可
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
这是官方文档
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句