Android Studio:如何保存文件



我正在执行这段代码来保存一些数据到我的android手机中的文件,但当保存它的FileNotFoundException触发器,我不知道为什么,因为我从许多不同的地方复制,但不适合我。

提示?

public void safeToExcelFile(View view) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1000);
}
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
String fileName = "hola" + ".txt";
String contenido = "pues algo a ver si va";
File root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_NOTIFICATIONS);
File dir = new File(root.getAbsolutePath()+"/MyAppFile");
if(!dir.exists()) {
dir.mkdir();
}
File file = new File(dir, fileName);
Toast.makeText(this, dir.getPath(), Toast.LENGTH_LONG).show();
try{
FileOutputStream fos = new FileOutputStream(file);
fos.write(contenido.getBytes());
fos.close();
Toast.makeText(this, "Se guardo", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
Toast.makeText(this, "Archivo no encontrado", Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (IOException e) {
Toast.makeText(this, "Error al guardar", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}else{
Toast.makeText(this, "No puedes guardar", Toast.LENGTH_LONG).show();
}
}

Toma hermano

requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1000);
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
String fileName = "hola" + ".txt";
String contenido = "pues algo a ver si va";
String path = getExternalFilesDir(null) + "/" + fileName;
try{
FileOutputStream fos = new FileOutputStream(path);
fos.write(contenido.getBytes());
fos.close();
Toast.makeText(this, "Se guardo", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
Toast.makeText(this, "Archivo no encontrado", Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (IOException e) {
Toast.makeText(this, "Error al guardar", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}else{
Log.d("Error", "No hay permiso");
}

请将日志删除路径设置为verás dónde se guarda el fichero。

我终于找到了答案,如果你感兴趣的话,我从https://blog.cindypotvin.com/saving-data-to-a-file-in-your-android-application/上得到了答案

try {
File testFile = new File(this.getExternalFilesDir(null), "Cuentas.csv");
if (!testFile.exists())
testFile.createNewFile();
Toast.makeText(this, testFile.getPath(), Toast.LENGTH_LONG).show();
// Adds a line to the file
BufferedWriter writer = new BufferedWriter(new FileWriter(testFile, true));
writer.write("This is a test file.");
writer.close();
// Refresh the data so it can seen when the device is plugged in a
// computer. You may have to unplug and replug the device to see the
// latest changes. This is not necessary if the user should not modify
// the files.
MediaScannerConnection.scanFile(this,
new String[]{testFile.toString()},
null,
null);
} catch (IOException e) {
//Log.e("ReadWriteFile", "Unable to write to the TestFile.txt file.");
Toast.makeText(this, "Error al guardar", Toast.LENGTH_LONG).show();
}

最新更新