同样的一段代码,在一个工程里能运行,另一个却不行。
public void writeToSD(View view) throws IOException {
qz = findViewById(R.id.qz);
xh = findViewById(R.id.xh);
String X = xh.getText().toString().trim();
String Y = qz.getText().toString().trim();
String coordinate = X + "," + Y + "," + "\r";
File dir = new File(Environment.getExternalStorageDirectory(), "point3");
if (!dir.exists()) {
dir.mkdir();
} else {
File file = new File(dir, SD_FILE_NAME);
try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)))) {
String stringBuffer = coordinate + "\n";
bw.write(stringBuffer);
} catch (Exception e) {
e.printStackTrace();
}
}
}
在能完美运行的app里,可以正常写入数据。在不能写入SD卡数据的app里,一点报错也没有。在sdcard/下面,既不创建文件夹,也不创建文件。
SD卡的读、写权限已经添加了。基本是照着能运行的代码抄。都无法创建文件。我还换了真机,照样不行。
能在SD里写入数据。
Android6.0之后读写权限需要动态申请,如果你没有写动态申请,那么你手动去该应用权限设置允许一下吧