List the available system roots in Java

Use the method listRoots in the File class. Notice that this is filesystem dependent. On Unix, there is only one system root: “/”. On Windows, it depends on drives that are mapped.
Here’s an example:

Main.java:

import java.io.*;
   
public class Main {
   public static void main(String[] args) {
      File[] roots = File.listRoots();
      for (int i=0; i<roots.length; i++) {
         System.out.println(roots[i]);
      }
   }
}

outputs on my machine:

A:
C:
D:
E:

Copying a file in Java

Use FileInputStream and FileOutputStream, these classes treat files as byte streams as opposed to FileReader and FileWriter that treat files as character streams.
To copy a file, open the source file with FileInputStream and call the read() method until end-of-file, occurs when read() return -1. In the meantime, use the write method to write that byte to the newly created file.
You can make this process much more performant by using BufferedInput and BufferedOutput Streams.

import java.io.*;
 
public class copy
{
   public static void main(String []args) {
      if (args.length != 2) {
         System.out.println("Required parameter missing");
         System.exit(1);
      }
 
      try {
         FileInputStream fis = new FileInputStream(args[0]);
         FileOutputStream fos = new FileOutputStream(args[1]);
 
         int b;
         while ((b = fis.read()) != -1) fos.write(b);
 
         fos.close();
         fis.close();
      }
      catch(Exception e) {
         System.out.println(e);
      }
   }
}

Renaming and deleting a file in Java

Rename:

Use the method renameTo in the File class. If the destination folder is different from the source folder, it will move the file to the destination folder. Eg.

import java.io.*;
 
public class FileRename 
{
   public static void main(String []args) {
      File file = new File("c:\test.txt");
 
      file.renameTo(new File("c:\test2.txt"));
 
      System.out.println(file.getName());
   }

}

Notice that, after renaming, getName returns the old filename. Bug? Anyone?

Delete:

Use the method delete in the File class. Eg.

import java.io.*;
 
public class FileDelete
{
   public static void main(String []args) {
      File file = new File("c:\test.txt");
 
      file.delete();
   }
}

Using a filter when listing the contents of a directory in Java

The easiest way is to use an anonymous inner class which implements either FileFilter or FilenameFilter:

//list only pdf files
File[] pdfFiles = departmentFolder.listFiles(new FilenameFilter(){
  public boolean accept(File dir, String name){
    return (name.endsWith("pdf")||name.endsWith("PDF"));
  }
});
//list only folders
File[] usrFolders = departmentFolder.listFiles(new FileFilter(){
  public boolean accept(File pathname){
    return (pathname.isDirectory());
  }
});

Listing the contents of a directory in Java

Use the File class. Here’s an example:

import java.io.*;
 
public class Main
{
   public static void main(String []args) {
      if (args.length != 1) {
         System.err.println("Usage: java Main <path>");
         System.exit(1);
      }
 
      File []files = new File(args[0]).listFiles();
 
      for (int i=0; i<files.length; i++) {
         // Checks whether this it's a directory
         if (files[i].isDirectory()) 
            System.out.println("Directoryt" + files[i].getName());
         else
            System.out.println("Filett" + files[i].getName());
      }
   }
}

If you want to enable wildcards, you can do all the customization yourself using
FilenameFilter. The following example shows you how to list the .java files in
the directory specified at command line:

import java.io.*;
 
public class Main
{
   public static void main(String []args) {
      if (args.length != 1) {
         System.err.println("Usage: java Main <path>");
         System.exit(1);
      }
 
      File path = new File(args[0]);
      File []files = path.listFiles(
               new FilenameFilter() {
                  public boolean accept(File f, String name) {
                     return name.toLowerCase().endsWith(".java");
                  }
               });
 
      for (int i=0; i<files.length; i++) {
         if (files[i].isDirectory()) 
            System.out.println("Directoryt" + files[i].getName());
         else
            System.out.println("Filett" + files[i].getName());
      }
   }
}

Tell how much free space is on disk in Java

Unfortunately, there is no API or method to find out, not even in JDK 1.3. Check out BUG 4057701 in Sun’s Bug Parade. Until this bug is fixed, you can try out to execute an external command like dir (Windows) or du (unix) and parse the output:

import java.util.*;
import java.text.*;
import java.io.*;
  
public class Main
{
   public static void main(String [] args) throws Exception {
      long fs = getFreeSpace("c:");
 
      System.out.println("Free space: " + fs);
   }
 
   public static long getFreeSpace(String dir) throws Exception {
      String osname = System.getProperty("os.name");
      String command = "";
      if (osname.indexOf("NT") > -1)
         command = "c:\winnt\cmd.com";
      else if (osname.indexOf("Windows") > -1)
         command = "c:\windows\command.com";
 
      Process p = Runtime.getRuntime().exec(command + " /c dir " + dir + " > c:\dir.txt");
      p.waitFor(); 
 
      File f = new File("c:\dir.txt");
      BufferedReader br = new BufferedReader(new FileReader(f));
      String line;
      String totalBytes = "";
      while ((line = br.readLine()) != null) {
         if (line.indexOf("bytes free") > -1) {
            int start = line.indexOf("dir(s)") + 7;
            int end = line.indexOf("bytes free", start);
            totalBytes = line.substring(start, end).trim();
            break;
         }
      }
 
      br.close();
      f.delete();
 
      return NumberFormat.getInstance().parse(totalBytes).longValue(); 
   }
}

This code needs to be adapted to be language and platform independent!

Reading a binary file into a byte array

Use BufferedInputStream as shown in following example.

Main.java:

import java.io.*;
 
public class Main {
   public static void main(String args[]) {
      if (args.length != 1) {
         System.err.println("Usage: java Main <file>");
         System.exit(1);
      }
 
      try {
         File f = new File(args[0]);
         BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f));
         byte[] buffer = new byte[(int) f.length()];
         bis.read(buffer, 0, buffer.length);
         bis.close();
         System.out.println("Read file with " + buffer.length + " bytes.");
      }
      catch(IOException e) {
         System.err.println(e);
      }
   }
}

How do I read a file that contains numbers?

The following code reads Numbers as well as String from a File.

import java.io.*;
 
public class readNumbers  {
 
   public static void main(String arg[])  {
      BufferedReader bis=null;
      StreamTokenizer st=null;
 
      try  {
         bis = new BufferedReader(new FileReader
                                ("numberFile.txt"));
	 st = new StreamTokenizer(bis);
      }
      catch(FileNotFoundException e)  {
         System.out.println("File Not Found");
      }
 
      try  {
	 while (st.nextToken() != StreamTokenizer.TT_EOF)  {
	    if (st.ttype == StreamTokenizer.TT_WORD)  {
	       System.out.println("String: " +  st.sval);
	    }
            else if (st.ttype == StreamTokenizer.TT_NUMBER)  {
	       System.out.println("Number: " + st.nval);
	    }
         }
      }
      catch(IOException e)  {
	 e.printStackTrace();
      }
   }
}

Eg., File(numberFile.txt) contents:

20432   34343  Testing String
23432  3343

Output:

Number: 20432.0 
Number: 34343.0 
String: Testing 
String: String 
Number: 23432.0 
Number: 3343.0