Example usage for java.io DataInputStream close

List of usage examples for java.io DataInputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this input stream and releases any system resources associated with the stream.

Usage

From source file:com.mingsoft.weixin.util.UploadDownUtils.java

/**
 * ? ? //from  ww w .  ja  v a2  s  . co  m
 * @param access_token ??
 * @param msgType image?voice?videothumb
 * @param localFile 
 * @return
 */
@Deprecated
public static String uploadMedia(String access_token, String msgType, String localFile) {
    String media_id = null;
    String url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=" + access_token + "&type="
            + msgType;
    String local_url = localFile;
    try {
        File file = new File(local_url);
        if (!file.exists() || !file.isFile()) {
            log.error("==" + local_url);
            return null;
        }
        URL urlObj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
        con.setRequestMethod("POST"); // Post????get?
        con.setDoInput(true);
        con.setDoOutput(true);
        con.setUseCaches(false); // post??
        // ?
        con.setRequestProperty("Connection", "Keep-Alive");
        con.setRequestProperty("Charset", "UTF-8");

        // 
        String BOUNDARY = "----------" + System.currentTimeMillis();
        con.setRequestProperty("content-type", "multipart/form-data; boundary=" + BOUNDARY);
        // con.setRequestProperty("Content-Type",
        // "multipart/mixed; boundary=" + BOUNDARY);
        // con.setRequestProperty("content-type", "text/html");
        // ?

        // 
        StringBuilder sb = new StringBuilder();
        sb.append("--"); // ////////?
        sb.append(BOUNDARY);
        sb.append("\r\n");
        sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + file.getName() + "\"\r\n");
        sb.append("Content-Type:application/octet-stream\r\n\r\n");
        byte[] head = sb.toString().getBytes("utf-8");
        // ?
        OutputStream out = new DataOutputStream(con.getOutputStream());
        out.write(head);

        // 
        DataInputStream in = new DataInputStream(new FileInputStream(file));
        int bytes = 0;
        byte[] bufferOut = new byte[1024];
        while ((bytes = in.read(bufferOut)) != -1) {
            out.write(bufferOut, 0, bytes);
        }
        in.close();
        // 
        byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// ??
        out.write(foot);
        out.flush();
        out.close();
        /**
         * ????,?????
         */
        // con.getResponseCode();
        try {
            // BufferedReader???URL?
            StringBuffer buffer = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
            String line = null;
            while ((line = reader.readLine()) != null) {
                // System.out.println(line);
                buffer.append(line);
            }
            String respStr = buffer.toString();
            log.debug("==respStr==" + respStr);
            try {
                JSONObject dataJson = JSONObject.parseObject(respStr);

                media_id = dataJson.getString("media_id");
            } catch (Exception e) {
                log.error("==respStr==" + respStr, e);
                try {
                    JSONObject dataJson = JSONObject.parseObject(respStr);
                    return dataJson.getString("errcode");
                } catch (Exception e1) {
                }
            }
        } catch (Exception e) {
            log.error("??POST?" + e);
        }
    } catch (Exception e) {
        log.error("?!=" + local_url);
        log.error("?!", e);
    } finally {
    }
    return media_id;
}

From source file:com.headwire.aem.tooling.intellij.util.Util.java

public static long getModificationStamp(VirtualFile file) {
    long ret = -1;
    Long temporary = file.getUserData(Util.MODIFICATION_DATE_KEY);
    if (temporary == null || temporary <= 0) {
        if (file instanceof NewVirtualFile) {
            final DataInputStream is = MODIFICATION_STAMP_FILE_ATTRIBUTE.readAttribute(file);
            if (is != null) {
                try {
                    try {
                        if (is.available() > 0) {
                            String value = IOUtil.readString(is);
                            ret = convertToLong(value, ret);
                            if (ret > 0) {
                                file.putUserData(Util.MODIFICATION_DATE_KEY, ret);
                            }//from   w w  w  .j  a v a  2  s  .c o  m
                        }
                    } finally {
                        is.close();
                    }
                } catch (IOException e) {
                    // Ignore it but we might need to throw an exception
                    String message = e.getMessage();
                }
            }
        }
    }
    return ret;
}

From source file:edu.gmu.csiss.automation.pacs.utils.BaseTool.java

/**
 * Read the string from a file/*from  www  .  j a  va2  s .c om*/
 * @param path
 * @return
 */
public static String readStringFromFile(String path) {
    StringBuffer strLine = new StringBuffer();
    try {
        // Open the file that is the first 
        // command line parameter
        FileInputStream fstream = new FileInputStream(path);
        // Get the object of DataInputStream
        DataInputStream in = new DataInputStream(fstream);
        FileReader fr = new FileReader(path);
        BufferedReader br = new BufferedReader(fr);
        String str = null;
        //Read File Line By Line
        while ((str = br.readLine()) != null) {
            // Print the content on the console
            strLine.append(str).append("\n");
            //              System.out.println (strLine);
        }
        //Close the input stream
        in.close();
    } catch (Exception e) {//Catch exception if any
        System.err.println("Error: " + e.getMessage());
    }
    return strLine.toString().trim();
}

From source file:Messenger.TorLib.java

/**
 * This method opens a TOR socket, and does an anonymous DNS resolve through it.
 * Since Tor caches things, this is a very fast lookup if we've already connected there
 * The resolve does a gethostbyname() on the exit node.
 * @param targetHostname String containing the hostname to look up.
 * @return String representation of the IP address: "x.x.x.x"
 *//*from w w  w .j  a v  a  2 s . c o m*/
static String TorResolve(String targetHostname) {
    int targetPort = 0; // we dont need a port to resolve

    try {
        Socket s = TorSocketPre(targetHostname, targetPort, TOR_RESOLVE);
        DataInputStream is = new DataInputStream(s.getInputStream());

        byte version = is.readByte();
        byte status = is.readByte();
        if (status != (byte) 90) {
            //failed for some reason, return useful exception
            throw (new IOException(ParseSOCKSStatus(status)));
        }
        int port = is.readShort();
        byte[] ipAddrBytes = new byte[4];
        is.read(ipAddrBytes);
        InetAddress ia = InetAddress.getByAddress(ipAddrBytes);
        //System.out.println("Resolved into:"+ia);
        is.close();
        String addr = ia.toString().substring(1); // clip off the "/"
        return (addr);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return (null);
}

From source file:org.apache.flink.statistics.StatisticsRequest.java

public static StatisticsRequest readBytes(byte[] statReqBytes) {
    StatisticsRequest sr = new StatisticsRequest();

    ByteArrayInputStream bis = new ByteArrayInputStream(statReqBytes);
    DataInputStream dis = new DataInputStream(bis);
    DataInputView inputView = new InputViewDataInputStreamWrapper(dis);
    try {/*from   www . ja  va  2s.c  o  m*/

        sr.inputStats = readArray(inputView);
        sr.outputStats = readArray(inputView);

        for (int numEntries = inputView.readInt(); numEntries > 0; --numEntries)
            sr.specialStats.add(inputView.readUTF());

        dis.close();
    } catch (IOException ioe) {
        LOG.error("Deserialisation error: " + StringUtils.stringifyException(ioe));
        return null;
    }

    return sr;
}

From source file:Main.java

/**
 * The URL looks like a request for a resource, such as a JavaScript or CSS file. Write
 * the given resource to the response output in binary format (needed for images).
 *//*from   ww w. j  av a  2  s.co m*/
public static void readWriteBinaryUtil(String sxURL, String resource, OutputStream outStream)
        throws IOException {

    DataOutputStream outData = null;
    DataInputStream inData = null;
    int byteCnt = 0;
    byte[] buffer = new byte[4096];

    // get full qualified path of class
    System.out.println("RW Base Directory - " + sxURL);

    // remove class and add resource relative path
    sxURL = getResourceURL(sxURL, resource);

    System.out.println("RW Loading - " + sxURL);
    try {
        outData = new DataOutputStream(outStream);
        inData = new DataInputStream(new URL(sxURL).openConnection().getInputStream());

        while ((byteCnt = inData.read(buffer)) != -1) {
            if (outData != null && byteCnt > 0) {
                outData.write(buffer, 0, byteCnt);
            }
        }
    } catch (IOException e) {
        throw e;
    } finally {
        try {
            if (inData != null) {
                inData.close();
            }
        } catch (IOException ioe) {
        }
    }
}

From source file:org.cloudata.core.common.io.CObjectWritable.java

private static Object readColumnValue(DataInput in, CloudataConf conf, Class<?> declaredClass, int length)
        throws IOException {
    long startTime = System.currentTimeMillis();

    int totalByteSize = in.readInt();
    byte[] buf = new byte[totalByteSize];
    in.readFully(buf);//from   w w w .ja  v a  2  s  . co m
    long endTime = System.currentTimeMillis();
    //LOG.fatal("readColumnValue1:length=" + length + ",bytes=" + totalByteSize + ",time=" + (endTime - startTime));

    DataInputStream byteDataIn = new DataInputStream(new ByteArrayInputStream(buf));

    ColumnValue[] instance = (ColumnValue[]) Array.newInstance(declaredClass.getComponentType(), length);
    //startTime = System.currentTimeMillis();
    Class componentClass = declaredClass.getComponentType();
    for (int i = 0; i < length; i++) {
        //Array.set(instance, i, readObject(byteDataIn, null, conf, true, declaredClass.getComponentType()));
        instance[i] = (ColumnValue) readObject(byteDataIn, null, conf, true, componentClass);
    }
    byteDataIn.close();
    byteDataIn = null;
    buf = null;
    //endTime = System.currentTimeMillis();
    //LOG.fatal("readColumnValue2:time=" + (endTime - startTime));
    return instance;
}

From source file:Main.java

public static float[] readBinAverageShapeArray(String dir, String fileName, int size) {
    float x;/*from   w  ww  .ja va2 s  .co m*/
    int i = 0;
    float[] tab = new float[size];

    // theses values was for 64140 points average shape
    //float minX = -90.3540f, minY = -22.1150f, minZ = -88.7720f, maxX = 101.3830f, maxY = 105.1860f, maxZ = 102.0530f;

    // values for average shape after simplification (8489 points)
    float maxX = 95.4549f, minX = -85.4616f, maxY = 115.0088f, minY = -18.0376f, maxZ = 106.7329f,
            minZ = -90.4051f;

    float deltaX = (maxX - minX) / 2.0f;
    float deltaY = (maxY - minY) / 2.0f;
    float deltaZ = (maxZ - minZ) / 2.0f;

    float midX = (maxX + minX) / 2.0f;
    float midY = (maxY + minY) / 2.0f;
    float midZ = (maxZ + minZ) / 2.0f;

    File sdLien = Environment.getExternalStorageDirectory();
    File inFile = new File(sdLien + File.separator + dir + File.separator + fileName);
    Log.d(TAG, "path of file : " + inFile);
    if (!inFile.exists()) {
        throw new RuntimeException("File doesn't exist");
    }
    DataInputStream in = null;
    try {
        in = new DataInputStream(new FileInputStream(inFile));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    try {
        //read first x
        x = in.readFloat();
        //Log.d(TAG,"first Vertices = "+x);
        while (true) {

            tab[i] = (x - midX) / deltaX; //rescale x
            i++;

            //read y
            x = in.readFloat();
            tab[i] = (x - midY) / deltaY; //rescale y
            i++;

            //read z
            x = in.readFloat();
            tab[i] = (x - midZ) / deltaZ; //rescale z
            i++;

            //read x
            x = in.readFloat();
        }
    } catch (EOFException e) {
        try {
            Log.d(TAG, "close");
            in.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (in != null) {
            try { //free ressources
                Log.d(TAG, "close");
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return tab;
}

From source file:com.tactfactory.harmony.utils.TactFileUtils.java

/** convert file content to a string.
 *
 * @param file The file to open/*from w  w w  .  j a v a 2 s. c o  m*/
 * @return the String containing the file contents
 */
public static String fileToString(final File file) {
    String result = null;
    DataInputStream inStream = null;

    try {
        final byte[] buffer = new byte[(int) file.length()];
        inStream = new DataInputStream(new FileInputStream(file));
        inStream.readFully(buffer);
        result = new String(buffer, TactFileUtils.DEFAULT_ENCODING);
    } catch (final IOException e) {
        throw new RuntimeException("IO problem in fileToString", e);
    } finally {
        try {
            if (inStream != null) {
                inStream.close();
            }
        } catch (final IOException e) {
            ConsoleUtils.displayError(e);
        }
    }
    return result;
}

From source file:Util.PacketGenerator.java

public static void GenerateTopology() {
    try {/*from  ww w .  ja  v  a 2  s.  c om*/
        File file = new File("D:\\Mestrado\\Prototipo\\topologydata\\AS1239\\CONVERTED.POP.1239");
        File newFile = new File("D:\\Mestrado\\SketchMatrix\\trunk\\AS1239_TOPOLOGY");

        FileInputStream topologyFIS = new FileInputStream(file);
        DataInputStream topologyDIS = new DataInputStream(topologyFIS);
        BufferedReader topologyBR = new BufferedReader(new InputStreamReader(topologyDIS));

        String topologyStr = topologyBR.readLine();

        int numberOfEdges = 0;
        Set<Integer> nodes = new HashSet<>();

        while (topologyStr != null) {

            String[] edge = topologyStr.split(" ");

            nodes.add(Integer.parseInt(edge[0]));
            nodes.add(Integer.parseInt(edge[1]));
            numberOfEdges++;

            topologyStr = topologyBR.readLine();

        }
        topologyBR.close();
        topologyDIS.close();
        topologyFIS.close();

        topologyFIS = new FileInputStream(file);
        topologyDIS = new DataInputStream(topologyFIS);
        topologyBR = new BufferedReader(new InputStreamReader(topologyDIS));
        FileWriter topologyFW = new FileWriter(newFile);

        topologyStr = topologyBR.readLine();

        topologyFW.write(nodes.size() + " " + numberOfEdges + "\n");

        while (topologyStr != null) {

            String[] edge = topologyStr.split(" ");

            nodes.add(Integer.parseInt(edge[0]));
            nodes.add(Integer.parseInt(edge[1]));
            nodes.add(Integer.parseInt(edge[1]));

            topologyFW.write(Integer.parseInt(edge[0]) + " " + Integer.parseInt(edge[1]) + " 1\n");

            topologyStr = topologyBR.readLine();

        }

        topologyBR.close();
        topologyDIS.close();
        topologyFIS.close();
        topologyFW.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}