Showing posts with label File I/O. Show all posts
Showing posts with label File I/O. Show all posts

Wednesday, July 25, 2012

How to delete a directory(recursively) in Android ?


Just call the below method from anyWhere in the code and just pass the file parameter address eg..

File a=new File("sdcard/example/com");
a.deleteDir(a);


This will call below method and delete the "com" directory...

public static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// The directory is now empty so delete it
return dir.delete();
}


OR


void recursiveDelete (File dirPath) {
String [] ls = dirPath.list ();
for (int idx = 0; idx < ls.length; idx++) {
File file = new File (dirPath, ls [idx]);
if (file.isDirectory ())
recursiveDelete (file);
file.delete ();

}
}

Monday, July 23, 2012

Get the file into ByteArray in Android ?


private byte[] convertToByteArray(final File file) {
   if (file.isDirectory())
       throw new RuntimeException("Unsupported operation, file "
                       + file.getAbsolutePath() + " is a directory");
   if (file.length() > Integer.MAX_VALUE)
       throw new RuntimeException("Unsupported operation, file "
                       + file.getAbsolutePath() + " is too big");

   Throwable pending = null;
   FileInputStream in = null;
   final byte buffer[] = new byte[(int) file.length()];
   try {
       in = new FileInputStream(file);
       in.read(buffer);
   } catch (Exception e) {
       pending = new RuntimeException("Exception occured on reading file "
                       + file.getAbsolutePath(), e);
   } finally {
       if (in != null) {
               try {
                       in.close();
               } catch (Exception e) {
                       if (pending == null) {
                               pending = new RuntimeException(
                                       "Exception occured on closing file"
                            + file.getAbsolutePath(), e);
                       }
               }
       }
       if (pending != null) {
               throw new RuntimeException(pending);
       }
   }
   return buffer;
}

Wednesday, March 14, 2012

How to uncompress a file in the gzip format in java?


This example decompresses a gzip compressed file with java.util.zip.GZIPInputStream.

public static boolean Uncompression(String infname, String outfname){
    
    GZIPInputStream in = null;
    OutputStream out = null;
    
    try {
        in = new GZIPInputStream(new FileInputStream(infname));
        out = new FileOutputStream(outfname);
        byte[] buf = new byte[65536];
        int len;
        while ((len = in.read(buf)) != -1) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
        return true;
    } catch (IOException e) {
        if ( in != null ) {
            try {
                in.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        if ( out != null ) {
            try {
                out.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        return false;
    }
}

Tuesday, March 13, 2012

How to Append Data to the End of Existing File in Java?


It's often useful to be able to append data to an existing file rather than overwriting it.
The BufferedWriter writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.The FileWriter is a convenience class used for writing character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. Also, theFileWriter supports to append data to existing file. For example,
class FileAppending 
{
    public static void main(String args[]) {
        try{
            FileWriter fstream = new FileWriter("x.txt",true);
            BufferedWriter fbw = new BufferedWriter(fstream);
            fbw.write("append txt...");
            fbw.newLine();
            fbw.close();
        }catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}
The FileWriter uses your computer's default character encoding. For UTF-8 file, you may use OutputStreamWriter with FileOutputStream class. The FileOutputStream(String fname, boolean append) constructor creates an output file stream to write to the file with the specified name. If the second argument is true, then bytes will be written to the end of the file rather than the beginning. The OutputStreamWriter class connects byte streams and character streams. The OutputStreamWriter writes bytes onto the underlying output stream after translating characters according to a specified character encoding such as UTF-8. For example,
class FileAppending 
{
    public static void main(String args[]) {
        try{
        
            OutputStreamWriter writer = new OutputStreamWriter(
                  new FileOutputStream("x.txt", true), "UTF-8");
            BufferedWriter fbw = new BufferedWriter(writer);
            fbw.write("append txt...");
            fbw.newLine();
            fbw.close();
        }catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}



Tuesday, March 6, 2012

How can I change a file attribute to writable in Java?


Prior to Java 1.6 the java.io.File class doesn't include a method to change a read only file attribute and make it writable. To do this on the old days we have to utilize or called operating system specific command. But now in 1.6 a new method named setWritable() was introduced to do exactly what the method name says.

import java.io.File;

public class WritableExample
{
    public static void main(String[] args) throws Exception
    {
        File file = new File("Writable.txt");
        
        // Create a file only if it doesn't exist.
        file.createNewFile();
 
        // Set file attribute to read only so that it cannot be written
        file.setReadOnly();
 
        // We are using the canWrite() method to check whether we can
        // modified file content.
        if (file.canWrite()) {
            System.out.println("File is writable!");
        } else {
            System.out.println("File is in read only mode!");
        }
        
        // Now make our file writable
        file.setWritable(true);

        // re-check the read-write status of file 
        if (file.canWrite()) {
            System.out.println("File is writable!");
        } else {
            System.out.println("File is in read only mode!");
        }
    }
}


How can I change a file attribute to read only in Java?


This code demonstrate how we can modify file attribute to be read only. File class has a setReadOnly() method to make file read only and a canWrite() method to know whether it is writable or not.

import java.io.File;

public class FileReadOnlyExample
{
    public static void main(String[] args) throws Exception
    {
        File file = new File("ReadOnly.txt");

        // Create a file only if it doesn't exist.
        file.createNewFile();

        // Set file attribute to read only so that it cannot be written
        file.setReadOnly();

        // We are using the canWrite() method to check whether we can
        // modified file content.
        if (file.canWrite())
        {
            System.out.println("File is writable!");
        } else
        {
            System.out.println("File is in read only mode!");
        }
    }
}

How do I get total space and free space of my disk in Java?


import java.io.File;

public class FreeSpaceExample {
    public static void main(String[] args) {
        
        // We create an instance of a File to represent a partition
        // of our file system. For instance here we used a drive D:
        // as in Windows operating system. 
        
        File file = new File("D:");

        
        // Using the getTotalSpace() we can get an information of
        // the actual size of the partition, and we convert it to
        // mega bytes. 
        
        long totalSpace = file.getTotalSpace() / (1024 * 1024);

        
        // Next we get the free disk space as the name of the
        // method shown us, and also get the size in mega bytes.
        
        long freeSpace = file.getFreeSpace() / (1024 * 1024);

        
        // Just print out the values.
        
        System.out.println("Total Space = " + totalSpace + " Mega Bytes");
        System.out.println("Free Space = " + freeSpace+ " Mega Bytes");
    }
}

Below is the output...

Total Space = 76316 Mega Bytes
Free Space = 58412 Mega Bytes


How do I check if a file is hidden in Java?


import java.io.File;
import java.io.IOException;

public class FileHiddenExample {
    public static void main(String[] args) throws IOException {
        File file = new File("Hidden.txt");
        file.createNewFile();

        // 
        // We are using the isHidden() method to check whether a file
        // is hidden.
        //
        if (file.isHidden()) {
            System.out.println("File is hidden!");
        } else {
            System.out.println("File is not hidden!");
        }
    }
}

How do I get the content of a directory in Java?


In this example you'll see how to read the list of files inside a directory. To get this functionality we can use the File.listFiles() method. This method return an array of File object which can be either an instance of file or directory.

import java.io.File;
import java.io.FilenameFilter;

public class DirectoryContentExample
{
    public static void main(String[] args)
    {
        File games = new File("D:\\Games");

        // Get a list of file under the specified directory
        // above and return it as an abstract file object.
        File[] files = games.listFiles();

        // Iterates the content of games directory, print it
        // and check it whether it was a directory or a file.
        for (File file : files)
        {
            System.out.println(file + " is a " 
                    + (file.isDirectory() ? "directory" : "file"));
        }

        // Here we also get the list of file in the directory but
        // return it just as an array of String.
        String[] xfiles = games.list();
        for (String file : xfiles)
        {
            System.out.println("File = " + file);
        }

        // Now we want to list the file in the directory but
        // we just want a file with a .doc extension. To do
        // this we first create a FilenameFilter which will
        // be given to the listFiles() method to filter the
        // listing process. The rule of filtering is
        // implemented in the accept() method of the
        // FilenameFilter interface.
        FilenameFilter filter = new FilenameFilter()
        {
            public boolean accept(File dir, String name)
            {
                if (name.endsWith(".doc"))
                {
                    return true;
                }
                return false;
            }
        };

        // Give me just a .doc files in your directory.
        File[] yfiles = games.listFiles(filter);
        for (File doc : yfiles)
        {
            System.out.println("Doc file = " + doc);
        }
    }
}

Below is the output.....

The File[] array returned:
D:\Games\AOE is a directory
D:\Games\Championship Manager 2007 is a directory
D:\Games\GameHouse is a directory
D:\Games\Sierra is a directory
D:\Games\testing.doc is a file
D:\Games\TTD is a directory

The String[] array returned.
File = AOE
File = Championship Manager 2007
File = GameHouse
File = Sierra
File = testing.doc
File = TTD

The File[] array using FilenameFilter result.
Doc file = D:\Games\testing.doc

Monday, March 5, 2012

How do I get file's last modification date in android?


To get file's last modification date we can use the lastModified() method of the File class. This method returns a long value. After getting this value you can create an instance of java.util.Dateclass and pass this value as the parameter. This Date will hold the file's last modification date.

import java.io.File;
import java.util.Date;

public class FileLastModificationDate
{
    public static void main(String[] args)
    {
        // Create an instance of file object.
        File file = new File("FileLastModificationDate.java");
        // Get the last modification information.
        Long lastModified = file.lastModified();

        // Create a new date object and pass last modified information
        // to the date object.
        Date date = new Date(lastModified);

        // We know when the last time the file was modified.
        System.out.println(date);
    }
}

Saturday, February 11, 2012

How to Open file with default application using Intents in android?

This code allows you to open a particular file with the default application, specifying the MIME, in these cases audio and video.

Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
File file = new File("/sdcard/test.mp4");
intent.setDataAndType(Uri.fromFile(file), "video/*");
startActivity(intent); 


Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
File file = new File("/sdcard/test.mp3");
intent.setDataAndType(Uri.fromFile(file), "audio/*");
startActivity(intent); 

How to view all files from sdcard in android device?

This is a little code snippet that i developed recently when i wanted to build an "android file manager".You can see all the files form sdcard using this code snippet.

    File file[] = Environment.getExternalStorageDirectory().listFiles();
recursiveFileFind(file);


public void recursiveFileFind(File[] file1){
    int i = 0;
    String filePath="";
         if(file1!=null){
        while(i!=file1.length){
            filePath = file1[i].getAbsolutePath();
        if(file1[i].isDirectory()){
        File file[] = file1[i].listFiles();
                recursiveFileFind(file);
        }
            i++;
            //Log.d(i+"", filePath);
        }
      }
    }

Wednesday, February 1, 2012

How to retrieve the specified extension files from particular directory?

In below example we are retrieving the images from the directory
String categoryPath="/sdcard/directory/";


private String GetImage(String categoryPath) {
String[] lv_arr;
File directory = new File(categoryPath);
if (!(directory.isDirectory())) {
directory.mkdir();
return "";
}

lv_arr = directory.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
if (new File(dir, name).isDirectory())
return false;
return name.toLowerCase().contains(".jpeg")
|| (name.toLowerCase().contains(".jpg"))
|| (name.toLowerCase().contains(".png"))
|| (name.toLowerCase().contains(".bmp"))
|| (name.toLowerCase().contains(".gif"));
}
});

return lv_arr[0].toString();
}

Monday, January 30, 2012

How to write and read xml file on sdcard?


public static void WriteFile(String filenames,String content)
{
File file = new File("/sdcard/", filenames);
if (file.exists() || (!file.exists())) {
            FileOutputStream fos = null;
try {
fos = new FileOutputStream(file, false);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
            try {
fos.write(content.getBytes());
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
         
}
}

public static String ReadFile(String filenames)
{
String content = null;

File myFile = new File("/sdcard/", filenames);
if (myFile.exists()) {
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(myFile);
}
catch (FileNotFoundException e2) {
return content;
}
try {
BufferedReader readerRead1 = new BufferedReader(new InputStreamReader(inputStream));
content = readerRead1.readLine();
} catch (IOException e1) {
// TODO Auto-generated catch block
return content;
}

}
return content;
}

How to read Read Asset file?


public static String ReadFromAssetFile(Context context,String filenames)
{
String content = "";

InputStream inputStream = null;
try {
inputStream = context.getAssets().open(filenames);
BufferedReader readerRead1 = new BufferedReader(new InputStreamReader(inputStream));
String line="";
while((line=readerRead1.readLine())!=null){
content+=line.trim();
}
} catch (IOException e1) {
// TODO Auto-generated catch block
return content;
}


return content;
}

Sunday, January 29, 2012

Push db into application package

First do


1. copy your Database.db file in your projects assets folder.
2. now using coding copy this file into device's internal storage 
  (data/data/<package name>/database folder).
for this use code below given,
try {
// Open your local db as the input stream
InputStream myInput = myContext.getAssets().open("your database file name");
// Path to the just created empty db
String outFileName = "/data/data/your app package name/databases/database file name";
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) 
 {
     myOutput.write(buffer, 0, length);
 }
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
} catch (Exception e) {
Log.e("error", e.toString());
}