Example usage for java.io DataOutputStream close

List of usage examples for java.io DataOutputStream close

Introduction

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

Prototype

@Override
public void close() throws IOException 

Source Link

Document

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

Usage

From source file:com.qcloud.PicCloud.java

/**
 * Download //from  ww w  . j  av a 2  s .  co  m
 * @param url           
 * @param fileName    ?
 * @return ?0?
 */
public int download(String url, String fileName) {
    JSONObject rspData = null;
    try {
        String rsp = mClient.get(url, null, null);
        File file = new File(fileName);
        DataOutputStream ops = new DataOutputStream(new FileOutputStream(file));
        ops.writeBytes(rsp);
        ops.close();
    } catch (Exception e) {
        return setError(-1, "url exception, e=" + e.toString());
    }

    return setError(0, "success");
}

From source file:com.kyne.webby.rtk.web.WebServer.java

public void printJSONObject(final JSONObject data, final Socket clientSocket) {
    try {//from  ww w. ja v  a  2  s. c o  m
        final DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
        out.writeBytes("HTTP/1.1 200 OK\r\n");
        out.writeBytes("Content-Type: application/json; charset=utf-8\r\n");
        out.writeBytes("Cache-Control: no-cache \r\n");
        out.writeBytes("Server: Bukkit Webby\r\n");
        out.writeBytes("Connection: Close\r\n\r\n");
        out.writeBytes(data.toJSONString());
        out.flush();
        out.close();
    } catch (final SocketException e) {
        /* .. */
    } catch (final Exception e) {
        LogHelper.error(e.getMessage(), e);
    }
}

From source file:org.bungeni.ext.integration.bungeniportal.BungeniAppConnector.java

public File getDownloadUrl(String sPage, boolean prefix) {

    String pageURL = (prefix ? this.urlBase + sPage : sPage);

    final HttpGet geturl = new HttpGet(pageURL);

    try {//from www. j av a2 s  . com
        String filenameRandom = RandomStringUtils.randomAlphanumeric(8);
        File fTempODT = TempFileManager.createTempFile(filenameRandom, ".odt");
        HttpResponse response = client.execute(geturl);
        int nStatusCode = response.getStatusLine().getStatusCode();
        HttpEntity entity = response.getEntity();
        if (entity != null && nStatusCode == 200) {
            InputStream istream = entity.getContent();
            DataOutputStream dos = new DataOutputStream(
                    new BufferedOutputStream(new FileOutputStream(fTempODT)));
            //FileWriter fw = new FileWriter(fTempODT);
            byte[] rawFiles = IOUtils.toByteArray(istream);
            dos.write(rawFiles);
            dos.close();
        }
        consumeContent(entity);
        return fTempODT;
    } catch (IOException ex) {
        log.error("Error while accessin url : " + pageURL, ex);

    }
    return null;
}

From source file:copter.ServerConnection.java

private String postToServer(String postUrl, Map<String, String> parameters) {
    String serverHost = Config.getInstance().getString("main", "server_host");
    URL url;/* w  w w.  ja v a2  s  .c om*/
    try {
        url = new URL("http://" + serverHost + postUrl);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();

        //add reuqest header
        con.setRequestMethod("POST");
        //con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        String urlParameters = "";
        for (Map.Entry<String, String> entry : parameters.entrySet()) {
            String paramName = entry.getKey();
            String paramValue = entry.getValue();
            String encodedParamValue = URLEncoder.encode(paramValue, "UTF-8");
            urlParameters += paramName + "=" + encodedParamValue + "&";
        }
        if (urlParameters.endsWith("&")) {
            urlParameters = urlParameters.substring(0, urlParameters.length() - 1);
        }
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        //logger.log("\nSending 'POST' request to URL : " + url);
        //logger.log("Post parameters : " + urlParameters);
        //logger.log("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        String serverResponse = response.toString();
        return serverResponse;
    } catch (Exception ex) {
        logger.log(ex.getMessage());
        return null;
    }
}

From source file:ReadWriteStreams.java

public void writeStream(String[] sData, boolean[] bData, int[] iData) {
    try {//w  w  w.  j  a  va 2s.c om
        // Write data into an internal byte array
        ByteArrayOutputStream strmBytes = new ByteArrayOutputStream();

        // Write Java data types into the above byte array
        DataOutputStream strmDataType = new DataOutputStream(strmBytes);

        byte[] record;

        for (int i = 0; i < sData.length; i++) {
            // Write Java data types      
            strmDataType.writeUTF(sData[i]);
            strmDataType.writeBoolean(bData[i]);
            strmDataType.writeInt(iData[i]);

            // Clear any buffered data
            strmDataType.flush();

            // Get stream data into byte array and write record
            record = strmBytes.toByteArray();
            rs.addRecord(record, 0, record.length);

            // Toss any data in the internal array so writes 
            // starts at beginning (of the internal array)
            strmBytes.reset();
        }

        strmBytes.close();
        strmDataType.close();

    } catch (Exception e) {
        db(e.toString());
    }
}

From source file:BugTrackerJFace.java

private void saveBugs(Vector v) {
    // Save bugs to a file.
    DataOutputStream out = null;
    try {//  w w  w  .  ja  v  a2s  .co m
        File file = new File("bugs.dat");

        out = new DataOutputStream(new FileOutputStream(file));

        for (int i = 0; i < v.size(); i++) {
            Bug bug = (Bug) v.elementAt(i);
            out.writeUTF(bug.id);
            out.writeUTF(bug.summary);
            out.writeUTF(bug.assignedTo);
            out.writeBoolean(bug.isSolved);
        }
    } catch (IOException ioe) {
        // Ignore.
    } finally {
        try {
            if (out != null)
                out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:io.v.positioning.gae.ServletPostAsyncTask.java

@Override
protected String doInBackground(Context... params) {
    mContext = params[0];//w  ww . j  ava  2  s . c om
    DataOutputStream os = null;
    InputStream is = null;
    try {
        URLConnection conn = mUrl.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.connect();
        os = new DataOutputStream(conn.getOutputStream());
        os.write(mData.toString().getBytes("UTF-8"));
        is = conn.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        return br.readLine();
    } catch (IOException e) {
        return "IOException while contacting GEA: " + e.getMessage();
    } catch (Exception e) {
        return "Exception while contacting GEA: " + e.getLocalizedMessage();
    } finally {
        if (os != null)
            try {
                os.close();
            } catch (IOException e) {
                return "IOException closing os: " + e.getMessage();
            }
        if (is != null)
            try {
                is.close();
            } catch (IOException e) {
                return "IOException closing is: " + e.getMessage();
            }
    }
}

From source file:ClipboardExample.java

public void javaToNative(Object object, TransferData transferData) {
    if (!checkMyType(object) || !isSupportedType(transferData)) {
        DND.error(DND.ERROR_INVALID_DATA);
    }/*from  w w  w  .  j av a  2 s .  co m*/
    MyType[] myTypes = (MyType[]) object;
    try {
        // write data to a byte array and then ask super to convert to
        // pMedium
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        DataOutputStream writeOut = new DataOutputStream(out);
        for (int i = 0, length = myTypes.length; i < length; i++) {
            byte[] buffer = myTypes[i].firstName.getBytes();
            writeOut.writeInt(buffer.length);
            writeOut.write(buffer);
            buffer = myTypes[i].firstName.getBytes();
            writeOut.writeInt(buffer.length);
            writeOut.write(buffer);
        }
        byte[] buffer = out.toByteArray();
        writeOut.close();
        super.javaToNative(buffer, transferData);
    } catch (IOException e) {
    }
}

From source file:edu.ku.brc.specify.tools.StrLocaleFile.java

/**
 * Save as Ascii./*from  w  ww . j  a v  a2 s  .c o  m*/
 */
public boolean save() {
    FileOutputStream fos = null;
    DataOutputStream dos = null;

    try {
        fos = new FileOutputStream(dstPath);
        dos = new DataOutputStream(fos);//, "UTF-8");

        for (StrLocaleEntry entry : items) {
            String str = "";
            if (entry.getKey() == null) {

            } else if (entry.getKey().equals("#")) {
                str = entry.getSrcStr();
            } else {
                str = entry.getKey() + "=" + (entry.getDstStr() == null ? "" : entry.getDstStr());
            }

            str += '\n';
            dos.writeBytes(str);
        }
        dos.flush();
        dos.close();
        return true;

    } catch (Exception e) {
        System.out.println("e: " + e);
    }
    return false;
}

From source file:net.larry1123.elec.util.logger.EELogger.java

/**
 * Will Log a StackTrace and Post it on to http://paste.larry1123.net/
 * Will return true if it was able to post and false if it was not able to post
 * Throws with the Level given// ww  w .j a  v  a  2 s  .  c om
 *
 * @param lvl     The Level to be thrown with
 * @param message Message to be Logged
 * @param thrown  Throwable Error To be logged
 *
 * @return {@code true} if paste was made of stackTrace; {@code falase} if it failed for any reason
 */
public boolean logStackTraceToPasteBin(Level lvl, String message, Throwable thrown) {
    if (getConfig().isPastingAllowed()) {
        EELogger eeLogger = FactoryManager.getFactoryManager().getEELoggerFactory().getSubLogger("EEUtil",
                "PasteBinLog");
        try {
            URL url = new URL("https://paste.larry1123.net/api/xml/create");
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("User-Agent", "Mozilla/5.0");
            con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

            String urlParameters = "data=" + "[" + lvl.getName() + "] " + message + "\n"
                    + org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace(thrown);
            urlParameters += "&";
            String title = "[" + lvl.getName() + "] " + message;
            urlParameters += "title=" + (title.length() > 30 ? title.substring(0, 30) : title);
            urlParameters += "&";
            urlParameters += "language=Java";

            // Send post request
            con.setDoOutput(true);
            DataOutputStream wr = new DataOutputStream(con.getOutputStream());
            wr.writeBytes(urlParameters);
            wr.flush();
            wr.close();

            if (con.getResponseCode() == 200) {
                DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                Document document = dBuilder.parse(con.getInputStream());
                document.getDocumentElement().normalize();

                NodeList nodeList = document.getElementsByTagName("id");
                Node node = nodeList.item(0);
                String id = node.getTextContent();
                eeLogger.info("Logger " + getName() + ": https://paste.larry1123.net/" + id);
                return true;
            }
            return false;
        } catch (MalformedURLException e) {
            eeLogger.error("Failed to send: Malformed", e);
            return false;
        } catch (IOException e) {
            eeLogger.error("Failed to send: IOException", e);
            return false;
        } catch (ParserConfigurationException e) {
            eeLogger.error("Failed to send: ParserConfigurationException", e);
            return false;
        } catch (SAXException e) {
            eeLogger.error("Failed to send: SAXException", e);
            return false;
        }
    } else {
        return false;
    }
}