Java - File Upload And Download

java

http://tutorials.jenkov.com/java-io/index.html
http://tutorials.jenkov.com/java-io/bufferedoutputstream.html
https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html
https://docs.oracle.com/javase/tutorial/essential/io/charstreams.html
http://www.java2s.com/Code/Java/File-Input-Output/Utilitymethodsforfileandstreamcopying.htm
http://www.java2s.com/Code/Java/File-Input-Output/CopyALLavailabledatafromonestreamintoanotherwithChannel.htm
https://examples.javacodegeeks.com/core-java/io/copy-binary-file-with-streams/
http://www.mkyong.com/java/how-to-copy-file-in-java/
https://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/IOUtils.html
http://www.tutorialspoint.com/java/io/inputstream_read.htm

// Working with files:

// Creates a folder and the parent folders:
String folderName = "...";
File p = new File(folderName );
p.mkdirs();

// Read the entire content of a file into a string:
String fromFile = "..."; // Absolute path and name of a file
Path p = Paths.get(fromFile);
String fileContent = new String(Files.readAllBytes(p));

// Write a string to a file:
FileWriter writer = new FileWriter( new File(filename) );
writer.write(yourstring);

// Write a byte array to a file:
byte[] result = {};
FileOutputStream out = new FileOutputStream(fullPath);
out.write(result);
out.flush();
out.close();
out = null;

// Copy data from one stream to another stream one byte at a time:

FileInputStream in = null;
FileOutputStream out = null;

try {
    in = new FileInputStream("xanadu.txt");
    out = new FileOutputStream("outagain.txt");
    int c;

    while ((c = in.read()) != -1) {
        out.write(c);
    }
} finally {
    if (in != null) {
        in.close();
    }
    if (out != null) {
        out.close();
    }
}

// Scan a folder looking for files that match certain property:
File[] files = folder.listFiles(new FilenameFilter() {
    public boolean accept(File dir, String name) {
        String lowercaseName = name.toLowerCase();
        if (lowercaseName.endsWith(".pdf")) {
            return true;
        } else {
            return false;
        }
    }
});        

// Send a file as an attachment so that the browser open up the file download dialog:
File badFile = parser.createBadRecordsExcelFile(uploadedFile, lst);
String fileName = badFile.getName();
res.setHeader("Expires", "0");
res.setHeader("Cache-Control","private, must-revalidate, max-age=300, post-check=0, pre-check=0");
//res.setHeader("Pragma", "no-cache");
res.setContentType("application/vnd.ms-excel");
res.setHeader("Content-Disposition","attachment; filename=\"" + fileName + "\"");
res.setHeader("Content-Length", String.valueOf(badFile.length()));
ServletOutputStream servletoutputstream = res.getOutputStream();
int bufferSize = 10240; // 10KB
FileInputStream fileinputstream = new FileInputStream(badFile);
try {
    int i = fileinputstream.available();
    byte numOfBytes[] = new byte[i];
    int j = fileinputstream.read(numOfBytes);
    fileinputstream.close();
    servletoutputstream.write(numOfBytes);
} catch (Exception e) {
    fileinputstream.close();
    QGlobals.debugger.error("UploadFacilities","processData",e);
    throw new QuantrosException(e);
}
servletoutputstream.flush();
try {
    badFile.delete();
} catch (Exception e) {
    QGlobals.debugger.error("UploadFacilities","processData",e);
    throw new QuantrosException(e);                
}

// Check to see if a file exists:
File x = new File("C:\\tests\\greg.txt");
if (x.exists()) { ... }

// Read a text file one line at a time:
private Scanner input = new Scanner( new File("chinese.txt"));
while (input.hasNext()) { // while not end-of-file
  String a = input.next();  // read a string from the file
}

// Copy files:
File srcFile = new File(fromPath);
File destFile = new File(destination);
InputStream oInStream = new FileInputStream(srcFile);
OutputStream oOutStream = new FileOutputStream(destFile);
// Transfer bytes from in to out
byte[] oBytes = new byte[1024];
int nLength;
BufferedInputStream oBuffInputStream = new BufferedInputStream( oInStream );
while ((nLength = oBuffInputStream.read(oBytes)) != -1) {
    oOutStream.write(oBytes, 0, nLength);
}
oInStream.close();
oOutStream.close();

// Copy files:
String source = "...";
String destination = "...";
FileChannel srcChannel = new FileInputStream(source).getChannel();
FileChannel dstChannel = new FileOutputStream(destination).getChannel();
dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
srcChannel.close();
dstChannel.close();

// Reading user input from keyboard:
InputStreamReader istream = new InputStreamReader(System.in) ;
BufferedReader bufRead = new BufferedReader(istream) ;
System.out.print("Please enter the starting number:");
int start = Integer.parseInt(bufRead.readLine());
System.out.print("Please enter the ending number:");
int stop = Integer.parseInt(bufRead.readLine());

How can we write a byte array to a file?

byte[] result = {};
FileOutputStream out = new FileOutputStream(fullPath);
out.write(result);
out.flush();
out.close();
out = null;

In the above code, result is a byte array.

How can we create a directory and the parent directories if they are missing?

String folderName = "...";
File p = new File(folderName );
p.mkdirs();

How can we slurp or read the entire content of a file into a string?

String fromFile = "..."; // Absolute path and name of a file
Path p = Paths.get(fromFile);
String fileContent = new String(Files.readAllBytes(p));

How can we write a string to a file?

FileWriter writer = new FileWriter( new File(filename) );
writer.write(yourstring);

How can we copy data from one stream to another stream one byte at a time?

FileInputStream in = null;
FileOutputStream out = null;

try {
    in = new FileInputStream("xanadu.txt");
    out = new FileOutputStream("outagain.txt");
    int c;

    while ((c = in.read()) != -1) {
        out.write(c);
    }
} finally {
    if (in != null) {
        in.close();
    }
    if (out != null) {
        out.close();
    }
}

How can we scan a filter looking for files that match certain property?

print String convertPDFsToHTMLs(File folder) {
    File[] files = folder.listFiles(new FilenameFilter() {
        public boolean accept(File dir, String name) {
            String lowercaseName = name.toLowerCase();
            if (lowercaseName.endsWith(".pdf")) {
                return true;
            } else {
                return false;
            }
        }
    });        

    File file;
    int count = files.length;
    int i = 0;
    for (i = 0; i < count; i++) {
        file = files[i];
        String fileAbsolute = file.getAbsolutePath();
    }
}

In the above code, the convertPDFsToHTMLs method is given a File object which represent a folder. We then filter it for files ending with .pdf.

How can we send a file as an attachment so that the browser open up the file download dialog?

File file = new File(fileName);
response.setHeader("Content-Length", String.valueOf(file.length()));
response.setHeader("Content-Disposition", "attachment; filename=\""+ file.getName() + "\"");

String uploadID = iof.getParameter(req, "uploadID", "");
UploadFacilitiesParseExcel parser = new UploadFacilitiesParseExcel();
List lst = dao.getBadRecords(uploadID);
String uploadedFile = dao.getUploadedFile(uploadID);
File badFile = parser.createBadRecordsExcelFile(uploadedFile, lst);
String fileName = badFile.getName();
QGlobals.debugger.log("UploadFacilities","processData", "Bad record file name:" + fileName,  4);

res.setHeader("Expires", "0");
res.setHeader("Cache-Control","private, must-revalidate, max-age=300, post-check=0, pre-check=0");
//res.setHeader("Pragma", "no-cache");
res.setContentType("application/vnd.ms-excel");
res.setHeader("Content-Disposition","attachment; filename=\"" + fileName + "\"");
res.setHeader("Content-Length", String.valueOf(badFile.length()));

ServletOutputStream servletoutputstream = res.getOutputStream();
int bufferSize = 10240; // 10KB
//BufferedInputStream input = new BufferedInputStream(new FileInputStream(file), bufferSize);
//BufferedOutputStream output = new BufferedOutputStream(res.getOutputStream(), bufferSize);
FileInputStream fileinputstream = new FileInputStream(badFile);
QGlobals.debugger.log("UploadFacilities","processData", "Before sending excel content",  4);
try {
    int i = fileinputstream.available();
    byte numOfBytes[] = new byte[i];
    int j = fileinputstream.read(numOfBytes);
    fileinputstream.close();
    servletoutputstream.write(numOfBytes);
} catch (Exception e) {
    fileinputstream.close();
    QGlobals.debugger.error("UploadFacilities","processData",e);
    throw new QuantrosException(e);
}
servletoutputstream.flush();
try {
    badFile.delete();
} catch (Exception e) {
    QGlobals.debugger.error("UploadFacilities","processData",e);
    throw new QuantrosException(e);                
}

How can we check to see if a file exist?

import java.io.File;
import java.lang.*;
File x = new File("C:\\tests\\greg.txt");
if (x.exists()) { ... }

What is the purpose of the Formatter class?

NOT SURE. NEED RESEARCH.

// Writing to file
final Formatter x;
x = new Formatter("C:\\tests\\greg.txt"); // Create a file if not exist
x.format("%s\t%s\t%s", x, y, z);
x.close();

How can we read a text file one line at a time?

private Scanner input = new Scanner( new File("chinese.txt"));
while (input.hasNext()) { // while not end-of-file
  String a = input.next();  // read a string from the file
  String b = input.next();
  String c = input.next();
}

How can we copy files:

File srcFile = new File(fromPath);
File destFile = new File(destination);
InputStream oInStream = new FileInputStream(srcFile);
OutputStream oOutStream = new FileOutputStream(destFile);
// Transfer bytes from in to out
byte[] oBytes = new byte[1024];
int nLength;
BufferedInputStream oBuffInputStream = new BufferedInputStream( oInStream );
while ((nLength = oBuffInputStream.read(oBytes)) != -1) {
    oOutStream.write(oBytes, 0, nLength);
}
oInStream.close();
oOutStream.close();
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.Reader;
import java.io.DataInputStream;
import java.nio.channels.FileChannel;

public void copyFile(String source, String destination) throws Exception {
    // http://www.exampledepot.com/egs/java.nio/File2File.html
    // http://www.exampledepot.com/egs/java.io/CopyFile.html
    FileChannel srcChannel = new FileInputStream(source).getChannel();
    FileChannel dstChannel = new FileOutputStream(destination).getChannel();
    dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
    srcChannel.close();
    dstChannel.close();
}
            public void copyFile(String source, String destination) throws Exception {
                // http://www.exampledepot.com/egs/java.nio/File2File.html
                // http://www.exampledepot.com/egs/java.io/CopyFile.html
                FileChannel srcChannel = new FileInputStream(source).getChannel();
                FileChannel dstChannel = new FileOutputStream(destination).getChannel();
                dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
                srcChannel.close();
                dstChannel.close();
            }
fis = new FileInputStream(strFileLoc);
//ASK ME: If 3145728 is used instead of 8164, "Connection reset by peer: socket write error" error is thrown in sendOutput method, why?
byte[] arrB = new byte[5000]; 
bos = new ByteArrayOutputStream();
int len = 0, totLen = 0;

/*    while( (len = fis.read(arrB, 0, 8164)) != -1 ) {        
        bos.write(arrB);    
        totLen += len;
    }*/
//Case#00032571: There was an error opening this document. The file is damaged and could not be repaired
while((len  = fis.read(arrB))!=-1) {
    if(len  == 5000) {
        bos.write(arrB);
    } else {
        bos.write(arrB, 0, len);
    }
    arrB = null;
    arrB = new byte[5000];
    totLen += len;
}    
res.setContentType(contentType);        
res.setContentLength(out.size());        
ServletOutputStream outstream = null;            
outstream = res.getOutputStream();        
// System.out.println(bos.size());        
bos.writeTo(outstream);    
bos.flush();        
bos.close();

Another example of working with files and getting user input from keyboard:

import java.io.*;

public class StressTest {
    private static String destinationFolder = "C:\\bea\\user_projects\\domains\\quantrosDev\\applications\\myquantros.ear\\quantros.war\\";
    private static String filename = "";
    public static void main(String[] args) throws Exception {
        InputStreamReader istream = new InputStreamReader(System.in) ;
        BufferedReader bufRead = new BufferedReader(istream) ;
        System.out.print("Please enter the starting number:");
        int start = Integer.parseInt(bufRead.readLine());
        System.out.print("Please enter the ending number:");
        int stop = Integer.parseInt(bufRead.readLine());
        for (int i=start; i < stop; i++) {
            filename = destinationFolder + "khaitest" + i;
            File fd = new File(filename);
            fd.createNewFile();
            FileWriter fstream = new FileWriter(filename);
            BufferedWriter out = new BufferedWriter(fstream);
            out.write("It is a long established fact that a reader will be distracted by the readable content 
            of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less 
            normal distribution of letters, as opposed to using 'Content here, content here', making it look like 
            readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum 
            as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in 
            their infancy. Various versions have evolved over the years, sometimes by accident, sometimes 
            on purpose (injected humour and the like).");
            out.close();
        }
        System.out.println("Please see that you can start your weblogic and load your page");
    }
}
import java.io.*;

public class DeleteTestFiles {
    private static String destinationFolder = "C:\\bea\\user_projects\\domains\\quantrosDev\\applications\\myquantros.ear\\quantros.war\\";
    private static String filename = "";
    public static void main(String[] args) throws Exception {
        InputStreamReader istream = new InputStreamReader(System.in) ;
        BufferedReader bufRead = new BufferedReader(istream) ;
        System.out.print("Please enter the starting number:");
        int start = Integer.parseInt(bufRead.readLine());
        System.out.print("Please enter the ending number:");
        int stop = Integer.parseInt(bufRead.readLine());
        for (int i=start; i < stop; i++) {
            filename = destinationFolder + "khaitest" + i;
            File fd = new File(filename);
            fd.delete();
        }
        System.out.println("Please see that you can start your weblogic and load your page");
    }
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License