• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Program to Copy *.txt files in a Directory

 
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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);
}
}
}

}
}
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic