1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Files in Java

Discussion in 'Java' started by pradeep, Aug 2, 2006.

  1. pradeep

    pradeep Team Leader

    Apr 4, 2005
    Likes Received:
    Trophy Points:
    Kolkata, India
    Home Page:
    Java has a class called File, which actually represents not a file you can read or write, but rather a filename. Using this class is highly recommended instead of simple strings, because it makes your file naming operating-system independent. You can easily find out wether a filename is relative or absolute, it strips trailing slashes on directory names and replaces the path separator char with the correct one for the OS.
    Some useful methods:

    File(String pathname)             
     File(File parent, String child)   
     File(String parent,String child)  
    File getAbsoluteFile() Returns the absolute form of this abstract pathname.
    String getAbsolutePath() Returns the absolute pathname string of this abstract pathname.

    boolean isDirectory()    
     boolean isAbsolute()    
    Most of the time you do not need any fancy stuff. You just want to open a file, and then read it, one line at a time. Or write to it, with println. What you call file handles in other languages, in Java its Streams. This is the way to do it:

    import java.io.*;
     class Ftest{
     public static void main(String[] infile){
             BufferedReader LINE;
             PrintWriter OUT;
             String PATH;
             String PATHOUT = "ftest.txt";
             String data;
     if (infile.length != 1){
             System.out.println("Parameter is one filename, Bozo!");
             PATH = infile[0]; 
             try {//i/o may go wrong
        LINE = new BufferedReader(new FileReader(PATH)); //input file handle
        OUT = new PrintWriter(new FileWriter(PATHOUT)); //output file handle
        while((data = LINE.readLine()) != null){         //read lines
         System.out.println("Read: "+data);       //..do some work
         data = data.toUpperCase();
             OUT.println(data);                             //write line
       \tLINE.close();                                 \t//be nice.
             }catch(IOException e){System.out.println("ACK!");}
    Some explanations. First of all, in the example there is no word stream! The point is, that even though java has them under the hood, there are other classes more convenient to use.

    InputStreams and OutputStreams

    These are inconvenient, old stuff. Their incarnations FileInputStream and FileOutputStream read an unstructured flow of bytes. To use them with characters you have to wrap them in InputStreamReader and OutputStreamWriter. You only would need this cumbersome technique to specify a character-encoding different from the Standard used by the normal Readers/Writers.

    Readers and Writers

    These new, abstract classes we used in their incarnations for files, FileReader and FileWriter. They read an unstructered flow of characters. They eat a String or a File Object to find their target in the Operating System - but File also uses a String to connect to its target of course. More on that later. Readers and Writers are better for human-readable data, but still not optimal. For ease of use, we wrapped them in BufferedReader and PrintWriter respectively.


    Like the name suggests contains a buffer for the data read and thus makes it possible to have methods like readline(), which - you guessed it - reads a line of data from the file (assuming it's standard encoded), and returns null if there are no more lines to read. The BufferedReader can be seen as a handle to the file we want to read from.


    This is the opposite to BufferedReader, a Wrapper Class that represents a file handle for writing standard-encoded chars to some Stream or Writer and has a bunch of useful methods like print(), println(). Actually the well-known out-Stream of Sytem.out.print() uses this.

    In all of this we didn't mention the File class. It takes some String and constructs a File Object from it,which can be used as an Argument to various other Classes like Readers/Writers, and which has a lot of other useful methods which check properties of the file or do Operating System work like

    • exists(); canRead(); canWrite(); isDirectory();
    • list() (returns a String[]of all files in the current directory)
    • delete();
    • mkdir();
    • renameTo();
    and most importantly:


    This contains the first character of the environment variable file.separator, which should be the file separator (/ on Unix, \ on Windows). You can use it to keep your code platform independend (and you should!).

Share This Page