Example usage for java.io DataOutputStream write

List of usage examples for java.io DataOutputStream write

Introduction

In this page you can find the example usage for java.io DataOutputStream write.

Prototype

public synchronized void write(byte b[], int off, int len) throws IOException 

Source Link

Document

Writes len bytes from the specified byte array starting at offset off to the underlying output stream.

Usage

From source file:com.orange.labs.sdk.RestUtils.java

public void uploadRequest(URL url, File file, String folderIdentifier, final Map<String, String> headers,
        final OrangeListener.Success<JSONObject> success, final OrangeListener.Progress progress,
        final OrangeListener.Error failure) {

    // open a URL connection to the Server
    FileInputStream fileInputStream = null;
    try {// w  w w  .  j a va  2s .c  o  m
        fileInputStream = new FileInputStream(file);

        // Open a HTTP connection to the URL
        HttpURLConnection conn = (HttpsURLConnection) url.openConnection();

        // Allow Inputs & Outputs
        conn.setDoInput(true);
        conn.setDoOutput(true);

        // Don't use a Cached Copy
        conn.setUseCaches(false);

        conn.setRequestMethod("POST");

        //
        // Define headers
        //

        // Create an unique boundary
        String boundary = "UploadBoundary";

        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        for (String key : headers.keySet()) {
            conn.setRequestProperty(key.toString(), headers.get(key));
        }

        //
        // Write body part
        //
        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

        int bytesAvailable = fileInputStream.available();

        String marker = "\r\n--" + boundary + "\r\n";

        dos.writeBytes(marker);
        dos.writeBytes("Content-Disposition: form-data; name=\"description\"\r\n\r\n");

        // Create JSonObject :
        JSONObject params = new JSONObject();
        params.put("name", file.getName());
        params.put("size", String.valueOf(bytesAvailable));
        params.put("folder", folderIdentifier);

        dos.writeBytes(params.toString());

        dos.writeBytes(marker);
        dos.writeBytes(
                "Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"\r\n");
        dos.writeBytes("Content-Type: image/jpeg\r\n\r\n");

        int progressValue = 0;
        int bytesRead = 0;
        byte buf[] = new byte[1024];
        BufferedInputStream bufInput = new BufferedInputStream(fileInputStream);
        while ((bytesRead = bufInput.read(buf)) != -1) {
            // write output
            dos.write(buf, 0, bytesRead);
            dos.flush();
            progressValue += bytesRead;
            // update progress bar
            progress.onProgress((float) progressValue / bytesAvailable);
        }

        dos.writeBytes(marker);

        //
        // Responses from the server (code and message)
        //
        int serverResponseCode = conn.getResponseCode();
        String serverResponseMessage = conn.getResponseMessage();

        // close streams
        fileInputStream.close();
        dos.flush();
        dos.close();

        if (serverResponseCode == 200 || serverResponseCode == 201) {
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));

            String response = "";
            String line;
            while ((line = rd.readLine()) != null) {
                Log.i("FileUpload", "Response: " + line);
                response += line;
            }
            rd.close();
            JSONObject object = new JSONObject(response);
            success.onResponse(object);
        } else {
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
            String response = "";
            String line;
            while ((line = rd.readLine()) != null) {
                Log.i("FileUpload", "Error: " + line);
                response += line;
            }
            rd.close();
            JSONObject errorResponse = new JSONObject(response);
            failure.onErrorResponse(new CloudAPIException(serverResponseCode, errorResponse));
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.caboclo.clients.OneDriveClient.java

@Override
public void putFile(File file, String path) throws IOException {
    final String BOUNDARY_STRING = "3i2ndDfv2rThIsIsPrOjEcTSYNceEMCPROTOTYPEfj3q2f";

    //We use the directory name (without actual file name) to get folder ID
    int indDirName = path.replace("/", "\\").lastIndexOf("\\");
    String targetFolderId = getFolderID(path.substring(0, indDirName));
    System.out.printf("Put file: %s\tId: %s\n", path, targetFolderId);

    if (targetFolderId == null || targetFolderId.isEmpty()) {
        return;//  w ww.  j a va2s .c  o  m
    }

    URL connectURL = new URL("https://apis.live.net/v5.0/" + targetFolderId + "/files?"
            + "state=MyNewFileState&redirect_uri=https://login.live.com/oauth20_desktop.srf" + "&access_token="
            + accessToken);
    HttpURLConnection conn = (HttpURLConnection) connectURL.openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY_STRING);
    // set read & write
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.connect();
    // set body
    DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
    dos.writeBytes("--" + BOUNDARY_STRING + "\r\n");
    dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\""
            + URLEncoder.encode(file.getName(), "UTF-8") + "\"\r\n");
    dos.writeBytes("Content-Type: application/octet-stream\r\n");
    dos.writeBytes("\r\n");

    FileInputStream fileInputStream = new FileInputStream(file);
    int fileSize = fileInputStream.available();
    int maxBufferSize = 8 * 1024;
    int bufferSize = Math.min(fileSize, maxBufferSize);
    byte[] buffer = new byte[bufferSize];

    // send file
    int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    while (bytesRead > 0) {

        // Upload file part(s)
        dos.write(buffer, 0, bytesRead);

        int bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, buffer.length);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    }
    fileInputStream.close();
    // send file end

    dos.writeBytes("\r\n");
    dos.writeBytes("--" + BOUNDARY_STRING + "--\r\n");

    dos.flush();

    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line = null;
    StringBuilder sbuilder = new StringBuilder();
    while ((line = reader.readLine()) != null) {
        sbuilder.append(line);
    }

    String fileId = null;
    try {
        JSONObject json = new JSONObject(sbuilder.toString());
        fileId = json.getString("id");
        //System.out.println("File ID is: " + fileId);
        //System.out.println("File name is: " + json.getString("name"));
        //System.out.println("File uploaded sucessfully.");
    } catch (JSONException e) {
        Logger.getLogger(OneDriveClient.class.getName()).log(Level.WARNING,
                "Error uploading file " + file.getName(), e);
    }
}

From source file:ClassFile.java

public void write(DataOutputStream dos, ConstantPoolInfo pool[]) throws IOException, Exception {
    dos.writeShort(ConstantPoolInfo.indexOf(name, pool));
    dos.writeInt(data.length);//from  w w w . j  a  v a2s  .co m
    dos.write(data, 0, data.length);
}

From source file:com.bemis.portal.fileuploader.service.impl.FileUploaderLocalServiceImpl.java

public void uploadFiles(long companyId, long groupId, long userId, File file, long fileTypeId,
        String[] assetTagNames) throws IOException, PortalException {

    String fileName = file.getName();

    if (!fileName.endsWith(".zip")) {
        if (_log.isWarnEnabled()) {
            _log.warn(">>> Unsupported compressed file type. Supports ZIP" + "compressed files only. ");
        }/*w  w  w.  j  a va2 s. co  m*/

        throw new FileUploaderException("error.unsupported-file-type");
    }

    DataOutputStream outputStream = null;

    try (ZipInputStream inputStream = new ZipInputStream(new BufferedInputStream(new FileInputStream(file)))) {

        ZipEntry fileEntry;
        while ((fileEntry = inputStream.getNextEntry()) != null) {
            boolean isDir = fileEntry.isDirectory();
            boolean isSubDirFile = fileEntry.getName().contains(SLASH);

            if (isDir || isSubDirFile) {
                if (_log.isWarnEnabled()) {
                    _log.warn(">>> Directory found inside the zip file " + "uploaded.");
                }

                continue;
            }

            String fileEntryName = fileEntry.getName();

            String extension = PERIOD + FileUtil.getExtension(fileEntryName);

            File tempFile = null;

            try {
                tempFile = File.createTempFile("tempfile", extension);

                byte[] buffer = new byte[INPUT_BUFFER];

                outputStream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(tempFile)));

                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }

                outputStream.flush();

                String fileDescription = BLANK;
                String changeLog = BLANK;

                uploadFile(companyId, groupId, userId, tempFile, fileDescription, fileEntryName, fileTypeId,
                        changeLog, assetTagNames);
            } finally {
                StreamUtil.cleanUp(outputStream);

                if ((tempFile != null) && tempFile.exists()) {
                    tempFile.delete();
                }
            }
        }
    } catch (FileNotFoundException fnfe) {
        if (_log.isWarnEnabled()) {
            _log.warn(">>> Unable to upload files" + fnfe);
        }
    }
}

From source file:com.splout.db.dnode.HttpFileExchanger.java

public void send(final String tablespace, final int partition, final long version, final File binaryFile,
        final String url, boolean blockUntilComplete) {
    Future<?> future = clientExecutors.submit(new Runnable() {
        @Override//from   w w  w.j  a v a 2 s  . c  o  m
        public void run() {
            DataOutputStream writer = null;
            InputStream input = null;
            try {
                HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
                connection.setChunkedStreamingMode(config.getInt(FetcherProperties.DOWNLOAD_BUFFER));
                connection.setDoOutput(true);
                connection.setRequestProperty("filename", binaryFile.getName());
                connection.setRequestProperty("tablespace", tablespace);
                connection.setRequestProperty("partition", partition + "");
                connection.setRequestProperty("version", version + "");

                Checksum checkSum = new CRC32();

                writer = new DataOutputStream(new GZIPOutputStream(connection.getOutputStream()));
                // 1 - write file size
                writer.writeLong(binaryFile.length());
                writer.flush();
                // 2 - write file content
                input = new FileInputStream(binaryFile);
                byte[] buffer = new byte[config.getInt(FetcherProperties.DOWNLOAD_BUFFER)];
                long wrote = 0;
                for (int length = 0; (length = input.read(buffer)) > 0;) {
                    writer.write(buffer, 0, length);
                    checkSum.update(buffer, 0, length);
                    wrote += length;
                }
                // 3 - add the CRC so that we can verify the download
                writer.writeLong(checkSum.getValue());
                writer.flush();
                log.info("Sent file " + binaryFile + " to " + url + " with #bytes: " + wrote + " and checksum: "
                        + checkSum.getValue());
            } catch (IOException e) {
                log.error(e);
            } finally {
                try {
                    if (input != null) {
                        input.close();
                    }
                    if (writer != null) {
                        writer.close();
                    }
                } catch (IOException ignore) {
                }
            }
        }
    });
    try {
        if (blockUntilComplete) {
            while (future.isDone() || future.isCancelled()) {
                Thread.sleep(1000);
            }
        }
    } catch (InterruptedException e) {
        // interrupted!
    }
}

From source file:com.trigger_context.Main_Service.java

private void sendFile(DataOutputStream out, String Path) {
    Log.i(Main_Service.LOG_TAG, "SendFile--Start");
    File infile = new File(Path);
    String FileName = null;// w  w  w. j av a2s.  c o  m
    try {

        FileName = Path.substring(Path.lastIndexOf("/") + 1);
        out.writeUTF(FileName);
        out.writeLong(infile.length());
    } catch (IOException e) {
        Log.i(Main_Service.LOG_TAG, "SendFile--error sending filename length");
    }

    byte[] mybytearray = new byte[(int) infile.length()];

    FileInputStream fis = null;
    ;
    try {
        fis = new FileInputStream(infile);
    } catch (FileNotFoundException e1) {
        Log.i(Main_Service.LOG_TAG, "sendFile--Error file not found");
    }
    BufferedInputStream bis = new BufferedInputStream(fis);

    DataInputStream dis = new DataInputStream(bis);
    try {
        dis.readFully(mybytearray, 0, mybytearray.length);
    } catch (IOException e1) {
        Log.i(Main_Service.LOG_TAG, "sendFile--Error while reading bytes from file");

    }

    try {
        out.write(mybytearray, 0, mybytearray.length);
    } catch (IOException e1) {
        Log.i(Main_Service.LOG_TAG, "sendFile--error while sending");
    }

    try {
        dis.close();
        bis.close();
        fis.close();
    } catch (IOException e) {

        Log.i(Main_Service.LOG_TAG, "sendFile--error in closing streams");
    }

}

From source file:ipc.Server.java

private void wrapWithSasl(ByteArrayOutputStream response, Call call) throws IOException {
    if (call.connection.useSasl) {
        byte[] token = response.toByteArray();
        // synchronization may be needed since there can be multiple Handler
        // threads using saslServer to wrap responses.
        synchronized (call.connection.saslServer) {
            token = call.connection.saslServer.wrap(token, 0, token.length);
        }//from  ww  w .jav  a  2s.  co m
        if (LOG.isDebugEnabled())
            LOG.debug("Adding saslServer wrapped token of size " + token.length + " as call response.");
        response.reset();
        DataOutputStream saslOut = new DataOutputStream(response);
        saslOut.writeInt(token.length);
        saslOut.write(token, 0, token.length);
    }
}

From source file:csic.ceab.movelab.beepath.Util.java

public static boolean uploadFile(byte[] bytes, String filename, String uploadurl) {

    HttpURLConnection conn = null;
    DataOutputStream dos = null;
    // DataInputStream inStream = null;

    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";

    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 64 * 1024; // old value 1024*1024
    ByteArrayInputStream byteArrayInputStream = null;
    boolean isSuccess = true;
    try {// ww w  . ja v  a 2s .  c  o m
        // ------------------ CLIENT REQUEST

        byteArrayInputStream = new ByteArrayInputStream(bytes);

        // open a URL connection to the Servlet
        URL url = new URL(uploadurl);
        // Open a HTTP connection to the URL
        conn = (HttpURLConnection) url.openConnection();
        // Allow Inputs
        conn.setDoInput(true);
        // Allow Outputs
        conn.setDoOutput(true);
        // Don't use a cached copy.
        conn.setUseCaches(false);
        // set timeout
        conn.setConnectTimeout(60000);
        conn.setReadTimeout(60000);
        // Use a post method.
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

        dos = new DataOutputStream(conn.getOutputStream());
        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + filename + "\""
                + lineEnd);
        dos.writeBytes(lineEnd);

        // create a buffer of maximum size
        bytesAvailable = byteArrayInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];

        // read file and write it into form...
        bytesRead = byteArrayInputStream.read(buffer, 0, bufferSize);
        while (bytesRead > 0) {
            dos.write(buffer, 0, bufferSize);
            bytesAvailable = byteArrayInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = byteArrayInputStream.read(buffer, 0, bufferSize);
        }

        // send multipart form data necesssary after file data...
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

        // close streams
        // Log.e(TAG,"UploadService Runnable:File is written");
        // fileInputStream.close();
        // dos.flush();
        // dos.close();
    } catch (Exception e) {
        // Log.e(TAG, "UploadService Runnable:Client Request error", e);
        isSuccess = false;
    } finally {
        if (dos != null) {
            try {
                dos.close();
            } catch (IOException e) {
                // Log.e(TAG, "exception" + e);

            }
        }
        if (byteArrayInputStream != null) {
            try {
                byteArrayInputStream.close();
            } catch (IOException e) {
                // Log.e(TAG, "exception" + e);

            }
        }

    }

    // ------------------ read the SERVER RESPONSE
    try {

        if (conn.getResponseCode() != 200) {
            isSuccess = false;
        }
    } catch (IOException e) {
        // Log.e(TAG, "Connection error", e);
        isSuccess = false;
    }

    return isSuccess;
}

From source file:edu.umn.cs.spatialHadoop.nasa.StockQuadTree.java

/**
 * Merges multiple trees of the same spatial resolution into one tree of
 * lower temporal resolution (larger time) and the same spatial resolution.
 * @param inTrees/*from   w  ww  .ja  v a  2s.com*/
 * @param outTree
 * @throws IOException 
 */
public static void merge(DataInputStream[] inTrees, DataOutputStream outTree) throws IOException {
    // Write the spatial resolution of the output as the same of all input trees
    int resolution = inTrees[0].readInt();
    short fillValue = inTrees[0].readShort();
    for (int iTree = 1; iTree < inTrees.length; iTree++) {
        int iResolution = inTrees[iTree].readInt();
        int iFillValue = inTrees[iTree].readShort();
        if (resolution != iResolution || fillValue != iFillValue)
            throw new RuntimeException("Tree #0 has a resolution of " + resolution
                    + " not compatible with resolution" + iResolution + " of Tree #" + iTree);
    }
    outTree.writeInt(resolution);
    outTree.writeShort(fillValue);

    // Sum up the cardinality of all input trees
    int cardinality = 0;
    int cardinalities[] = new int[inTrees.length];
    for (int iTree = 0; iTree < inTrees.length; iTree++)
        cardinality += (cardinalities[iTree] = inTrees[iTree].readInt());
    outTree.writeInt(cardinality);

    // Write timestamps of all trees
    for (int iTree = 0; iTree < inTrees.length; iTree++) {
        outTree.writeLong(inTrees[iTree].readLong());
    }

    // Merge sorted values in all input trees
    byte[] buffer = new byte[1024 * 1024];
    int size = resolution * resolution;
    while (size-- > 0) {
        for (int iTree = 0; iTree < inTrees.length; iTree++) {
            int sizeToRead = ValueSize * cardinalities[iTree]; // sizeof(short) * c
            while (sizeToRead > 0) {
                int bytesRead = inTrees[iTree].read(buffer, 0, Math.min(sizeToRead, buffer.length));
                outTree.write(buffer, 0, bytesRead);
                sizeToRead -= bytesRead;
            }
        }
    }

    // Merge aggregate values of all nodes
    Node treeNode = new Node();
    StockQuadTree stockQuadTree = getOrCreateStockQuadTree(resolution);
    int numOfNodes = stockQuadTree.nodesID.length;
    for (int iNode = 0; iNode < numOfNodes; iNode++) {
        Node outputNode = new Node();
        for (int iTree = 0; iTree < inTrees.length; iTree++) {
            treeNode.readFields(inTrees[iTree]);
            outputNode.accumulate(treeNode);
        }
        outputNode.write(outTree);
    }
}

From source file:com.curso.listadapter.net.RESTClient.java

public void writeFile(DataOutputStream dos, String NameParamImage, File file) {
    //BEGIN THE UPLOAD
    Log.d("Test", "(********) BEGINS THE WRITTING");
    if (file.exists()) {
        Log.d("Test", "(*****) FILE EXISTES");
    } else {/*w w w.j  ava2  s. c  o m*/
        Log.d("Test", "(*****) FILE DOES NOT EXIST");
    }
    try {
        FileInputStream fileInputStream;
        fileInputStream = new FileInputStream(file);
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        Log.e("Test", "(*****) fileInputStream.available():" + fileInputStream.available());
        post += "Content-Disposition: attachment; name=\"" + NameParamImage + "\"; filename=\"" + file.getName()
                + "\"" + lineEnd;
        String mimetype = getMimeType(file.getName());
        post += "Content-Type: " + mimetype + lineEnd;
        post += "Content-Transfer-Encoding: binary" + lineEnd + lineEnd;

        dos.writeBytes(post);

        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        while (bytesRead > 0) {
            dos.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }
        fileInputStream.close();
        post += lineEnd;
        post += twoHyphens + boundary + twoHyphens;
        Log.i("Test", "(********) WRITING FILE ENDED");
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    Log.d("Test", "(********) EXITING FROM FILE WRITTING");
}