Here you can find the source of readFile(String path, String root, OutputStream out)
public static void readFile(String path, String root, OutputStream out) throws IOException
//package com.java2s; //License from project: Open Source License import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.OutputStream; public class Main { /**/* ww w . jav a2 s . c o m*/ * Dump the contents of the given path (relative to the root) to the output * stream. The path must not go above the root, either - if it does, it will * throw a FileNotFoundException * * Closes the OutputStream out on successful completion * but leaves it open when throwing IOE. */ public static void readFile(String path, String root, OutputStream out) throws IOException { File rootDir = new File(root); while (path.startsWith("/") && (path.length() > 0)) path = path.substring(1); if (path.length() <= 0) throw new FileNotFoundException("Not serving up the root dir"); File target = new File(rootDir, path); if (!target.exists()) throw new FileNotFoundException("Requested file does not exist: " + path); String targetStr = target.getCanonicalPath(); String rootDirStr = rootDir.getCanonicalPath(); if (!targetStr.startsWith(rootDirStr)) throw new FileNotFoundException("Requested file is outside the root dir: " + path); byte buf[] = new byte[4 * 1024]; FileInputStream in = null; try { in = new FileInputStream(target); int read = 0; while ((read = in.read(buf)) != -1) out.write(buf, 0, read); try { out.close(); } catch (IOException ioe) { } } finally { if (in != null) try { in.close(); } catch (IOException ioe) { } } } }