Tutorials Java Copying the Contents of One text file to Another in Java

Copying the Contents of One text file to Another in Java

In this example, we will see a sample program to copying the contents of one text file to another in Java.

package com.javatechig;

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 CopyFileContent {

	public static void main(String[] args) {

		/* Source file, from which content will be copied */
		File sourceFile = new File("file1.txt");

		/* destination file, where the content to be pasted */
		File destFile = new File("file2.txt");
		
		/* if file not exist then create one */
		if (!destFile.exists()) {
			try {
				destFile.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		InputStream input = null;
		OutputStream output = null;

		try {

			/* FileInputStream to read streams */
			input = new FileInputStream(sourceFile);

			/* FileOutputStream to write streams */
			output = new FileOutputStream(destFile);

			byte[] buf = new byte[1024];
			int bytesRead;

			while ((bytesRead = input.read(buf)) > 0) {
				output.write(buf, 0, bytesRead);
			}

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		finally {
			try {

				if (null != input) {
					input.close();
				}
				
				if (null != output) {
					output.close();
				}

			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
Total
0
Shares
guest
3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Ashuil.com
Ashuil.com
7 years ago

copying entire file is one thing but to copy the text between 2 delimiters is different. I’m trying to write a program which finds a string say and start writing the text from here till it finds another string say . If you can share your thoughts.

Thanks!

kittu
kittu
6 years ago
Reply to  Ashuil.com

do u got the solution ?

kittu
kittu
6 years ago
Reply to  Ashuil.com

hi.. if you have got the solution then plz share

Previous Post
Java Tutorials

How to Create a Text File in Java

Next Post
Java Tutorials

Copy file from one folder to another in java

Related Posts
By clicking “Allow All”, you agree to the storing of cookies on your device to enhance site navigation, analyze site usage, and assist in our marketing efforts. Cookie Notice
Allow All
3
0
Would love your thoughts, please comment.x
()
x