Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You must separate the stream copy from the free filename assignation. The stream copy must be done within the calling thread (jersey service). Only the file naming operation must be common to all threads/requests.</p> <p>Here is your code with a little refactoring :</p> <p><strong>getNextFilename</strong></p> <p>This file naming operation must be synchronized to guarantee each call gives a free name. This functions creates an empty file to guarantee the next call to work, because the function relies on file.exists().</p> <pre><code>public synchronized File getNextFilename(String uploadedFileLocation, String extension) throws IOException { // This function MUST be synchronized to guarantee unicity of files names // Synchronized functions must be the shortest possible to avoid threads waiting each other. // No long job such as copying streams here ! String fileName = "raw"; //Create directories (if not already existing) File dir = new File(uploadedFileLocation); if (!dir.exists()) dir.mkdirs(); //Search for next free filename (raw.&lt;extension&gt;, else raw_&lt;increment&gt;.&lt;extension&gt;) int currentIncrement = 0; String finalFileName = fileName + "." + extension; File f = new File(uploadedFileLocation + finalFileName); while (f.exists()) { currentIncrement++; finalFileName = fileName + "_" + currentIncrement + "." + extension; f = new File(uploadedFileLocation + finalFileName); } //Creates the file with size 0 in order to physically reserve the file "raw_&lt;n&gt;.extension", //so the next call to getNextFilename will find it (f.exists) and will return "raw_&lt;n+1&gt;.extension" f.createNewFile(); //The file exists, let the caller fill it... return f; } </code></pre> <p><strong>writeToFile</strong></p> <p>Must not be synchronized !</p> <pre><code>public void writeToFile(InputStream rawData, String uploadedFileLocation, String extension) throws IOException { //(1) Gets next available filename (creates the file with 0 size) File file = getNextFilename(uploadedFileLocation, extension); //(2) Copies data from inputStream to file int read = 0; byte[] bytes = new byte[1024]; OutputStream out = new FileOutputStream(file); while ((read = rawData.read(bytes)) != -1) { out.write(bytes, 0, read); } out.flush(); out.close(); } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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