# code to upload a file in java



## radhika123 (Apr 2, 2008)

HI friends
I want to know how to upload a file in java.
After submitting the selected file should be copied in a folder created by us only.
I mean first we need to select a file using browse,then after submitting the selected file should be placed in a folder ,this folder should be created by us only using mkdir();
Can any one send me the code to upload a file.
Thanks in advance


----------



## Chicon (Jul 29, 2004)

Hi radhika123,

Welcome to Tsg ! 

The following examples work even if the destination folder is a shared folder of a remote system.

To move the file to another directory

```
[SIZE=2]
String srcDir = "C:\\source";
String dstDir = "Z:\\destination";
String filNam = "file.ext";

File f = new File(srcDir + File.separator + filNam);
f.renameTo(new File(dstDir + File.separator + filNam));
[/SIZE]
```
To copy the file to another directory

```
[SIZE=2]
String srcDir = "C:\\source";
String dstDir = "Z:\\destination";
String filNam = "file.ext";

try {
   BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcDir + File.separator + filNam));
   BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dstDir + File.separator + filNam));
   byte[] buf = new byte[1024];
   int len;
   while ((len = bis.read(buf)) > 0) {
      bos.write(buf, 0, len);
   }
   bos.close();
   bis.close();
} catch(IOException ioe) {
      System.out.println(ioe.getMessage());
}
[/SIZE]
```


----------

