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:at.illecker.hama.hybrid.examples.summation.SummationBSP.java

static BigDecimal writeSummationInputFile(FileSystem fs, Path dir, int fileCount) throws IOException {

    BigDecimal sum = new BigDecimal(0);
    Random rand = new Random();
    double rangeMin = 0;
    double rangeMax = 100;

    for (int i = 0; i < fileCount; i++) {
        DataOutputStream out = fs.create(new Path(dir, "part" + i));

        // loop between 50 and 149 times
        for (int j = 0; j < rand.nextInt(100) + 50; j++) {
            // generate key value pair inputs
            double randomValue = rangeMin + (rangeMax - rangeMin) * rand.nextDouble();

            String truncatedValue = new BigDecimal(randomValue)
                    .setScale(DOUBLE_PRECISION, BigDecimal.ROUND_DOWN).toString();

            String line = "key" + (j + 1) + "\t" + truncatedValue + "\n";
            out.writeBytes(line);/*from   w  w  w . j a  v a2  s  .  c  om*/

            sum = sum.add(new BigDecimal(truncatedValue));
            LOG.debug("input[" + j + "]: '" + line + "' sum: " + sum.toString());
        }
        out.close();
    }
    return sum;
}

From source file:learn.encryption.ssl.SSLContext_Https.java

/**
 * Post??web??,?utf-8/*  www  .  j ava  2s  .  c o m*/
 * 
 * ?UTF8
 * 
 * @param actionUrl
 * @param params
 * @param timeout   
 * @return
 * @throws InvalidParameterException
 * @throws NetWorkException
 * @throws IOException
 * @throws IllegalAccessException 
 * @throws IllegalArgumentException 
 * @throws Exception
 */
public static String post(String url, Map<String, String> params, int timeout)
        throws IOException, IllegalArgumentException, IllegalAccessException {
    if (url == null || url.equals(""))
        throw new IllegalArgumentException("url ");
    if (params == null)
        throw new IllegalArgumentException("params ?");
    if (url.indexOf('?') > 0) {
        url = url
                + "&token=A04BCQULBDgEFB1BQk5cU1NRU19cQU1WWkBPCg0FAwIkCVpZWl1UVExTXFRDSFZSSVlPSkADGhw7HAoQEQMDRFhAWUJYV0hBVE4JAxQLCQlPQ1oiNig/KSsmSEBPGBsAFxkDEkBYSF1eTk1USVldU1FQSEBPFh0OMQhPXEBQSBE=";
    } else {
        url = url
                + "?token=A04BCQULBDgEFB1BQk5cU1NRU19cQU1WWkBPCg0FAwIkCVpZWl1UVExTXFRDSFZSSVlPSkADGhw7HAoQEQMDRFhAWUJYV0hBVE4JAxQLCQlPQ1oiNig/KSsmSEBPGBsAFxkDEkBYSF1eTk1USVldU1FQSEBPFh0OMQhPXEBQSBE=";
    }

    String sb2 = "";
    String BOUNDARY = java.util.UUID.randomUUID().toString();
    String PREFIX = "--", LINEND = "\r\n";
    String MULTIPART_FROM_DATA = "multipart/form-data";
    String CHARSET = "UTF-8";
    // try {
    URL uri = new URL(url);
    HttpsURLConnection conn = (HttpsURLConnection) uri.openConnection();
    // 
    conn.setConnectTimeout(timeout);
    conn.setReadTimeout(timeout);
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("connection", "keep-alive");
    conn.setRequestProperty("Charsert", "UTF-8");
    conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
    SSLSocketFactory ssf = sslContext.getSocketFactory();
    conn.setSSLSocketFactory(ssf);
    conn.setHostnameVerifier(HOSTNAME_VERIFIER);

    StringBuilder sb = new StringBuilder();
    for (Map.Entry<String, String> entry : params.entrySet()) {
        sb.append(PREFIX);
        sb.append(BOUNDARY);
        sb.append(LINEND);
        sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);
        sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
        sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
        sb.append(LINEND);
        sb.append(entry.getValue());
        sb.append(LINEND);
    }

    DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
    outStream.write(sb.toString().getBytes("UTF-8"));
    InputStream in = null;

    byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
    outStream.write(end_data);
    outStream.flush();

    int res = conn.getResponseCode();
    if (res == 200) {
        in = conn.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
        String line = "";
        for (line = br.readLine(); line != null; line = br.readLine()) {
            sb2 = sb2 + line;
        }
    }
    outStream.close();
    conn.disconnect();
    return sb2;
}

From source file:com.sinpo.xnfc.nfc.Util.java

public static String execRootCmd(String cmd) {
    String result = "";
    DataOutputStream dos = null;
    DataInputStream dis = null;/*from   w w w  .j a va 2 s. c  o  m*/

    try {
        Process p = Runtime.getRuntime().exec("su");
        dos = new DataOutputStream(p.getOutputStream());
        dis = new DataInputStream(p.getInputStream());

        dos.writeBytes(cmd + "\n");
        dos.flush();
        dos.writeBytes("exit\n");
        dos.flush();
        String line = null;
        while ((line = dis.readLine()) != null) {
            result += line + "\r\n";
        }
        p.waitFor();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (dos != null) {
            try {
                dos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (dis != null) {
            try {
                dis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return result;
}

From source file:Main.java

private static byte[] ExecuteCommand(String command, Boolean useroot, boolean forcenew) throws Exception {
    Process p;/*from   w w  w.j a va2 s . co m*/
    DataOutputStream stdin;
    InputStream stdout;
    ByteArrayOutputStream baos;
    int read;
    byte[] buffer;
    /*
     * If for any reason the command does not print anything we are stuck forever.
     * Make sure that we print SOMETHING ALWAYS!
     */
    command = "RESULT=$(" + command + "); if [[ $RESULT == '' ]]; then echo '#null#';else echo $RESULT;fi\n";

    p = getProcess(useroot, forcenew);

    stdin = new DataOutputStream(p.getOutputStream());
    stdout = p.getInputStream();
    buffer = new byte[BUFF_LEN];
    baos = new ByteArrayOutputStream();

    stdin.writeBytes(command);

    while (true) {
        read = stdout.read(buffer);
        baos.write(buffer, 0, read);
        if (read < BUFF_LEN) {
            //we have read everything
            break;
        }
    }
    if (forcenew) {
        stdin.writeBytes("exit\n");
        stdin.flush();
        stdin.close();
    }

    //p.waitFor();

    return baos.toByteArray();
}

From source file:com.aliyun.odps.ogg.handler.datahub.DatahubHandler.java

public static void recordSendTimes(int times, HandlerProperties handlerProperties) {
    DataOutputStream out = null;
    OggAlarm oggAlarm = handlerProperties.getOggAlarm();
    try {//from  www.  j  ava  2s  .  c  om
        out = new DataOutputStream(new FileOutputStream(handlerProperties.getHandlerInfoFileName(), false));
        out.writeInt(handlerProperties.getSkipSendTimes());
    } catch (IOException e) {
        oggAlarm.error("Error writing handler info file. sendTimesInTx=" + times + ".", e);
        logger.error("Error writing handler info file. sendTimesInTx=" + times + ".", e);
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                oggAlarm.error("Close handler info file failed. sendTimesInTx=" + times + ".", e);
                logger.error("Close handler info file failed. sendTimesInTx=" + times + ".", e);
            }
        }
    }
}

From source file:CounterApp.java

public int getCount() throws Exception {
    java.net.URL url = new java.net.URL(servletURL);
    java.net.URLConnection con = url.openConnection();
    if (sessionCookie != null) {
        con.setRequestProperty("cookie", sessionCookie);
    }// w  w w.ja  va2s  . co m
    con.setUseCaches(false);
    con.setDoOutput(true);
    con.setDoInput(true);
    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    DataOutputStream out = new DataOutputStream(byteOut);
    out.flush();
    byte buf[] = byteOut.toByteArray();
    con.setRequestProperty("Content-type", "application/octet-stream");
    con.setRequestProperty("Content-length", "" + buf.length);
    DataOutputStream dataOut = new DataOutputStream(con.getOutputStream());
    dataOut.write(buf);
    dataOut.flush();
    dataOut.close();
    DataInputStream in = new DataInputStream(con.getInputStream());
    int count = in.readInt();
    in.close();
    if (sessionCookie == null) {
        String cookie = con.getHeaderField("set-cookie");
        if (cookie != null) {
            sessionCookie = parseCookie(cookie);
            System.out.println("Setting session ID=" + sessionCookie);
        }
    }

    return count;
}

From source file:com.hippo.httpclient.JsonPoster.java

@Override
public void onOutput(HttpURLConnection conn) throws Exception {
    super.onOutput(conn);

    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
    out.write(mJSON.toString().getBytes("utf-8"));
    out.flush();//from  www .  j  a  v a  2s . c o  m
    out.close();
}

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

/** convert file content to a string array with each line separated.
 * @param strings The lines to copy to the file
 * @param file The File to read//www  .  j a v  a  2 s  .  c o m
 */
public static void stringArrayToFile(final List<String> strings, final File file) {

    DataOutputStream out = null;
    BufferedWriter br = null;

    try {
        out = new DataOutputStream(new FileOutputStream(file));
        br = new BufferedWriter(new OutputStreamWriter(out, TactFileUtils.DEFAULT_ENCODING));

        for (final String string : strings) {
            br.write(string);
            br.write('\n');
        }
    } catch (final IOException e) {
        throw new RuntimeException("IO problem in fileToString", e);
    } finally {
        try {
            if (br != null) {
                br.close();
            }
            if (out != null) {
                out.close();
            }
        } catch (final IOException e) {
            ConsoleUtils.displayError(e);
        }
    }
}

From source file:com.paymaya.sdk.android.common.network.AndroidClient.java

private void write(OutputStream os, byte[] body) throws IOException {
    DataOutputStream out = new DataOutputStream(os);
    out.write(body);//from   w w w. j  a  v  a2s  .com
    out.flush();
    out.close();
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.publico.FileDownload.java

@Override
public ActionForward execute(final ActionMapping mapping, final ActionForm actionForm,
        final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    final String oid = request.getParameter("oid");
    final File file = FenixFramework.getDomainObject(oid);
    if (file == null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.getWriter().write(HttpStatus.getStatusText(HttpStatus.SC_BAD_REQUEST));
        response.getWriter().close();//from w  w  w  .j  a va  2 s  .c o  m
    } else {
        final Person person = AccessControl.getPerson();
        if (!file.isPrivate() || file.isPersonAllowedToAccess(person)) {
            response.setContentType(file.getContentType());
            response.addHeader("Content-Disposition", "attachment; filename=" + file.getFilename());
            response.setContentLength(file.getSize().intValue());
            final DataOutputStream dos = new DataOutputStream(response.getOutputStream());
            dos.write(file.getContents());
            dos.close();
        } else if (file.isPrivate() && person == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write(HttpStatus.getStatusText(HttpStatus.SC_UNAUTHORIZED));
            response.getWriter().close();
        } else {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            response.getWriter().write(HttpStatus.getStatusText(HttpStatus.SC_FORBIDDEN));
            response.getWriter().close();
        }
    }
    return null;
}