Copying File in Java


This Simple Java Program is for Copying of a Text File into another Text File in Java. This is a part of Mumbai University MCA Colleges Java Practicals.

Reading a File in Java requires you to include or import java.io file. There are many different classes used for reading a file or byte stream in java. FileInputStream is most commonly used. To write to a file we will use FileOutputStream. We can read different types of files with this


The Below program opens a file named demofile.txt from a specified location (You can change the file you want to read). It then reads the file line by line using the read() function of FileInputStream Class. The read() function will return a -1 if it encounters end of file (EOF). The contents of the demofile are then copied to demooutput file using the write() function of FileOutputStream Class. The end result is that the copying of file in java is completed and the new content of Demooutput file are displayed

 

import java.io.*;
class copyfile
{
public static void main(String ar[])
{
File f_input=new File("D:/demofile.txt"); // You can change the file names
File f_output=new File("D:/demooutput.txt");
try
{
FileInputStream fis=new FileInputStream(f_input);
FileOutputStream fos=new FileOutputStream(f_output);
int t=fis.read();
while(t!=-1)
{
fos.write(t);
t=fis.read();
}

fis.close();
fos.close(); 
fis=new FileInputStream(f_output);
t=fis.read();
while(t!=-1)
{
System.out.print((char)t);
t=fis.read();
}
}
catch(Exception e)
{
System.out.print(e);
}
}
}

Hope this Java Program is useful to you in some sense or other. Keep following this blog for more Mumbai University MCA College Programs and simple Programs. Happy Programming and Studying

No comments:

Post a Comment