[Logo]
Forums Register Login
Program to Copy *.txt files in a Directory
Hi Guys,
I need to write a JAVA program that copies all text files in a Directory
to another Directory.
I tried using runtime.exec(cmd /c copy *.txt ../newdir)
But it is working erratically...some times it copies..but some times it doesn't.....are there JAVA API's which can do this ?
Thanks in Advance.
There aren't any Java APIs to the OS copy command. You can write the copy operations yourself. Create a File object with the directory name, use the list() method to find all the files in the directory, for each text file create another pair of File objects for copy source and copy destination, read bytes from source and write bytes to destination. Is that enough to go on?
You can use IO streams in Java. These IO streams are available in java.io package.
Program which does your task is :
import java.io.*;

class TextFileCopy{

public static void main(String argv[]) throws Exception{

FileInputStream fin;//File I/O streams
FileOutputStream fout;
BufferedInputStream bin;//wrap file streams with buffered streams
BufferedOutputStream bout;

File srcDir,destDir,fileList[];
int ch;
String fileName;

srcDir=new File("C:/My Documents");//source directory

destDir=new File("C:/");//destination directory



fileList=srcDir.listFiles();//list all file of the directory

for(int i=0;i<fileList.length;i++){

fileName=fileList[i].getAbsolutePath().trim();


if(fileName.endsWith(".txt")){ //check for text files
fin=new FileInputStream(new File(fileName));
bin=new BufferedInputStream(fin);

fout=new FileOutputStream(destDir+fileList[i].getName().trim());
bout=new BufferedOutputStream(fout);

while((ch=bin.read())!=-1){
bout.write(ch);
}
}
}

}
}

This thread has been viewed 1557 times.

All times above are in ranch (not your local) time.
The current ranch time is
Sep 23, 2018 07:50:15.