【问题标题】:read and write files to removable sd card读取和写入文件到可移动 sd 卡
【发布时间】:2019-05-18 19:42:37
【问题描述】:

如何在Android中读写文件到可移动sd卡?

我想将 Android Id 存储在文本文件中。文本文件应在外部 sdcard 上创建。

代码:

PackageManager m = getPackageManager();
String s = getPackageName();
PackageInfo p = m.getPackageInfo(s, 0);
s = p.applicationInfo.dataDir;
File myFile = new File(s + "/MyDoople.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(TxtS.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),"Text Updated",Toast.LENGTH_SHORT).show();

第二个是

 File sdCard = new File("file:///mnt/external_sd/");
 File myFile = new File(sdCard, "test.txt");
 FileWriter writer = new FileWriter(myFile); 
 writer.append(TESTSTRING);
 writer.flush(); 
 writer.close();

【问题讨论】:

  • 你尝试了什么......向我们展示......
  • 我编辑了我的问题,请再看一遍。
  • 这很糟糕 - file:///mnt/external_sd/ 你怎么知道它存在? Environment.getExternalStorageDirectory()
  • @Simon- Environment.getExternalStorageDirectory() 显示设备的外部存储器(inbulid)。但我想使用可移动设备,即设备的辅助内存。我已经尝试过显示您的链接。

标签: android android-memory


【解决方案1】:

试试下面的。使用 Environment.getExternalStorageDirectory() 获取路径

  File dir =new File(android.os.Environment.getExternalStorageDirectory(),"MyFolder");
    if(!dir.exists())
    {
           dir.mkdirs();
    }    
    String filename= "MyDoople.txt";
    try
    {
    File f = new File(dir+File.separator+filename);

    FileOutputStream fOut = new FileOutputStream(f);
    OutputStreamWriter myOutWriter = new OutputStreamWriter(
            fOut);
    myOutWriter.append("Mytest");
    myOutWriter.close();
    fOut.close();
    Toast.makeText(getBaseContext(),
            "Text Updated",
            Toast.LENGTH_SHORT).show();
   }
    catch(Exception e)
    {
        e.printStackTrace();
    }

更新:

try
{

FileWriter fileWritter = new FileWriter(f,true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write("Mydata");
bufferWritter.close();
}
 catch(Exception e)
 {
e.printStackTrace();
 }

当我使用文本文件查看器打开时,我的设备上的结果。

编辑:

下面是hackish,不是推荐的方式。

在我的设备 (Samsung Galaxy s3) 中,我的内部手机内存被命名为 sdCard0,而我的外部 扩展卡。这个 Environment.getExternalStorageDirectory() 将给出内部内存的路径。在这种情况下,您可以使用以下方法获取外部存储器的路径。

String externalpath = new String();
String internalpath = new String();

public  void getExternalMounts() {
Runtime runtime = Runtime.getRuntime();
try
{
Process proc = runtime.exec("mount");
InputStream is = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
String line;

BufferedReader br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
    if (line.contains("secure")) continue;
    if (line.contains("asec")) continue;

    if (line.contains("fat")) {//external card
        String columns[] = line.split(" ");
        if (columns != null && columns.length > 1) {
            externalpath = externalpath.concat("*" + columns[1] + "\n");
        }
} 
        else if (line.contains("fuse")) {//internal storage
        String columns[] = line.split(" ");
        if (columns != null && columns.length > 1) {
            internalpath = internalpath.concat(columns[1] + "\n");
        }
    }
}
}
catch(Exception e)
{
    e.printStackTrace();
}
  System.out.println("Path  of sd card external............"+externalpath);
  System.out.println("Path  of internal memory............"+internalpath);
}

【讨论】:

  • 我已经获得了路径,但是当我的代码写入或读取文件时,就会发生错误。错误是:java.io.FileNotFoundException:打开失败:ENOENT(没有这样的文件或目录)对不起我的英语......
  • @Aman 检查您是否创建了目录。如果你做得对,它应该可以工作。以上适用于我的设备,我已经发布了快照
  • @Aman 我遇到了一个对 funbook 有同样问题的用户。我建议您在其他设备上尝试,然后在此处发布结果
  • @Raghunandan- 我复制粘贴您的代码及其工作。但它会在手机内存中创建一个文件。我不想在手机内存中创建文件。我想在外部存储卡中创建或写入文件。
  • @Aman 你尝试过编辑吗?通过使用编辑中的代码来使用外部路径。还要在不同的设备上测试它以检查行为是否重复
【解决方案2】:
private static String getExternalStoragePath(Context mContext) {

    StorageManager mStorageManager = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE);
    Class<?> storageVolumeClazz = null;
    try {
        storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
        Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");
        Method getPath = storageVolumeClazz.getMethod("getPath");
        Method isRemovable = storageVolumeClazz.getMethod("isRemovable");
        Object result = getVolumeList.invoke(mStorageManager);
        final int length = Array.getLength(result);
        for (int i = 0; i < length; i++) {
            Object storageVolumeElement = Array.get(result, i);
            String path = (String) getPath.invoke(storageVolumeElement);
            boolean removable = (Boolean) isRemovable.invoke(storageVolumeElement);
            if (removable == true) {
                return path;
            }
        }
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
    return null;
}

并输入此代码。

如果SD卡可用,则返回SD卡路径的路径

然后你就可以使用那个路径了。

String sdCardPath = getExternalStoragePath(context);
File Path1 = new File(sdCardPath + "NewFolder");
    if (!Path1.exists()) {
        Path1.mkdir();
    }
File file = new File(Path1, "test.txt");

【讨论】:

  • 即使代码是不言自明的,请给出更多解释。
【解决方案3】:

也许你忘记了这些权限。

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

【讨论】:

  • 我已经在 Manifest 文件中使用了这个权限。它仅用于存储设备的外部存储器而不是可移动存储器。
【解决方案4】:
      package com.example.writeinsdcard;

       import android.os.Bundle;
       import android.app.Activity;
       import android.view.Menu;
       import java.io.BufferedReader;
       import java.io.File;
       import java.io.FileNotFoundException;
       import java.io.FileOutputStream;
       import java.io.IOException;
       import java.io.InputStream;
       import java.io.InputStreamReader;
       import java.io.PrintWriter;
       import android.os.Environment;
       import android.util.Log;
       import android.widget.TextView;

       public class MainActivity extends Activity {

             private static final String TAG = "Sdcard";
             private TextView tv;

             @Override
             protected void onCreate(Bundle savedInstanceState) {
                      super.onCreate(savedInstanceState);
                      setContentView(R.layout.fragment_main);

                      tv = (TextView) findViewById(R.id.TextView01);
                      checkExternalMedia();
                      writeToSDFile();
                      readRaw();

             }

             @Override
             public boolean onCreateOptionsMenu(Menu menu) {
                      // Inflate the menu; this adds items to the action bar if it is present.
                      getMenuInflater().inflate(R.menu.main, menu);
                      return true;
             }

             /** Method to check whether external media available and writable. This is adapted from
          http://developer.android.com/guide/topics/data/data-storage.html#filesExternal */

             private void checkExternalMedia(){
                      boolean mExternalStorageAvailable = false;
                      boolean mExternalStorageWriteable = false;
                      String state = Environment.getExternalStorageState();

                      if (Environment.MEDIA_MOUNTED.equals(state)) {
                               // Can read and write the media
                               mExternalStorageAvailable = mExternalStorageWriteable = true;
                      } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
                               // Can only read the media
                               mExternalStorageAvailable = true;
                               mExternalStorageWriteable = false;
                      } else {
                               // Can't read or write
                               mExternalStorageAvailable = mExternalStorageWriteable = false;
                      }   
                      tv.append("\n\nExternal Media: readable="
                                     +mExternalStorageAvailable+" writable="+mExternalStorageWriteable);
             }

             /** Method to write ascii text characters to file on SD card. Note that you must add a 
          WRITE_EXTERNAL_STORAGE permission to the manifest file or this method will throw
          a FileNotFound Exception because you won't have write permission. */

             private void writeToSDFile(){

                      // Find the root of the external storage.
                      // See http://developer.android.com/guide/topics/data/data-storage.html#filesExternal

                      File root = android.os.Environment.getExternalStorageDirectory(); 
                      tv.append("\nExternal file system root: "+root);


                      File dir = new File (root.getAbsolutePath() + "/download");
                      dir.mkdirs();
                      File file = new File(dir, "myData.txt");

                      try {
                               FileOutputStream f = new FileOutputStream(file);
                               PrintWriter pw = new PrintWriter(f);
                               pw.println("Howdy do to you.");
                               pw.println("Here is a second line.");
                               pw.flush();
                               pw.close();
                               f.close();
                      } catch (FileNotFoundException e) {
                               e.printStackTrace();
                               Log.i(TAG, "File not found. Did you" +
                               " add a WRITE_EXTERNAL_STORAGE permission to the manifest?");
                      } catch (IOException e) {
                               e.printStackTrace();
                      } 
                      tv.append("\n\nFile written to:\n"+file);
             }

             /** Method to read in a text file placed in the res/raw directory of the application. The
             method reads in all lines of the file sequentially. */

             private void readRaw(){
                      tv.append("\n\nData read from res/raw/textfile.txt:\n");
                      InputStream is = this.getResources().openRawResource(R.raw.textfile);
                      InputStreamReader isr = new InputStreamReader(is);
                      BufferedReader br = new BufferedReader(isr, 8192);    // 2nd arg is buffer size

                      // More efficient (less readable) implementation of above is the composite expression
                      /*BufferedReader br = new BufferedReader(new InputStreamReader(
                               this.getResources().openRawResource(R.raw.textfile)), 8192);*/

                      try {
                               String test; 
                               while (true){                
                                     test = br.readLine();   
                                     // readLine() returns null if no more lines in the file
                                     if(test == null) break;
                                     tv.append("\n"+"    "+test);
                               }
                               isr.close();
                               is.close();
                               br.close();
                      } catch (IOException e) {
                               e.printStackTrace();
                      }
                      tv.append("\n\nThat is all");
             }
       }

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.writesdcard"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="19" />
    <!--permission to write external storage  -->
    <uses-permission 
        android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.writesdcard.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

【讨论】:

    【解决方案5】:

    我的问题解决了。 我直接使用路径“/mnt/external_sd/.. Path of File.”。

    但它只适用于我的设备

    【讨论】:

      猜你喜欢
      • 2014-07-05
      • 2021-05-30
      • 2015-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-28
      • 1970-01-01
      相关资源
      最近更新 更多