简体   繁体   English

Android写入SD卡

[英]android writing to sdcard

I am not able to write to the SDCARD. 我无法写SDCARD。 I can not create a Directory or a File, what am I missing I have this in the manifest 我无法创建目录或文件,清单中缺少此内容

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

And this in my code 这在我的代码中

btnSave.setOnClickListener(new View.OnClickListener() 
        {
            public void onClick(View arg0) 
            {   
                // Create a directory; all ancestor directories must exist
                    boolean success = (new File("/sdcard/Methods/")).mkdirs();
                //create file   
                    try{
                    File myFile = new File("/sdcard/Methods/Method 1 Square.xml");
                    File file = myFile;
                        // Create file if it does not exist
                        boolean success1 = file.createNewFile();}   
                    catch (IOException e) 
                        {}
                //write to file
                    try {
                        BufferedWriter out = new BufferedWriter(new FileWriter("/sdcard/Methods/Method 1 Square.xml"));
                        out.write ("<?xml version=\"1.0\"?>");
                        out.write ("<?mso-application progid=\"Excel.Sheet\"?>");
                        out.write ("Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"");
                        out.close();
                    } // end try
                    catch (IOException e) 
                    {
                    } // end catch

            } // end public

        }); // end SAVE Button

1st Thing: 第一件事:

Just check the 'success' variable, whether it returns really true . 只需检查“成功”变量,是否返回true即可

2nd Thing: 第二件事:

As you have hard coded the /sdcard, Instead i suggest you get the directory using: Environment.getExternalStorageDirectory() because in some devices the sd-card root directory is /mnt/sdcard so the above method to get root directory. 由于已经对/ sdcard进行了硬编码,因此我建议您使用以下目录来获取目录: Environment.getExternalStorageDirectory()因为在某些设备中sd卡的根目录是/ mnt / sdcard,因此上述获取根目录的方法。

3rd Thing: 第三件事:

You should first check whether the SD-card is mounted or not. 您应该首先检查SD卡是否已安装。

Example: 例:

File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdcard.getAbsolutePath() + "/dir/subdir");  // in your case, just give /Methods

dir.mkdirs();
File file = new File(dir, "filename");  // in your case, just give "Method 1 Square.xml"

FileOutputStream f = new FileOutputStream(file);

The problem may be that the directories in the path do not exist. 问题可能是路径中的目录不存在。 With that FileWriter constructor, if the file does not exist it is created but that doesn't include the directories. 使用该FileWriter构造函数,如果文件不存在,则创建该文件,但不包括目录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM