Win a copy of The Journey To Enterprise Agility this week in the Agile and Other Processes forum! And see the welcome thread for 20% off.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Paul Clapham
  • Junilu Lacar
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Ganesh Patekar
  • Tim Moores
  • Pete Letkeman
  • Stephan van Hulst
  • Carey Brown
  • Tim Holloway
  • Joe Ess

Program to Copy *.txt files in a Directory  RSS feed

Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
Ranch Hand
Posts: 135
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can use IO streams in Java. These IO streams are available in package.
Program which does your task is :

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++){


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);


  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!