File Handling


File Writer 


How to use existing Java API for writing data to external file for persistance.
Source: TestFileWriter.java


import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class 
TestFileWriter {
    public static void main(String[] args) {
    try {
            FileWriter writer = new FileWriter("c:/citydata.txt", true); //set true for append mode
            BufferedWriter bufferedWriter =new BufferedWriter(writer);
            bufferedWriter.write("Tokyo");
            bufferedWriter.write(",");
            bufferedWriter.write("New York");
            bufferedWriter.write(",");
            bufferedWriter.write("Colombo");
            bufferedWriter.write(",");
            bufferedWriter.write("Korea");
            bufferedWriter.write("\n");

            bufferedWriter.flush();
            bufferedWriter.close();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

Output
After running above program check for creation of c:/citydata.txt with following contents


Tokyo, New York, Colombo, Korea
=================================================


File Reader 


How to use existing Java API for reading data from external file.
Source: TestFileReader.java

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;

public class 
TestFileReader {
    public static void main(String[] args) {
        File file = new File("c:/citydata.txt");
        try {
            Scanner scan = new Scanner(file);
            while (scan.hasNext()) {
                System.out.println(scan.nextLine());
            }       
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }
}

Output
Tokyo, New York, Colombo, Korea

No comments :

Post a Comment