Header Ads

  • Breaking Now

    Code Snippets:File Operations

    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    public class FileOperation {
    /**
    * @param args
    */
    public static void main(String[] args) {
    FileOperation fio = new FileOperation();
    //Creating a source file
    File sourceFile=new File("test.txt");
    //Creating a destination file
    File destinationFile=new File("testDest.txt");
    // Writing to a file
    fio.writeFile("test.txt", "Writing inside files is fun.");
    // Reading from a file
    fio.readFile("test.txt");
    // Copy from a source file to a destination file
    fio.copyFile(sourceFile, destinationFile);
    }
    // Read from a file
    void readFile(String fileName) {
    BufferedReader bufferedReader;
    String line;
    try {
    bufferedReader = new BufferedReader(new FileReader(fileName));
    while ((line = bufferedReader.readLine()) != null) {
    System.out.println(line);
    }
    bufferedReader.close();
    } catch (IOException e) {
    System.out.println("Error reading file");
    }
    }
    // Write to a file
    void writeFile(String fileName, String aText) {
    BufferedWriter bufferedWriter;
    try {
    // FileWriter(fileName,true) constructor allows to append
    // the data at the end of the file
    bufferedWriter = new BufferedWriter(new FileWriter(fileName, true));
    bufferedWriter.append(aText);
    bufferedWriter.close();
    } catch (IOException e) {
    System.out.println("Error writing to file");
    }
    }
    // copy from source file to destination file
    void copyFile(File fileSource, File fileDestination) {
    // Declare variables
    InputStream inputStream = null;
    OutputStream outputStream = null;
    try {
    // Declare variables
    int nLen = 0;
    inputStream = new FileInputStream(fileSource);
    outputStream = new FileOutputStream(fileDestination);
    // Transfer bytes from in to out
    byte[] bBuffer = new byte[1024];
    while ((nLen = inputStream.read(bBuffer)) > 0) {
    outputStream.write(bBuffer, 0, nLen);
    }
    // Flush
    outputStream.flush();
    } catch (IOException e) {
    System.out.println("Error while copying file");
    }
    finally {
    // Close streams
    try {
    if (inputStream != null)
    inputStream.close();
    if (outputStream != null)
    outputStream.close();
    } catch (IOException eError) {
    }
    }
    }
    }
    

    No comments

    Post Top Ad

    Post Bottom Ad