Principle: Copy a file to another file.
The Code for action is given here, and the other pages are omitted:
Packagecn.itcast.action;ImportJava.io.BufferedInputStream;ImportJava.io.BufferedOutputStream;ImportJava.io.File;ImportJava.io.FileInputStream;Importjava.io.FileNotFoundException;ImportJava.io.FileOutputStream;ImportJava.io.InputStream;ImportJava.io.OutputStream;ImportCom.opensymphony.xwork2.ActionSupport; Public classFileuploadactionextendsactionsupport{//File copy function//src represents the source file, DST indicates the destination file Public voidCopy (File src,file DST)throwsexception{//defines an input stream object that needs to provide an input stream object using a buffer classInputStream in =NewBufferedinputstream (NewFileInputStream (SRC)); OutputStream out=NewBufferedoutputstream (NewFileOutputStream (DST)); //declares a byte array that is used to store the data read in byte[] B =New byte[1024]; intLength=0; //iterates through the input stream object, reads the input stream into a byte array, returns the length of bytes read, and returns 1 if read to the end while( -1!= (length=In.read (b))) {Out.write (b);//writes the data of the byte array to the output stream file.} }
Method Two:
public void Copy2 (File src,file DST) throws exception{
InputStream in = new FileInputStream (SRC);
OutputStream out = new FileOutputStream (DST);
Byte[] B = new byte[1024];
int len = 0;
while ((Len=in.read (b))!=-1) {
Out.write (b);
}
} Public Static voidMain (String args[]) {File image=NewFile ("C:\\bb.jpg"); Let's say this is the file to be uploaded files Image2=NewFile ("C:\\bb2.jpg");//This represents the file uploaded to the server fileuploadaction fileuploadaction=Newfileuploadaction (); Try{fileuploadaction.copy (image, Image2); } Catch(Exception e) {e.printstacktrace (); } }}
There are many ways to upload files, and the principle is to copy files. Copied from the input stream into the output stream.
Strut2 File Upload