Blackberry - 如何使用输入/输出流将文件复制到SD卡?

时间:2012-03-16 17:26:14

标签: java blackberry cordova

我正在尝试使用输入/输出流将我的Blackberry资源文件夹复制到SD卡。但是,我似乎无法让这个工作。运行Blackberry模拟器时,我收到一条错误消息,指示error: cannot find symbol inConn.close(); & outConn.close();。有人可以告诉我我做错了吗?

import com.phonegap.api.Plugin;
import com.phonegap.api.PluginResult;
import javax.microedition.io.*;
import javax.microedition.io.file.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.json.me.JSONArray;

public static PluginResult execute(JSONArray args) {
String[] resourseFileNames = {"file1","file2"."file3"};
final int length = resourseFileNames.length;

for(int i=0; i<length; i++) {
    String srcFile = "file:///store/home/user/sample/www" + resourseFileNames[i];
    FileConnection srcConn = (FileConnection) Connector.open(srcFile, Connector.READ);
    InputStream in = srcConn.openInputStream();
    String dstFile = "file:///SDCard/MyAppName/www" + resourseFileNames[i];
    FileConnection dstConn = (FileConnection)Connector.open(dstFile, Connector.WRITE);
    OutputStream out = dstConn.openOutputStream();
    // Copy the bits from instream to outstream
    byte[] buf = new byte[1024];
    int len;
    while ((len = in.read(buf)) > 0) {
        out.write(buf, 0, len);
    }
    in.close();
    inConn.close();
    out.close();
    outConn.close();
}
    String value = "OK";
return new PluginResult(PluginResult.Status.OK, value);
}

我正在使用Phonegap如果这有任何区别。感谢。

1 个答案:

答案 0 :(得分:3)

您没有正确打开流。相反,您应该为源文件和目标文件使用单独的FileConnection。然后用  FileConnection#openInputStream()打开InputStreamFileConnection#openOutputStream()打开OutputStream

代码段:

for(int i=0; i<length; i++) {
    try {
        String srcFile = "file:///store/home/user/sample/www" + resourseFileNames[i];
        FileConnection srcConn = (FileConnection) Connector.open(srcFile, Connector.READ);
        InputStream in = srcConn.openInputStream();

        String dstFile = "file:///SDCard/myAppName/www" + resourseFileNames[i];
        FileConnection dstConn = (FileConnection)Connector.open(dstFile, Connector.WRITE);
        OutputStream out = dstConn.openOutputStream();

        // Copy the bits from instream to outstream
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
           out.write(buf, 0, len);
        }

        in.close();
        srcConn.close();

        out.close();
        dstConn.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

更新1 :修正了导致“无法找到符号”错误的错误。

更新2 :使用try / catch包围代码(捕获IOException)。