【问题标题】:Get file from res/raw folder从 res/raw 文件夹中获取文件
【发布时间】:2014-10-05 18:00:54
【问题描述】:

我需要文件方面的帮助。

        int aIdSound=R.raw.sound;  
        String path=getString(aIdSound); // return res/raw/sound.wav

        File file=new File(path);

        if(file.exists()){
            // File doesnt exist.

        }

所以我试过了

       InputStream input=getResources().openRawResource(aIdSound);

但我需要 File 类,那么有什么方法可以将 InputStream 更改为 File 或知道如何通过 id 获取文件?

【问题讨论】:

  • 你到底想做什么?播放声音?从生的?
  • 创建新文件,将输入流复制到它,并使用它...或使用使用流而不是文件的库

标签: android file inputstream


【解决方案1】:

您必须读取InputStream,将其写入带有FileOutputStream 的外部文件,以获取您的原始资源的File 实例。

或者我错过了一个 API。 :)

【讨论】:

    【解决方案2】:

    试试这个:

    final int resId = getResources().getIdentifier("fileName.wav", "raw", getPackageName());
    

    如果您尝试播放音频,您可能需要调查 MediaPlayer。这是我的使用方法:

    try {
            final MediaPlayer player = MediaPlayer.create(this, redId);
            mp.start();
            mp.setOnCompletionListener(new OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    mp.release();
                }
            });
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    

    如果您决定要使用外部保存的文件,那么您应该使用:

    File fis = new File(Environment.getExternalStorageDirectory().getPath() + "fileName" + ".wav");
    Uri external = Uri.fromFile(fis);
    
    final MediaPlayer player = MediaPlayer.create(this, external);
    

    【讨论】:

      【解决方案3】:

      将该文件放在Asserts 文件夹中

      您可以使用

      获取该文件
          DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
          DocumentBuilder docBuilder = dbf.newDocumentBuilder();
      
          // reading a assert file context.getAssets().open("filename.xml")
      
          Document doc = docBuilder.parse(context.getAssets().open("filename.xml"));
      

      或从外部文件夹(SD 卡)

       try{
          // Creating Input Stream 
          File file = new File(context.getExternalFilesDir(null), filename); 
          FileInputStream myInput = new FileInputStream(file);
          }catch (Exception e){
              e.printStackTrace(); 
              Toast.makeText(context, "Error in reading the file",   Toast.LENGTH_SHORT).show();
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-20
        相关资源
        最近更新 更多