Featured post

Marshmallow Features Point by Point

Android Runtime (“ART”) Improved application performance and lower memory overhead for faster  multi-tasking. Battery Doze...

Monday 15 February 2016

File Operation for Android

1. Create Directory in Sdcard.
2. Delete Directory.
3.Get all files from any directory from SDcard.
4. Read content from file.
5. Sdcard 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(newInputStreamReader(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();
           }

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

No comments:

Post a Comment