0

我们有一个 rest api,我可以在其中获取我需要下载并保存到我创建的文件夹中的设备的文件列表。所以我可以一个一个地保存文件,不知道这是如何工作的。

这些文件是从 WCF api 下载的。来自 wcf 服务的传出流内容类型是 OCTET_STREAM。

首先我获取/创建目录,并创建文件:

File mediadir = context.getDir("foo", Context.MODE_PRIVATE);
File file = new File(mediadir, "newfile.png"); // the file name I get from the server, it could be any thing
FileOutputStream out = new FileOutputStream(file); // Stream the contents of the file on the server to the localfile?

我试图下载这样的文件:

File mediadir = context.getDir("tvr", Context.MODE_PRIVATE);

    URL url = new URL(urlString);
    URLConnection conexion = url.openConnection();
    conexion.connect();
    int lenghtOfFile = conexion.getContentLength();
    InputStream is = url.openStream();
    FileOutputStream fos = new FileOutputStream(mediadir+"/video.mp4");
    byte data[] = new byte[1024];
    int count = 0;
    long total = 0;
    int progress = 0;
    while ((count=is.read(data)) != -1){
        total += count;
        int progress_temp = (int)total*100/lenghtOfFile;
        if(progress_temp%10 == 0 && progress != progress_temp){
            progress = progress_temp;
        }
        fos.write(data, 0, count);
    }
    is.close();
    fos.close();

一旦到达 .connect() 我得到错误java.net.SocketException: socket failed: EACCES (Permission denied)

我的清单如下所示:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.tvrplayer"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <permission  android:name="android.permission.INTERNET"></permission>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.tvrplayer.MainActivity"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.NoTitleBar.Fullscreen" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>


</manifest>

如何将api文件保存到我创建的本地director?

我还编写了一个对用户浏览器执行此操作的网络应用程序,但我不确定它如何在 android 上运行。

更新

因此,在我将行更改为权限错误消失后,现在我有一个新错误:

02-20 09:51:28.909: E/AndroidRuntime(12594): FATAL EXCEPTION: main
02-20 09:51:28.909: E/AndroidRuntime(12594): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tvrplayer/com.example.tvrplayer.MainActivity}: android.os.NetworkOnMainThreadException
02-20 09:51:28.909: E/AndroidRuntime(12594):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1970)
02-20 09:51:28.909: E/AndroidRuntime(12594):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1995)
02-20 09:51:28.909: E/AndroidRuntime(12594):    at android.app.ActivityThread.access$600(ActivityThread.java:128)
02-20 09:51:28.909: E/AndroidRuntime(12594):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1161)
02-20 09:51:28.909: E/AndroidRuntime(12594):    at android.os.Handler.dispatchMessage(Handler.java:99)
02-20 09:51:28.909: E/AndroidRuntime(12594):    at android.os.Looper.loop(Looper.java:137)
02-20 09:51:28.909: E/AndroidRuntime(12594):    at android.app.ActivityThread.main(ActivityThread.java:4514)
02-20 09:51:28.909: E/AndroidRuntime(12594):    at java.lang.reflect.Method.invokeNative(Native Method)
02-20 09:51:28.909: E/AndroidRuntime(12594):    at java.lang.reflect.Method.invoke(Method.java:511)
02-20 09:51:28.909: E/AndroidRuntime(12594):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
02-20 09:51:28.909: E/AndroidRuntime(12594):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
02-20 09:51:28.909: E/AndroidRuntime(12594):    at dalvik.system.NativeStart.main(Native Method)
02-20 09:51:28.909: E/AndroidRuntime(12594): Caused by: android.os.NetworkOnMainThreadException
02-20 09:51:28.909: E/AndroidRuntime(12594):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
02-20 09:51:28.909: E/AndroidRuntime(12594):    at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
02-20 09:51:28.909: E/AndroidRuntime(12594):    at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
02-20 09:51:28.909: E/AndroidRuntime(12594):    at libcore.io.IoBridge.connect(IoBridge.java:112)
02-20 09:51:28.909: E/AndroidRuntime(12594):    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
02-20 09:51:28.909: E/AndroidRuntime(12594):    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
02-20 09:51:28.909: E/AndroidRuntime(12594):    at java.net.Socket.connect(Socket.java:842)
02-20 09:51:28.909: E/AndroidRuntime(12594):    at libcore.net.http.HttpConnection.<init>(HttpConnection.java:77)
02-20 09:51:28.909: E/AndroidRuntime(12594):    at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
02-20 09:51:28.909: E/AndroidRuntime(12594):    at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:351)
02-20 09:51:28.909: E/AndroidRuntime(12594):    at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:86)
02-20 09:51:28.909: E/AndroidRuntime(12594):    at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
02-20 09:51:28.909: E/AndroidRuntime(12594):    at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:308)
02-20 09:51:28.909: E/AndroidRuntime(12594):    at libcore.net.http.HttpEngine.connect(HttpEngine.java:303)
02-20 09:51:28.909: E/AndroidRuntime(12594):    at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:282)
02-20 09:51:28.909: E/AndroidRuntime(12594):    at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:232)
02-20 09:51:28.909: E/AndroidRuntime(12594):    at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:80)
02-20 09:51:28.909: E/AndroidRuntime(12594):    at com.example.tvrplayer.MainActivity.download(MainActivity.java:127)
02-20 09:51:28.909: E/AndroidRuntime(12594):    at com.example.tvrplayer.MainActivity.downLoadMedia(MainActivity.java:118)
02-20 09:51:28.909: E/AndroidRuntime(12594):    at com.example.tvrplayer.MainActivity.onCreate(MainActivity.java:52)
02-20 09:51:28.909: E/AndroidRuntime(12594):    at android.app.Activity.performCreate(Activity.java:4465)
02-20 09:51:28.909: E/AndroidRuntime(12594):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1053)
02-20 09:51:28.909: E/AndroidRuntime(12594):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1934)
02-20 09:51:28.909: E/AndroidRuntime(12594):    ... 11 more
4

1 回答 1

1
File path = new File(getActivity().getFilesDir(), "Your Folder Name");
// if the directory doesn't exist it will create one.
path.mkdirs();
File file = new File(path,"Your File Name");
//if the file doesn't exist it will create one
file.createNewFile();

//for write
FileOutputStream fout = new FileOutputStream(file);
ObjectOutputStream os = new ObjectOutputStream(fout);
os.writeObject("Your Object");
os.flush();
os.close();

//for read
FileInputStream fis = new FileInputStream(file);
ObjectInputStream is = new ObjectInputStream(fis);
Your_Object_Type variable = (Your_Object_Type) is.readObject();
is.close();

就我而言,我写了一个类对象

编辑:

这是发生的,因为你在主 UI 线程上使用了互联网请求。修改您的代码:

new Thread( new Runnable() {
    @Override
    public void run() {
       try {
           //............
           // your internet code
           //.............
       } catch (Exception e) {
           // TODO Auto-generated catch block
           Log.e(Tag, e.toString());
       }
     }
   }).start();

编辑2: 如果您想知道文件是否已保存,请检查:

File file = new File(mediadir, "newfile.png");
if(file.exists()){
   //that means the "newfile.png" is exist in otherword it is saved
}else{
      //that means the "newfile.png" does not exist in otherword it is not saved
}
于 2013-02-20T07:24:44.183 回答