Java Program to read data from a file and write into another file

Java is one of the most favorite and popular programming language choice for many programmers. Today, We are going to see an example where we will read text or data from a text file and write the same in another file.

Java Program to read data from a file and write into another file:

import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class ReadAndWrite {
    public static void main(String[] args) throws IOException {
        FileOutputStream fos;
        DataOutputStream dos;
        FileInputStream fis = new FileInputStream("D://java//examplefile.txt");
		byte[] byt=new byte[fis.available()];
		fis.read(byt);
		fos = new FileOutputStream("D://java//newfile.txt");
		dos = new DataOutputStream(fos);
		dos.write(byt);
        dos.close();
        fos.close();
    }
}

To run this program:

1. You must have JVM installed on your system and classpath must be set correctly.
2. Now, Save the file with name ReadAndWrite.java
3. Open CMD or command prompt
4. Compile the program using the command: javac ReadAndWrite.java
5. Execute the program using the command: java ReadAndWrite

Hope this example was useful for you.

Good Luck!

Related Post

Advertisements

admin has written 4 articles