0

Hello I am wondering how do you have an android app that can go online and retrieve a custom file type and then store it on the phone in a readable space for the application? Also sense I'm already posting how would you have your android application read the said file?

Thank you for you time.

2 Answers2

0

I think it's not valid anymore in Android 3.0 and above. You must use AsyncTask to prevent any application freeze while downloading :How to fix android.os.NetworkOnMainThreadException?

Community
  • 1
  • 1
0

Nothing specific to Android. Do it how you do in Java.

   // Create a URL for the desired file
   URL url = new URL(URL_LOCATION);
   // Open an InputStream to read the resource
   InputStream is = url.openStream();

   // Use this InputStream to read your file

Here is how you can use this InputStream to save the file on sd card by using OutputStream.

         try {
                File root = Environment.getExternalStorageDirectory();

                String localFilePath = root.getPath() + "/yourFileName";



                FileOutputStream fos = new FileOutputStream(localFilePath, false);

                OutputStream os = new BufferedOutputStream(fos);



                byte[] buffer = new byte[1024];

                int byteRead = 0;



                while ((byteRead = is.read(buffer)) != -1) {

                        os.write(buffer, 0, byteRead);

                }

                fos.close();

        } catch (Exception e) {

                e.printStackTrace();

        }
Timuçin
  • 4,653
  • 3
  • 25
  • 34
  • thank you but is there any special methods you need to do to save that file on the phone? – Kyle Bartz Apr 15 '11 at 22:55
  • @Kyle Bartz : added a code snippet for reading the file from InputStream and writing it to a file on sd card by using OutputStream. – Timuçin Apr 15 '11 at 23:09
  • so basically your opening the online file, creating a local path, then reading the file and inputing its information in the local location? – Kyle Bartz Apr 15 '11 at 23:45
  • Thank you i just have one more small question whats the purpose of the byte[] buffer = new byte[1024];? Is it declaring the file size? Again thank you for the help – Kyle Bartz Apr 15 '11 at 23:53
  • @Kyle Bartz InputStream is used for reading byte based data. You can read the data byte by byte using InputStream's read() method. But to be more efficient we use a byte array to read a chunk of bytes calling read(byte[]) method. In our case, we use a buffer which can hold 1024 bytes. On each loop, we read 1024 bytes. – Timuçin Apr 16 '11 at 00:04