27

我想将内部存储上的文件保存到特定文件夹中。我的代码是:

File mediaDir = new File("media");
if (!mediaDir.exists()){
   mediaDir.createNewFile();
   mediaDir.mkdir();

}
File f = new File(getLocalPath());
f.createNewFile();
FileOutputStream fos = new FileOutputStream(f);
fos.write(data);
fos.close();

getLocalPath返回/data/data/myPackage/files/media/qmhUZU.jpg,但是当我想创建媒体文件夹时,我得到了异常“java.io.IOException:只读文件系统”。任何想法如何在文件夹媒体中的内部手机存储中写入我的文件?谢谢。

4

5 回答 5

23

您应该像这样使用ContextWrapper

ContextWrapper cw = new ContextWrapper(context);
File directory = cw.getDir("media", Context.MODE_PRIVATE);

与往常一样,请参阅文档ContextWrapper提供了很多东西。

于 2011-02-16T15:07:44.693 回答
2

您应该创建media附加到getLocalPath()返回内容的目录。

于 2011-02-16T14:02:14.317 回答
2

我也得到了同样的错误。这是修复。当您指定写入位置时,Android 会自动将您的路径解析为/data//mnt/sdcard/。让我解释。

如果执行以下语句:

File resolveMe = new File("/data/myPackage/files/media/qmhUZU.jpg");
resolveMe.createNewFile();

它将解析到/data/Android 中更高位置的根路径。

我想通了,因为在执行以下代码后,它会自动放置在根目录中,/mnt/而无需我自己翻译任何内容。

File resolveMeSDCard = new File("/sdcard/myPackage/files/media/qmhUZU.jpg");
resolveMeSDCard.createNewFile();

快速解决方法是更改​​以下代码:

File f = new File(getLocalPath().replace("/data/data/", "/"));

希望这可以帮助

于 2011-08-10T18:19:47.097 回答
0

写一个文件

将文件保存到内部存储时,您可以通过调用以下两种方法之一获取适当的目录作为文件:

获取文件目录()

      Returns a File representing an internal directory for your app.

获取缓存目录()

     Returns a File representing an internal directory for your 
     app's temporary cache files.
     Be sure to delete each file once it is no longer needed and implement a reasonable 
     size limit for the amount of memory you use at any given time, such as 1MB.

注意:如果系统存储空间不足,它可能会在不发出警告的情况下删除您的缓存文件。

于 2018-03-19T11:01:34.683 回答
-3

嗨试试这个它会在里面创建目录+文件

File mediaDir = new File("/sdcard/download/media");
if (!mediaDir.exists()){
    mediaDir.mkdir();
}

File resolveMeSDCard = new File("/sdcard/download/media/hello_file.txt");
resolveMeSDCard.createNewFile();
FileOutputStream fos = new FileOutputStream(resolveMeSDCard);
fos.write(string.getBytes());
fos.close();

System.out.println("Your file has been written");  
于 2012-04-19T23:53:47.577 回答