This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes I/O and Streams and the fly likes copy a any type of file Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » I/O and Streams
Reply locked New topic
Author

copy a any type of file

sam liyanage
Ranch Hand

Joined: Nov 25, 2008
Posts: 1087
i tried many times with below code.but it copy only the text files correctly.if file is non text it copy,but unable to open.
so please give me java code that copy any type of file(ex jpg,doc,war,mpg



package write;
import java.util.*;
import java.io.*;

class Read{
private static ArrayList<Byte> file = new ArrayList<Byte>();
private static String path="g:\\write\\name.txt";


private void reader()throws IOException //read a file and put to the arraylist
{
File f;
f=new File("g:\\read\\a.txt");

if(!f.exists()&& f.length()<0)
System.out.println("The specified file is not exist");

else{ ;


FileInputStream finp=new FileInputStream(f);

byte b=(byte)finp.read();

int i=0;
while(b!=-1)
{
file.add(b);
char d=(char)b;
Character ch=new Character(d);

String s=ch.toString();


b=(byte)finp.read();
i++;
}
finp.close();

}

}

private void writer()throws IOException //get byte by byte from arraylist and write to the file
{
File f=new File(path);
FileOutputStream fop=new FileOutputStream(f);

if(f.exists()){
String str="This data is written through the program";

Object []oa=file.toArray();
for(Object oa)
{
Byte b=(Byte)o;
fop.write(b);

}

fop.flush();
fop.close();

}
}


public static void main(String[] args) {
try{
Read r=new Read();
rd.reader();
rd.writer();
}catch(Exception e)
{
e.printStackTrace();
}
}
})
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19677
    
  18

Again, please Use Code Tags.

Also please Use One Thread Per Question. I don't see how this question is any different from this one.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
Don't get me started about those stupid light bulbs.
 
subject: copy a any type of file