【问题标题】:reading a specific file from sdcard in android从android中的sdcard读取特定文件
【发布时间】:2011-04-16 08:22:02
【问题描述】:

如何从 sdcard 读取特定文件。我已经通过 DDMS 将文件推送到 sdcard 中,我试图通过这种方式读取它,但这给了我例外。谁能告诉我如何准确地指向那个文件?

我的代码是这样的。

String path = Environment.getExternalStorageDirectory().getAbsolutePath();
FileInputStream iStream =  new FileInputStream(path);

【问题讨论】:

    标签: android file android-sdcard


    【解决方案1】:

    您正在尝试读取目录...您需要的是文件!做这样的事情......然后,您可以根据需要读取文件。

    File dir = Environment.getExternalStorageDirectory();
    File yourFile = new File(dir, "path/to/the/file/inside/the/sdcard.ext");
    

    【讨论】:

    • 在我的应用程序中,我有一个存储在 sdcard 中的 contactbackup.vcf 文件。我怎样才能一一读取 .vcf 文件。@Cristian:
    • 您好,请问有没有返回文件名的方法?如果我不知道文件名。 @克里斯蒂安
    【解决方案2】:

    要从外部存储读取任何文件(在我的情况下为 CSV),我们需要它的路径,一旦你有了路径,你就可以这样做......

    void readFileData(String path) throws FileNotFoundException 
        {
    
            String[] data;
            File file = new File(path);
            if (file.exists())
            {
                BufferedReader br = new BufferedReader(new FileReader(file));
                try
                {
                    String csvLine;
                    while ((csvLine = br.readLine()) != null)
                    {
                        data=csvLine.split(",");
                        try
                        {
                            Toast.makeText(getApplicationContext(),data[0]+" "+data[1],Toast.LENGTH_SHORT).show();
                        }
                        catch (Exception e)
                        {
                            Log.e("Problem",e.toString());
                        }
                    }
                }
                catch (IOException ex)
                {
                    throw new RuntimeException("Error in reading CSV file: "+ex);
                }
            }
            else
            {
                Toast.makeText(getApplicationContext(),"file not exists",Toast.LENGTH_SHORT).show();
            }
        }
    
    /*
    csv file data
    
    17IT1,GOOGLE
    17IT2,AMAZON
    17IT3,FACEBOOK*/
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-16
      • 1970-01-01
      相关资源
      最近更新 更多