如何使用SDCard文件夹而不是资源文件夹?

时间:2014-08-12 16:02:20

标签: android assets

我试图在SD卡中使用sdfolder中的.jpg图像而不是资源文件夹。 我仍然从资产文件夹中获取图像。 我认为问题出在这一行!

copy(getAssets().open(filename), new File(path) );

有人可以给我一些提示吗?

//create a folder in sdcard directory

File folder = new File(Environment.getExternalStorageDirectory() + "/sdfolder");

String[] urls = null;
List<String> items = new ArrayList<String>();


        try {

            //urls = getAssets().list(""); 
            urls = folder.list();

            for (String filename : urls) 
            {
                if (filename.matches(".+\\.jpg")) 
                {
                    String path = getFilesDir() + "/" + filename;
                    copy(getAssets().open(filename), new File(path) );
                    items.add(path);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        FilePagerAdapter pagerAdapter = new FilePagerAdapter(this, items);
        pagerAdapter.setOnItemChangeListener(new OnItemChangeListener()
        {
            @Override
            public void onItemChange(int currentPosition)
            {
                //Toast.makeText(GalleryFileActivity.this, "Current item is " + currentPosition, Toast.LENGTH_SHORT).show();
            }
        });

        mViewPager = (GalleryViewPager)findViewById(R.id.viewer);
        mViewPager.setOffscreenPageLimit(3);
        mViewPager.setAdapter(pagerAdapter);


 public void copy(InputStream in, File dst) throws IOException {

        OutputStream out = new FileOutputStream(dst);

        // Transfer bytes from in to out
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
    }

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。

只需替换copy(getAssets()。open(filename),new File(path));对

copy(new FileInputStream(new File(Environment.getExternalStorageDirectory()+&#34; / sdfolder /&#34; + filename)),new File(path));

谢谢!