Search
Sponsors
Sponsors

Archive for the ‘File System’ Category

Delete a directory

Thursday, August 25th, 2011

 

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

Read a file to a string

Thursday, August 25th, 2011

 

private String readFile(String pathname) throws IOException {
    StringBuilder stringBuilder = new StringBuilder();
    Scanner scanner = new Scanner(new File(pathname));

    try {
        while(scanner.hasNextLine()) {       
            stringBuilder.append(scanner.nextLine() + "\n");
        }
    } finally {
        scanner.close();
    }
    return stringBuilder.toString();
}

Copy a directory

Thursday, August 25th, 2011

 

private  void copyDirectory(File sourceLocation , File targetLocation) throws IOException {
     
      if (sourceLocation.isDirectory()) {
          if (!targetLocation.exists()) {
              targetLocation.mkdir();
          }
         
          String[] children = sourceLocation.list();
          for (int i=0; i<children.length; i++) {
              copyDirectory(new File(sourceLocation, children[i]),
                      new File(targetLocation, children[i]));
          }
      } else {
         
          InputStream in = new FileInputStream(sourceLocation);
          OutputStream out = new FileOutputStream(targetLocation);
         
          // Copy the bits from instream to outstream
          byte[] buf = new byte[1024];
          int len;
          while ((len = in.read(buf)) > 0) {
              out.write(buf, 0, len);
          }
          in.close();
          out.close();
      }
  }

Read a file

Thursday, August 25th, 2011

 

File multiUserFile = new File("test.txt");

String line = "";
       
try {
   BufferedReader ficTexte = new BufferedReader(new FileReader(multiUserFile));
   line = ficTexte.readLine();
}
catch (IOException e) {
   e.printStackTrace();
}

Write to a file

Thursday, August 25th, 2011

 

File multiUserFile = new File(filepath);
   
try {

BufferedWriter ficTexte = new BufferedWriter(new FileWriter(multiUserFile));
ficTexte.write("singlepath=false"+System.getProperty("line.separator"));
ficTexte.write("multiuser=false"+System.getProperty("line.separator"));
ficTexte.close();

}
catch (IOException e) {
e.printStackTrace();
}

Directory recursion example

Thursday, August 25th, 2011

 

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
*
*/

/**
* @author hariharan_kumar
*
*/
public class Dfs {

    List<String> directoryLists;
    /**
     *
     */
    public Dfs() {
       
        directoryLists = new ArrayList<String>();
       
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
       
        Dfs df = new Dfs();
        df.iterate("G:/jbossTest");
        df.displayDirList();
       
    }

    public void iterate(String baseDir)
    {
        File folder_and_files = new File(baseDir);
        File[] file_array = folder_and_files.listFiles();
       
        for(int i = 0;i < file_array.length;i++)
        {
            if(file_array[i].isDirectory())
            {
                //System.out.println("Directory  is : " + file_array[i].getName());
                directoryLists.add(file_array[i].getAbsolutePath());
                iterate(file_array[i].getAbsolutePath());
            }
            else if (file_array[i].isFile())
            {
                //System.out.println("File is : " + file_array[i].getAbsolutePath());
               
            }
            else if(file_array.length == i)
            {
                return;
            }
               
        }       
    }
   
    public void displayDirList()
    {
        Iterator<String> i = directoryLists.iterator();
        while(i.hasNext())
        {
            System.out.println(i.next());
        }
    }
}

File read and write example

Thursday, August 25th, 2011

 

import java.util.Vector;
import java.io.*;

public class FileUtility {

    public static String[] readLinesFromFile(String fileName) {

        Vector<String> lines = new Vector<String>();

        DataInputStream dis = null;

        try {

            FileInputStream fis = new FileInputStream(new File(fileName));
            dis = new DataInputStream(fis);
            BufferedReader br = new BufferedReader(new InputStreamReader(dis));

            String line;
            while ((line = br.readLine()) != null) {
                lines.add(line);
            }

            dis.close();

        } catch (IOException e) {
        } catch (Exception e) {
        } finally {

            if (dis != null) {
                try {
                    dis.close();
                } catch (Exception e) {
                }
            }

        }

        String[] data = new String[lines.size()];
        for (int n = 0; n < lines.size(); n++) {
            data[n] = lines.elementAt(n);
        }

        return data;

    }

    public static boolean writeLinesToFile(String fileName, String[] lines) {
        return writeLinesToFile(fileName, lines, false);
    }

    public static boolean writeLinesToFile(String fileName, String[] lines,
            boolean append) {

        DataOutputStream dos = null;

        boolean success = true;

        try {

            FileOutputStream fos = new FileOutputStream(new File(fileName), true);
            dos = new DataOutputStream(fos);
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(dos));

            for (int n = 0; n < lines.length; n++) {
                bw.write(lines[n]);
                bw.newLine();
                bw.flush();
            }

        } catch (IOException e) {
            success = false;
        } catch (Exception e) {
            success = false;
        } finally {

            if (dos != null) {
                try {
                    dos.close();
                } catch (Exception e) {
                }
            }

        }

        return (success) ? true : false;

    }

    public static void main(String[] args) {

        String fileName = "yourFileHere";

        String[] data = readLinesFromFile(fileName);
        for (int i = 0; i < data.length; i++) {
            System.out.println(data[i]);
        }

        if (writeLinesToFile(fileName, new String[] { "x", "y" }, true)) {
            System.out.println("Write success");
        }

    }

}

Read a file

Thursday, August 25th, 2011

 

import java.net.*;
import java.io.*;

public class URLReader {

    private String url;

    public URLReader(String url) {

        this.url = url;

    }

    public String read() throws Exception {

        StringBuffer sb = new StringBuffer();

        URL u = new URL(this.url);

        BufferedReader in = new BufferedReader(
            new InputStreamReader(
                u.openStream()
            )
        );

        String line;

        while ((line = in.readLine()) != null) {

            sb.append(line);

        }

        return sb.toString();

    }

    public static void main(String[] args) {

        URLReader u = new URLReader("http://mscribellito.com");

        try {

            System.out.println(u.read());

        } catch (Exception e) {

            System.out.println(e.getMessage());

        }

    }

}

Translate