在Android中的内部存储特定文件夹中写入文件

时间:2017-10-03 06:51:18

标签: android

我想在特定文件夹的内部存储中写一个文件,在创建fileoutputStream时出错。 以下是我的代码:

String filePath = ctx.getFilesDir().getPath().toString() +"/"+folderName;
Log.d("filePath",filePath);
file= new File(filePath, filename);
final FileOutputStream fileOutput = new FileOutputStream(file);

2 个答案:

答案 0 :(得分:1)

你可以这样走。

File directory = new File("path_to_directory");
try {
if(!file.exists()) {
directory.createNewFile();
}
File dataFile = new File(directory, "Your File Name");
FileOutputStream stream = new FileOutputStream(dataFile, true); // true if append is required.
stream.write();
stream.flush()
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (null != stream) {
stream.close();
}

此处path_to_directory = Environment.getExternalStorageDirectory() + File.seperator + "FolderName";

OR

path_to_directory = ctx.getFilesDirectory() + File.seperator + "FolderName";

顺便说一下,在根目录之前,你不能在android的内部存储中创建一个文件夹。它肯定会给你IOException,因为没有root,android内部FS是只读的。所以要注意这一点。

谢谢, 快乐编码: - )

答案 1 :(得分:0)

好的,如果你想将它从凌空保存(或下载并保存到特定文件夹)这里代码

DownloadManager.Request request = new DownloadManager.Request(
            downloadUri);

    request.setAllowedNetworkTypes(
            DownloadManager.Request.NETWORK_WIFI
                    | DownloadManager.Request.NETWORK_MOBILE)
            .setAllowedOverRoaming(false).setTitle(notesName)
           // .setDescription("Something useful. No, really.")
            .setDestinationInExternalPublicDir("/YOUR PATH"+"/"+OTHER PATH, notesName)
            .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);