Example usage for java.io DataInputStream read

List of usage examples for java.io DataInputStream read

Introduction

In this page you can find the example usage for java.io DataInputStream read.

Prototype

public final int read(byte b[]) throws IOException 

Source Link

Document

Reads some number of bytes from the contained input stream and stores them into the buffer array b.

Usage

From source file:com.asto.move.util.qcloud.pic.PicCloud.java

public int Upload(String fileName, String fileid, PicAnalyze flag, UploadResult result) {
    if ("".equals(fileName)) {
        return SetError(-1, "invalid file name");
    }/*from w  ww . ja  v a  2 s .  co m*/

    String req_url = GetUrl(fileid);
    String BOUNDARY = "---------------------------abcdefg1234567";
    String rsp = "";

    //check analyze flag
    String query_string = "";
    if (flag.fuzzy != 0) {
        query_string += ".fuzzy";
    }
    if (flag.food != 0) {
        query_string += ".food";
    }
    if ("".equals(query_string) == false) {
        req_url += "?analyze=" + query_string.substring(1);
    }

    //        System.out.println("url=" + req_url);
    // create sign
    long expired = System.currentTimeMillis() / 1000 + 600;
    String sign = FileCloudSign.appSignV2(m_appid, m_secret_id, m_secret_key, m_bucket, expired);
    if (null == sign) {
        return SetError(-1, "create app sign failed");
    }
    //        System.out.println("sign=" + sign);

    try {
        URL realUrl = new URL(req_url);
        HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
        // set header
        connection.setRequestMethod("POST");
        connection.setRequestProperty("accept", "*/*");
        connection.setRequestProperty("Host", "web.image.myqcloud.com");
        connection.setRequestProperty("user-agent", "qcloud-java-sdk");
        connection.setRequestProperty("Authorization", sign);

        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

        OutputStream out = new DataOutputStream(connection.getOutputStream());
        StringBuilder strBuf = new StringBuilder();

        if (fileName != null) {
            File file = new File(fileName);
            String filename = file.getName();
            String contentType = URLConnection.getFileNameMap().getContentTypeFor(fileName);

            strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
            strBuf.append("Content-Disposition: form-data; name=\"FileContent\"; filename=\"").append(fileName)
                    .append("\"\r\n");
            strBuf.append("Content-Type:").append(contentType).append("\r\n\r\n");

            out.write(strBuf.toString().getBytes());

            DataInputStream ins = new DataInputStream(new FileInputStream(file));
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = ins.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
        }

        byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
        out.write(endData);
        out.flush();
        out.close();

        connection.connect();
        rsp = GetResponse(connection);
    } catch (Exception e) {
        return SetError(-1, "url exception, e=" + e.toString());
    }
    System.out.println("rsp=" + rsp);
    try {
        JSONObject jsonObject = new JSONObject(rsp);
        int code = jsonObject.getInt("code");
        String msg = jsonObject.getString("message");
        if (0 != code) {
            return SetError(code, msg);
        }

        result.url = jsonObject.getJSONObject("data").getString("url");
        result.download_url = jsonObject.getJSONObject("data").getString("download_url");
        result.fileid = jsonObject.getJSONObject("data").getString("fileid");

        if (jsonObject.getJSONObject("data").has("is_fuzzy")) {
            result.analyze.fuzzy = jsonObject.getJSONObject("data").getInt("is_fuzzy");
        }
        if (jsonObject.getJSONObject("data").has("is_food")) {
            result.analyze.food = jsonObject.getJSONObject("data").getInt("is_food");
        }

    } catch (JSONException e) {
        return SetError(-1, "json exception, e=" + e.toString());
    }
    return SetError(0, "success");
}

From source file:cn.org.eshow.framwork.util.AbFileUtil.java

/**
 * ??byte[]./*from w  w w.ja v  a  2  s  . c  o m*/
 * @param imgByte byte[]
 * @param fileName ?????.jpg
 * @param type ???AbConstant
 * @param desiredWidth 
 * @param desiredHeight 
 * @return Bitmap 
 */
public static Bitmap getBitmapFromByte(byte[] imgByte, String fileName, int type, int desiredWidth,
        int desiredHeight) {
    FileOutputStream fos = null;
    DataInputStream dis = null;
    ByteArrayInputStream bis = null;
    Bitmap bitmap = null;
    File file = null;
    try {
        if (imgByte != null) {

            file = new File(imageDownloadDir + fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
            fos = new FileOutputStream(file);
            int readLength = 0;
            bis = new ByteArrayInputStream(imgByte);
            dis = new DataInputStream(bis);
            byte[] buffer = new byte[1024];

            while ((readLength = dis.read(buffer)) != -1) {
                fos.write(buffer, 0, readLength);
                try {
                    Thread.sleep(500);
                } catch (Exception e) {
                }
            }
            fos.flush();

            bitmap = getBitmapFromSD(file, type, desiredWidth, desiredHeight);
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (dis != null) {
            try {
                dis.close();
            } catch (Exception e) {
            }
        }
        if (bis != null) {
            try {
                bis.close();
            } catch (Exception e) {
            }
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (Exception e) {
            }
        }
    }
    return bitmap;
}

From source file:org.apache.hadoop.hive.ql.io.TestRCFile.java

public void testRCFileHeader(char[] expected, Configuration conf) throws IOException, SerDeException {
    writeTest(fs, 10000, file, bytesArray, conf);
    DataInputStream di = fs.open(file, 10000);
    byte[] bytes = new byte[3];
    di.read(bytes);
    for (int i = 0; i < expected.length; i++) {
        assertTrue("Headers did not match", bytes[i] == expected[i]);
    }//  ww  w . ja va2 s .c  o  m
    di.close();
}

From source file:com.asto.move.util.qcloud.pic.VideoCloud.java

/**
 * Upload ?SliceUpload/*from w ww .  j  a v  a 2 s  . co  m*/
 * @param userid      ?,0
 * @param fileName      ??
 * @param title         
 * @param desc          ??
 * @param magicContext   ????url
 * @param result      ?
 * @return ?0?
 */
public int Upload(String userid, String fileName, String title, String desc, String magicContext,
        UploadResult result) {
    String req_url = "http://" + QCLOUD_DOMAIN + "/" + m_appid + "/" + userid;
    String BOUNDARY = "---------------------------abcdefg1234567";
    String rsp = "";

    // create sign
    long expired = System.currentTimeMillis() / 1000 + 2592000;
    String sign = FileCloudSign.appSign(m_appid, m_secret_id, m_secret_key, expired);
    if (null == sign) {
        return SetError(-1, "create app sign failed");
    }
    System.out.println("sign=" + sign);

    try {
        URL realUrl = new URL(req_url);
        HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
        // set header
        connection.setRequestMethod("POST");
        connection.setRequestProperty("accept", "*/*");
        connection.setRequestProperty("Host", "web.video.myqcloud.com");
        connection.setRequestProperty("user-agent", "qcloud-java-sdk");
        connection.setRequestProperty("Authorization", sign);

        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

        OutputStream out = new DataOutputStream(connection.getOutputStream());
        StringBuilder strBuf = new StringBuilder();

        if (fileName != null) {
            File file = new File(fileName);
            String filename = file.getName();
            String contentType = URLConnection.getFileNameMap().getContentTypeFor(fileName);

            strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
            strBuf.append("Content-Disposition: form-data; name=\"FileContent\"; filename=\"").append(fileName)
                    .append("\"\r\n");
            strBuf.append("Content-Type:").append(contentType).append("\r\n\r\n");

            out.write(strBuf.toString().getBytes());

            DataInputStream ins = new DataInputStream(new FileInputStream(file));
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = ins.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
        }

        byte[] endData = ("\r\n--" + BOUNDARY + "\r\n").getBytes();
        out.write(endData);
        byte[] arrTitle = ("Content-Disposition: form-data; name=\"Title\";\r\n\r\n" + title + "\r\n--"
                + BOUNDARY + "\r\n").getBytes();
        out.write(arrTitle);
        byte[] arrDesc = ("Content-Disposition: form-data; name=\"Desc\";\r\n\r\n" + desc + "\r\n--" + BOUNDARY
                + "\r\n").getBytes();
        out.write(arrDesc);
        byte[] arrMagicContext = ("Content-Disposition: form-data; name=\"magiccontext\";\r\n\r\n"
                + magicContext + "\r\n--" + BOUNDARY + "--\r\n").getBytes();
        out.write(arrMagicContext);

        out.flush();
        out.close();

        connection.connect();
        rsp = GetResponse(connection);
    } catch (Exception e) {
        return SetError(-1, "url exception, e=" + e.toString());
    }

    try {
        JSONObject jsonObject = new JSONObject(rsp);
        int code = jsonObject.getInt("code");
        String msg = jsonObject.getString("message");
        if (0 != code) {
            return SetError(code, msg);
        }

        result.url = jsonObject.getJSONObject("data").getString("url");
        result.download_url = jsonObject.getJSONObject("data").getString("download_url");
        result.fileid = jsonObject.getJSONObject("data").getString("fileid");
        if (jsonObject.getJSONObject("data").has("cover_url"))
            result.cover_url = jsonObject.getJSONObject("data").getString("cover_url");
    } catch (JSONException e) {
        return SetError(-1, "json exception, e=" + e.toString());
    }
    return SetError(0, "success");
}

From source file:org.apache.wookie.WidgetAdminServlet.java

private void doDownload(HttpServletRequest req, HttpServletResponse resp, File f, String original_filename)
        throws IOException {
    int BUFSIZE = 1024;

    // File f = new File(filename);
    int length = 0;
    ServletOutputStream op = resp.getOutputStream();
    ServletContext context = getServletConfig().getServletContext();
    String mimetype = context.getMimeType(f.getAbsolutePath());

    ////  ww  w . jav a2s .com
    // Set the response and go!
    //
    //
    resp.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
    resp.setContentLength((int) f.length());
    resp.setHeader("Content-Disposition", "attachment; filename=\"" + original_filename + "\"");

    //
    // Stream to the requester.
    //
    byte[] bbuf = new byte[BUFSIZE];
    DataInputStream in = new DataInputStream(new FileInputStream(f));

    while ((in != null) && ((length = in.read(bbuf)) != -1)) {
        op.write(bbuf, 0, length);
    }

    in.close();
    op.flush();
    op.close();
}

From source file:org.kawanfw.commons.util.Sha1Util.java

/**
 * Gets the a file hash value.//from   w  w  w  .j a v a2  s.  c o m
 * 
 * @param file the file to hash
 *            
 * @return the file hash as bytes
 * 
 * @exception IOException
 *                an I/O error occurred
 * @exception NoSuchAlgorithmException
 *                hash algorithm not found
 * @exception NoSuchProviderException
 *                hash provider not found
 */

public byte[] getFileHash(File file) throws IOException, NoSuchAlgorithmException, NoSuchProviderException {

    FileInputStream fisIn = new FileInputStream(file);
    BufferedInputStream bisIn = new BufferedInputStream(fisIn);

    DataInputStream disIn = null;

    try {
        disIn = new DataInputStream(bisIn);

        // Bytes containing the MD5 or SHA-1 Hash Code
        byte[] bytesHash = new byte[160];

        MessageDigest mdInstance = MessageDigest.getInstance("SHA-1");

        int bytesRead;
        int total = disIn.available();

        if (total == 0) {
            return null;
        }

        if (total > READ_BUFFER_SIZE) {
            total = READ_BUFFER_SIZE;
        }

        byte bRead[] = new byte[total];

        while ((bytesRead = disIn.read(bRead)) > 0) {
            mdInstance.update(bRead, 0, bytesRead);
        }

        bytesHash = mdInstance.digest();

        return bytesHash;
    } finally {
        IOUtils.closeQuietly(disIn);
    }

}

From source file:org.onesocialweb.openfire.web.FileServlet.java

private void processGet(HttpServletRequest request, HttpServletResponse response)
        throws MissingParameterException, IOException, InvalidParameterValueException {

    // Validate the request token
    // TODO/*from   w  ww .j av a  2  s.  c  o  m*/

    // Process the parameters
    String fileId = request.getParameter("fileId");
    if (fileId == null || fileId.isEmpty()) {
        throw new MissingParameterException("fileId");
    }

    // Get the file entry
    FileEntry fileEntry = UploadManager.getInstance().getFile(fileId);
    if (fileEntry == null) {
        throw new FileNotFoundException(fileId);
    }

    // Open the file
    File file = new File(getUploadFolder(), fileEntry.getId());
    if (!file.exists()) {
        throw new FileNotFoundException(fileEntry.getName());
    }

    // Process the file
    String pSize = request.getParameter("size");
    if (pSize != null) {
    }

    DataInputStream is = new DataInputStream(new FileInputStream(file));

    // Send the headers
    response.setContentType(fileEntry.getType());
    response.setContentLength((int) fileEntry.getSize());
    //response.setHeader("Content-Disposition", "attachment; filename=\"" + fileEntry.getName() + "\"");

    // Stream the file
    final byte[] bbuf = new byte[BUFFSIZE];
    final OutputStream os = response.getOutputStream();

    int length = 0;
    while ((is != null) && ((length = is.read(bbuf)) != -1)) {
        os.write(bbuf, 0, length);
    }

    is.close();
    os.flush();
    os.close();
}

From source file:org.apache.hadoop.hdfs.tools.offlineImageViewer.TestOfflineImageViewer.java

private void changeLayoutVersion(File src, File dest, int newVersion) throws IOException {
    DataInputStream in = null;
    DataOutputStream out = null;/*from www  .  j  a  v a2 s .  c om*/

    try {
        in = new DataInputStream(new FileInputStream(src));
        out = new DataOutputStream(new FileOutputStream(dest));

        in.readInt();
        out.writeInt(newVersion);

        byte[] b = new byte[1024];
        while (in.read(b) > 0) {
            out.write(b);
        }
    } finally {
        if (in != null)
            in.close();
        if (out != null)
            out.close();
    }
}

From source file:com.asto.move.util.qcloud.pic.VideoCloud.java

/**
 * SliceUpload 20M/*w  w w. j a v a  2  s.c  om*/
 * @param userid      ?,0
 * @param fileName      ??
 * @param title         
 * @param desc         ??
 * @param magicContext   ????url
 * @param result      ?
 * @return             ?0?
 */
public int SliceUpload(String userid, String fileName, String title, String desc, String magicContext,
        UploadResult result) {
    String req_url = "http://" + QCLOUD_DOMAIN + "/" + m_appid + "/" + userid;
    String BOUNDARY = "---------------------------abcdefg1234567";
    String rsp = "";
    long fileSize = 0;
    File file;
    if (fileName != null) {
        file = new File(fileName);
        if (file.exists() && file.isFile()) {
            fileSize = file.length();
        } else {
            SetError(-2, "file doesn't exist or is not a file");
        }
    } else {
        SetError(-2, "file doesn't exist or is not a file");
    }

    // create sign
    long expired = System.currentTimeMillis() / 1000 + 2592000;
    String sign = FileCloudSign.appSign(m_appid, m_secret_id, m_secret_key, expired);
    if (null == sign) {
        return SetError(-1, "create app sign failed");
    }
    System.out.println("sign=" + sign);

    try {
        URL realUrl = new URL(req_url);
        HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
        // set header
        connection.setRequestMethod("POST");
        connection.setRequestProperty("accept", "*/*");
        connection.setRequestProperty("Host", "web.video.myqcloud.com");
        connection.setRequestProperty("user-agent", "qcloud-java-sdk");
        connection.setRequestProperty("Authorization", sign);

        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

        OutputStream out = new DataOutputStream(connection.getOutputStream());

        byte[] arrOp = ("\r\n--" + BOUNDARY + "\r\n"
                + "Content-Disposition: form-data; name=\"op\";\r\n\r\nupload_slice" + "\r\n--" + BOUNDARY
                + "\r\n").getBytes();
        out.write(arrOp);
        byte[] arrFilesize = ("Content-Disposition: form-data; name=\"filesize\";\r\n\r\n" + fileSize + "\r\n--"
                + BOUNDARY + "\r\n").getBytes();
        out.write(arrFilesize);
        byte[] arrTitle = ("Content-Disposition: form-data; name=\"Title\";\r\n\r\n" + title + "\r\n--"
                + BOUNDARY + "\r\n").getBytes();
        out.write(arrTitle);
        byte[] arrDesc = ("Content-Disposition: form-data; name=\"Desc\";\r\n\r\n" + desc + "\r\n--" + BOUNDARY
                + "\r\n").getBytes();
        out.write(arrDesc);
        byte[] arrMagicContext = ("Content-Disposition: form-data; name=\"magiccontext\";\r\n\r\n"
                + magicContext + "\r\n--" + BOUNDARY + "--\r\n").getBytes();
        out.write(arrMagicContext);

        out.flush();
        out.close();

        connection.connect();
        rsp = GetResponse(connection);
    } catch (Exception e) {
        return SetError(-1, "url exception, e=" + e.toString());
    }

    try {

        JSONObject jsonObject = new JSONObject(rsp);
        int code = jsonObject.getInt("code");
        String msg = jsonObject.getString("message");
        if (0 != code) {
            return SetError(code, msg);
        }

        if (jsonObject.getJSONObject("data").has("url"))
            result.url = jsonObject.getJSONObject("data").getString("url");
        if (jsonObject.getJSONObject("data").has("download_url"))
            result.download_url = jsonObject.getJSONObject("data").getString("download_url");
        if (jsonObject.getJSONObject("data").has("fileid"))
            result.fileid = jsonObject.getJSONObject("data").getString("fileid");
        if (jsonObject.getJSONObject("data").has("cover_url"))
            result.cover_url = jsonObject.getJSONObject("data").getString("cover_url");

        if (result.url.length() <= 0 || result.download_url.length() <= 0 || result.fileid.length() <= 0) {
            String session = jsonObject.getJSONObject("data").getString("session");
            int offset = jsonObject.getJSONObject("data").getInt("offset");
            int sliceSize = jsonObject.getJSONObject("data").getInt("slice_size");
            File upload_file = new File(fileName);
            DataInputStream ins = new DataInputStream(new FileInputStream(upload_file));
            int bytes = 0;
            byte[] bufferOut = new byte[sliceSize];
            while ((bytes = ins.read(bufferOut)) != -1) {
                int ret = UploadData(userid, bufferOut, bytes, session, offset, result);
                if (ret != 1) {
                    return ret;
                }
                offset += bytes;
            }
        } else {
            return SetError(0, "success");
        }
    } catch (JSONException e) {
        return SetError(-1, "json exception, e=" + e.toString());
    } catch (Exception e) {
        return SetError(-1, "url exception, e=" + e.toString());
    }
    return SetError(0, "success");
}

From source file:ClipboardExample.java

public Object nativeToJava(TransferData transferData) {
    if (isSupportedType(transferData)) {

        byte[] buffer = (byte[]) super.nativeToJava(transferData);
        if (buffer == null)
            return null;

        MyType[] myData = new MyType[0];
        try {//w  w  w  . ja  va 2s  .c o m
            ByteArrayInputStream in = new ByteArrayInputStream(buffer);
            DataInputStream readIn = new DataInputStream(in);
            while (readIn.available() > 20) {
                MyType datum = new MyType();
                int size = readIn.readInt();
                byte[] name = new byte[size];
                readIn.read(name);
                datum.firstName = new String(name);
                size = readIn.readInt();
                name = new byte[size];
                readIn.read(name);
                datum.lastName = new String(name);
                MyType[] newMyData = new MyType[myData.length + 1];
                System.arraycopy(myData, 0, newMyData, 0, myData.length);
                newMyData[myData.length] = datum;
                myData = newMyData;
            }
            readIn.close();
        } catch (IOException ex) {
            return null;
        }
        return myData;
    }

    return null;
}