在安卓设备上将文件存储到手机内部存储或者外部SD卡的代码示例如下:
- 存储到手机内部存储:
String filename = "myfile.txt";
String fileContents = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(fileContents.getBytes());
outputStream.close();
Toast.makeText(getApplicationContext(), "File saved to internal storage", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
- 存储到外部SD卡:
String filename = "myfile.txt";
String fileContents = "Hello world!";
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath() + "/mydir");
dir.mkdirs();
File file = new File(dir, filename);
try {
FileOutputStream outputStream = new FileOutputStream(file);
outputStream.write(fileContents.getBytes());
outputStream.close();
Toast.makeText(getApplicationContext(), "File saved to external storage", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
请注意,存储到外部SD卡需要在AndroidManifest.xml文件中添加权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
在Android中,如果要将数据存储到手机的SD卡中,可以使用以下代码:
-
首先,在AndroidManifest.xml文件中添加下面的权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
-
然后,在代码中使用以下方法来获取可用的SD卡路径:
public File getExternalStorageDirectory() { File sdCard = null; if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { sdCard = Environment.getExternalStorageDirectory(); } return sdCard; }
-
接下来,使用上述方法得到的SD卡路径来创建存储目录:
File storageDirectory = new File(getExternalStorageDirectory() , "目录名"); if (!storageDirectory.exists()) { storageDirectory.mkdirs(); }
-
最后,将文件保存到该存储目录中:
File file = new File(storageDirectory, "文件名"); try { FileOutputStream outputStream = new FileOutputStream(file); // 将数据写入文件 outputStream.write("数据".getBytes()); outputStream.close(); } catch (IOException e) { e.printStackTrace(); }
以上代码可以将数据存储到手机的SD卡中。请注意,在Android6.0及以上的系统版本中,还需要动态请求存储权限。
发布者:luotuoemo,转转请注明出处:https://www.jintuiyun.com/140935.html