java - 使用Android中的Stream类从SD卡读取二进制文件

标签 java android file filestream

任何人都可以知道如何使用 Streams 读取驻留在 sdcard 中的二进制文件,例如 InputstreamCountingInputStream交换数据输入流

我正在使用这三个流来读取当前位于 Resources 文件夹 中的文件,但现在我想将该文件移动到 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);

非常感谢您的建议。

最佳答案

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

    /**
     * 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);
            }
    }

取 self 不久前制作的一个应用程序:http://code.google.com/p/meneameandroid/source/browse/trunk/src/com/dcg/util/IOUtilities.java

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

    /**
     * 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" />

已编辑:链接已更新

关于java - 使用Android中的Stream类从SD卡读取二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3862581/

相关文章:

c - 与互斥锁同步文件

java - 如何在 Android 中打开具有 Uri 的文件?

java - java程序退出时调用函数

java - instanceof 运算符在原始和包装器类型数组的情况下

java - 如何将回调函数从Java传递到Kotlin类

android - 自定义小部件 : Error inflating class

Linux:用一个异常文件删除所有早于某个日期的文件

java - 为什么要对 lambda 输入参数执行强制转换?

android - 从 SqliteDatabase 创建字节数组以使用 Google Saved Games 保存它?

android - 如何将数据从 Activity 的异步任务传递到 fragment