Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Try reading the file in chunks from Server while writing to client output stream rather than creating a temp byte array and reading entire file into memory. What if requested file is large? Also close the new Socket on server-side in a finally block so socket is closed even if an exception is thrown.</p> <p>Server Side:</p> <pre><code> Socket newCon = ss.accept(); FileInputStream is = null; OutputStream out = null; try { InputStream sin = newCon.getInputStream(); DataInputStream sdata = new DataInputStream(sin); String location = sdata.readUTF(); System.out.println("location=" + location); File toSend = new File(location); // TODO: validate file is safe to access here if (!toSend.exists()) { System.out.println("File does not exist"); return; } is = new FileInputStream(toSend); out = newCon.getOutputStream(); int bytesRead; byte[] buffer = new byte[4096]; while ((bytesRead = is.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } out.flush(); } finally { if (out != null) try { out.close(); } catch(IOException e) { } if (is != null) try { is.close(); } catch(IOException e) { } newCon.close(); } </code></pre> <p>If you use <a href="http://commons.apache.org/io/" rel="nofollow">Apache Common IOUtils</a> library then you can reduce much of the code to read/write files to streams. Here 5-lines down to one line.</p> <pre><code>org.apache.commons.io.IOUtils.copy(is, out); </code></pre> <p>Note that having a server that serves files by absolute path to remote clients is potentially dangerous and the target file should be restricted to a given directory and/or set of file types. Don't want to serve out system-level files to unauthenticated clients.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload