Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

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

 
siva krishnan
Greenhorn
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.
 
Stan James
(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?
 
Idly Vada
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 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.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!