Java Basics 1.17

File I/O: Copy a Text File

Code:

package com.lynda.files;

 

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

 

public class CopyFile {

 

    public static void main(String[] args) {

      try {

            // file is in the PROJECT directory

            File f1 = new File("loremipsum.txt");

            File f2 = new File("target.txt");

            

            InputStream in = new FileInputStream(f1);

            OutputStream out = new FileOutputStream(f2);

            

            //Copy text file byte by byte..or by chunck of bytes

            byte[] buf = new byte[1024];

            int len; //holds bytes remaining

            //reading information to fill the array

            //return the total number of bytes received to len

            while ((len = in.read(buf)) > 0) {

                 out.write(buf, 0, len);

            }

            

            in.close();

            out.close();

            

            System.out.println("File copied");

      } catch (FileNotFoundException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

      } catch (IOException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

      }

      

    }

}