使用android中的Stream类从sdcard读取二进制文件

问题描述 投票:0回答:1

任何人都可以知道如何使用Streams读取位于sdcard的二进制文件,如InputstreamCountingInputStreamSwappedDataInputStream

我正在使用这三个流来读取当前在Resources folder中的文件,但现在我想在sdcard中移动该文件,但我无法更改这些流,因为我已经做了很多工作而且我无法回滚我的工作。 我是这样做的,但它给了我FileNotFoundException。我需要你的帮助。

AssetManager assetManager = getResources().getAssets(); 
final File folder = new File(Environment.getExternalStorageDirectory() + "/map");
boolean success = false;         
if(!folder.exists()){
    success = folder.mkdir(); 
} else {
    Log.i("folder already exists", "folder already exists"); 
}

try {
    iStream = assetManager.open(Environment.getExternalStorageDirectory().getAbsolutePath().concat("/map/map.amf"));
} catch (IOException e) { 
    // TODO Auto-generated catch block  
    e.printStackTrace();        
}       
cis = new CountingInputStream(iStream);
input = new SwappedDataInputStream(cis);

非常感谢任何建议。

java android file filestream
1个回答
1
投票

这是一个简单的方法,只是将输入流的内容复制到输出流:

    /**
     * Copy the content of the input stream into the output stream, using a
     * temporary byte array buffer whose size is defined by
     * {@link #IO_BUFFER_SIZE}.
     * 
     * @param in
     *            The input stream to copy from.
     * @param out
     *            The output stream to copy to.
     * 
     * @throws java.io.IOException
     *             If any error occurs during the copy.
     */
    public static void copy(InputStream in, OutputStream out)
                    throws IOException {
            byte[] b = new byte[IO_BUFFER_SIZE];
            int read;
            while ((read = in.read(b)) != -1) {
                    out.write(b, 0, read);
            }
    }

它取自我之前制作的应用程序:http://code.google.com/p/meneameandroid/source/browse/trunk/src/com/dcg/util/IOUtilities.java

为了确保dir存在于您想要写入/读取数据的位置,我使用了以下内容:

    /**
     * Prepares the SDCard with all we need
     */
    private void prepareSDCard() {
        // Create app dir in SDCard if possible
        File path = new File("/sdcard/MyAppDirectory/");
        if(! path.isDirectory()) {
            if ( path.mkdirs() )
            {
                Log.d(TAG,"Directory created: /sdcard/MyAppDirectory");
            }
            else
            {
                Log.w(TAG,"Failed to create directory: /sdcard/MyAppDirectory");
            }
        }
    }

从SD卡写入/读取的权限是:

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

编辑:链接已更新

© www.soinside.com 2019 - 2024. All rights reserved.