Sunday 6 March 2022

Java: Copy the content of file to other location

Below snippet copy the content of file to other location.

 

 

Find the below working application.

 

CopyFile.java

package com.sample.app.files;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyFile {

	public static void copy(String src, String destination) throws FileNotFoundException, IOException {
		File destinationFile = new File(destination);
		File destinationParentFolder = destinationFile.getParentFile();

		// Create parent directories if not exists
		if (!destinationParentFolder.exists()) {
			destinationParentFolder.mkdirs();
		}

		try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(src));
				BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destination))) {

			byte[] inbuf = new byte[32768];
			int n;

			while ((n = bis.read(inbuf)) != -1) {
				bos.write(inbuf, 0, n);
			}

		}
	}

	public static void main(String[] args) throws FileNotFoundException, IOException {
		String src = "/users/Shared/a.txt";
		String dest = "/users/Shared/dir1/b.txt";

		copy(src, dest);

	}

}




You may like

File programs in Java

Get the resource file path

Get file name from absolute path

Count number of lines in a file

Download file from Internet using Java

Get the content of resource file as string

No comments:

Post a Comment