6 Jul 2015

File Operation for Android

Hello,

Today I am going to post common File operation which used day base for developers.
Here is the few operation for file.

1. Create Directory in SD-card.
2. Delete Directory.
3.Get all files from any directory from SD-card.
4. Read content from file.
5. SD-card is availability.
6.Save/Download files from server and store.
7.Byte Array from Image
8.Encoded & decode base64 string into image

1. Create Directory

public static boolean createFolder(String path) {
               if (storageReady()) {
                   boolean made = true;
                   File dir = new File(path);
                   if (!dir.exists()) {
                       made = dir.mkdirs();
                   }
                   return made;
               } else {
                   return false;
               }
           }  

2. Delete Directory

public boolean deleteFolder(String path) {
                     if (path != null && storageReady()) {
                   File dir = new File(path);
                   if (dir.exists() && dir.isDirectory()) {
                       File[] files = dir.listFiles();
                       for (File file : files) {
                           if (!file.delete()) {
                               Log.i(t, "Failed to delete " + file);
                           }
                       }
                   }
                   return dir.delete();
               } else {
                   return false;
               }
           }

3. Delete File

public static boolean deleteFile(String path) {
               if (storageReady()) {
                   File f = new File(path);
                   return f.delete();
               } else {
                   return false;
               }
           }

4. Get All file from directory

public ArrayList<String> getFoldersAsArrayList(String path) {
               ArrayList<String> mFolderList = new ArrayList<String>();
               File root = new File(path);

               if (!storageReady()) {
                   return null;
               }
               if (!root.exists()) {
                   if (!createFolder(path)) {
                       return null;
                   }
               }
               if (root.isDirectory()) {
                   File[] children = root.listFiles();
                   for (File child : children) {
                       boolean directory = child.isDirectory();
                       if (directory) {
                           mFolderList.add(child.getAbsolutePath());
                       }
                   }
               }
               return mFolderList;

           }      

5. Read content of file

public String getFileContentsAsString(final File file) throws IOException {
               final InputStream inputStream = new FileInputStream(file);
               final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
              
               final StringBuilder stringBuilder = new StringBuilder();
              
               boolean done = false;
              
               while (!done) {
                   final String line = reader.readLine();
                   done = (line == null);
                  
                   if (line != null) {
                       stringBuilder.append(line);
                   }
               }
              
               reader.close();
               inputStream.close();
              
               return stringBuilder.toString();
           }

5.1 Read content of file

fun readFileData(file: File): String
    {
        val sb = StringBuilder()

        if (file.exists()) {
            try {
                val bufferedReader = file.bufferedReader();
                bufferedReader.useLines { lines ->
                    lines.forEach {
                        sb.append(it)
                    }
                }
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
        return sb.toString()
    }

6. Write content to the file [Kotlin]

fun writeDataToFile(mContext: Context, folderName:String, fileName:String, data:String)
    {
        if(data.isNotEmpty())
        {
            val folder = mContext.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS).toString() + File.separator + folderName

            val file1 = File(folder)
            if (!file1.exists())
            {
                file1.mkdirs()
            }

            // Storing the data in file with name as param file name.
            val file = File(file1.toString(), "$fileName.txt")

            var fileOutputStream: FileOutputStream? = null
            try
            {
                fileOutputStream = FileOutputStream(file)
                fileOutputStream.write(data.toByteArray())

                //Refresh the storage.
                MediaScannerConnection.scanFile(mContext, arrayOf(file.toString()),null, null)
            }
            catch (e: java.lang.Exception)
            {
                e.printStackTrace()
            }
            finally
            {
                if (fileOutputStream != null)
                {
                    try
                    {
                        fileOutputStream.close()
                    }
                    catch (e: IOException)
                    {
                        e.printStackTrace()
                    }
                }
            }
        }
    }

6. Sdcard availability.        

public boolean storageReady() {
               String cardstatus = Environment.getExternalStorageState();
               if (cardstatus.equals(Environment.MEDIA_REMOVED)
                       || cardstatus.equals(Environment.MEDIA_UNMOUNTABLE)
                       || cardstatus.equals(Environment.MEDIA_UNMOUNTED)
                       || cardstatus.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
                   return false;
               } else {
                   return true;
               }
           }

7. Download file form server.   

      
void downloadFile(String strUrl , String filePath, String fileName)
       {
              try
              {
                     URL url = new URL(strUrl);
                     File myDir = new File(filePath);
                     if (!myDir.exists())
                     {
                           myDir.mkdirs();
                           Log.v("""inside mkdir");
                     }

                     /* checks the file and if it already exist delete */
                     String fname = fileName;
                     File file = new File(myDir, fname);
                     if (file.exists())
                           file.delete();

                     file.createNewFile();
                     /* Open a connection */
                     URLConnection ucon = url.openConnection();
                     InputStream inputStream = null;
                     HttpURLConnection httpConn = (HttpURLConnection) ucon;
                     httpConn.setRequestMethod("GET");
                     httpConn.connect();

                     if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK)
                     {
                           inputStream = httpConn.getInputStream();
                     }

                     FileOutputStream fos = new FileOutputStream(file);
                     //                   int totalSize = httpConn.getContentLength();
                     //                   int downloadedSize = 0;
                     byte[] buffer = new byte[1024];
                     int bufferLength = 0;
                     while ((bufferLength = inputStream.read(buffer)) > 0)
                     {
                           fos.write(buffer, 0, bufferLength);
                           //     downloadedSize += bufferLength;

                           //Log.i("Progress:", "downloadedSize:" + downloadedSize+ "totalSize:" + totalSize);
                     }

                     fos.close();
                     Log.d("test""Image Saved in sdcard..");
              } catch (IOException io) {
                     io.printStackTrace();
              } catch (Exception e) {
                     e.printStackTrace();
              }
       }      

8. Byte Array from Image.        


private byte[] getByteArrayFromImage(String filePath) throws FileNotFoundException, IOException {

              File file = new File(filePath);
              System.out.println(file.exists() + "!!");

              FileInputStream fis = new FileInputStream(file);
              //create FileInputStream which obtains input bytes from a file in a file system
              //FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader.

              //InputStream in = resource.openStream();
              ByteArrayOutputStream bos = new ByteArrayOutputStream();
              byte[] buf = new byte[1024];
              try {
                     for (int readNum; (readNum = fis.read(buf)) != -1;) {
                           bos.write(buf, 0, readNum);
                           //no doubt here is 0
                            /*Writes len bytes from the specified byte array starting at offset
                       off to this byte array output stream.*/
                           System.out.println("read " + readNum + " bytes,");
                     }
              } catch (IOException ex) {
                     Log.d("error","error");
              }
              byte[] bytes = bos.toByteArray();
              return bytes;

       }

8. Encoded & decode base64 string into image.      

public static String encodeTobase64(Bitmap image)
       {
           Bitmap immagex=image;
           ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
           immagex.compress(Bitmap.CompressFormat.JPEG, 100, baos);
           byte[] b = baos.toByteArray();
           String imageEncoded = Base64.encodeToString(b,Base64.DEFAULT);
        
           Log.e("Encode String", imageEncoded);
           return imageEncoded;
       }

       public static Bitmap decodeBase64(String input)
       {
           byte[] decodedByte = Base64.decode(input, 0);
           return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
       } 
     

I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.
Thank you :)

No comments:

Post a Comment