0

We have a rest api where I can get a list of files that I need to download and save to the device in a folder I created. So I can save the files on by one, not sure how this works.

The files are downloaded from a WCF api. The outgoing streams content type is OCTET_STREAM from the wcf service.

First I get/create the directory, and create the file:

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?

Im trying to download a file like this:

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();

Once it gets to .connect() I get the error java.net.SocketException: socket failed: EACCES (Permission denied)

My manifest looks like this:

<?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>

How do I get the api file saved to the local director I created?

I also wrote a web app that does this to the users browser, but Im not sure how it works on android.

UPDATE

So after I chandged the line to The permission error went away, now I have a new error:

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
Harry
  • 13,091
  • 29
  • 107
  • 167

1 Answers1

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();

in my case i have written a class object

Edited:

this is happen, because u have used internet request on main UI-Thread. modify your code:

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();

Edited 2: if u want to know that the file is saved or not, check this:

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
}
Shoshi
  • 2,254
  • 1
  • 29
  • 43
  • Thanks, not sure how to get the data from the API. I was looking at this example and worked through it: http://stackoverflow.com/questions/5027624/android-download-all-files-from-a-folder-on-server .But I get an error like this: http://stackoverflow.com/questions/11273197/socket-failed-eacces-permission-denied – Harry Feb 20 '13 at 07:27
  • have u define the `internet` permission in manifest? if u r testing on emulator, then u can turn off firewall. firewall may cause the problem – Shoshi Feb 20 '13 at 07:37
  • I have done that, im testing on a device. ill add my manifest – Harry Feb 20 '13 at 07:39
  • will u please add your logcat ? – Shoshi Feb 20 '13 at 07:49
  • I got the part working, by changing the permission line to . Now I have anew error – Harry Feb 20 '13 at 07:52
  • Shweet, that works now. I just want to make sure that the file is saved there – Harry Feb 20 '13 at 08:12
  • are you want to know that the file is saved or not ? @Harry – Shoshi Feb 20 '13 at 08:24