1. TTfile
  2. JSP File
  3. How to copy a file in JSP?

How to copy a file in JSP?

Java doesn't offer a neat and pretty one-liner for copying files. However, Java's file input-output (I/O) classes make it fairly easy to write your own file copying functionality. Get started by writing the file copy functionality as scriptlet code directly in your Java ServerPages (JSP) page.

The Basics and Catch Clause

Step 1

Import the Java classes you'll need for reading and writing files using the page directive in your JSP page:

<%@ page import="java.io.*" %>

Step 2

Create a try-catch block in your JSP page to handle IOException:

<%

try {}

catch (IOException ex) {}

%>

Step 3

Handle IOException errors inside the catch clause as needed for the JSP page to fail gracefully. Print the exception message in glaring colors into the JSP page by breaking out of the scriptlet code:

catch (IOException ex) { %>

<%=ex.getMessage()%>

<% }

The Try Block

Step 1

Open the source file (the file you want to copy) and the destination file (where the copy will be written to) inside the try-block. SrcFileName and dstFileName are string variables containing the path and file name of each file:

File srcFile = new File(srcFileName);

File dstFile = new File(dstFileName);

Step 2

Check that the source file exists, and throw an IOException if it doesn't:

if (!srcFile.exists()) {

throw new IOException("No source file: " + srcFileName);

}

Step 3

Check that the destination file exists and is writable. Throw an IOException if it isn't:

if (dstFile.exists()) {

if (!dstFile.canWrite()) {

throw new IOException("Destination read-only: " + dstFileName);

}

}

else {

throw new IOException("Destination not created: " + dstFileName);

}

Step 4

Open source and destination file streams:

FileInputStream srcStrm = new FileInputStream(srcFile);

FileOutputStream dstStrm = new FileOutputStream(dstFile);

Step 5

Create a byte array to hold data:

byte[] buf = new byte[4096];

Step 6

Read from the source stream and write to the destination stream in a while loop that continues until all the data have been read from the source file:

int len;

while ((len = srcStrm.read(buf)) > 0) {

dstStrm.write(buf, 0, len);

}

Step 7

Close the file streams:

srcStrm.close();

dstStrm.close();