JAVA-File Handling

Oct 06, 2013 No Comments by

Java classes related to input and output are present in the Java language package java.io . Java uses “streams” as a general mechanism of handling data. Input streams acts as the source of data. Output streams acts as the destination of data.
File class
The file class is used to store the path and name of a directory or file. The file object can be used to create, rename, or delete the file or directory it represents. The File class has the following constructors –

File(String pathname); // pathname could be file or a directory name

You can read files using these classes:

  • FileReader :It is a class for text files in your system’s default encoding (for example, files which contain Western European characters on a Western European computer).
  • FileInputStream:It is a class for binary files and text files that contain ‘weird’ characters.

FileReader (for the text files) has to be wrapped in a BufferedFileReader. This saves up your data so you can deal with it a line at a time or whatever instead of character by character.

Example of reading from a text file:

import java.io.*;
public class readTextFile {
public static void main(String[] args) {
// The full path of the file to open.
String filePath = "d:/file.txt";
String line = null;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(filePath);
BufferedReader bw = new BufferedReader(fileReader);
while ((line = bw.readLine()) != null) {
System.out.println(line);
}
bw.close();
} catch (FileNotFoundException ex) {
System.out.println("Some error has occured while opening the file '" + filePath + "'");
} catch (IOException ex) {
System.out.println("Some error has occured while reading the file '" + filePath + "'");
}
}
}

If you want to write files, basically all the same stuff applies,except you’ll deal with classes named FileWriter with BufferedWriter for text files, or FileOutputStream for binary files.

Example of writing into a textfile:

import java.io.*;
public class writeTextFile {
public static void main(String[] args) {
// The path of the file to open.
String filePath = "D:/file.txt";
try {
// Assume default encoding.
FileWriter fileWriter = new FileWriter(filePath);
BufferedWriter bw = new BufferedWriter(fileWriter);
// Note that write() does not automatically append a newline character.
bw.write("Hie,you hav successfully written the file " + filePath);
bw.newLine();
bw.write("Successfull");
bw.close();
} catch (IOException ex) {
System.out.println(
"Some error has occured while writing to file '" + filePath + "'");
}
}
}

Example of appending to a file(Whether existing or not):

import java.io.*;
public class appendToTextFile {
    public static void main(String[] args) {
        try {
            String data = "This content will append to the end of the file";
            File file = new File("D:/file.txt");
            //if file doesnt exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }
            //Here,true indicates append.
            FileWriter f = new FileWriter(file, true);
            BufferedWriter b = new BufferedWriter(f);
            b.write(data);
            b.close();
            System.out.println("Done");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
JAVA, Programming

About the author

Currently working as JAVA Developer cum Trainer at Appin Technology Lab, Noida. She has worked with brands like L&T and has a total work experience of more than 2 years now which includes development and training. Her area of expertise is JAVA and you can also find her hands on PHP with ease.
No Responses to “JAVA-File Handling”

Leave a Reply