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:br.org.indt.ndg.servlets.ReceiveImage.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    log.debug("RECEIVE IMAGE: executing doPost method.");

    response.reset();// www  .  ja  v  a2  s.  c  o m
    response.setContentType("image/jpg");

    InputStream inputStream = request.getInputStream();
    DataOutputStream dataOutputStream = new DataOutputStream(response.getOutputStream());

    if (inputStream != null) {
        log.debug("RECEIVE IMAGE: creating file ImageFromClient.jpg...");

        FileOutputStream fileOutputStream = new FileOutputStream("ImageFromClient.jpg");

        byte buffer[] = new byte[1024 * 128];
        int i = 0;

        while ((i = inputStream.read(buffer)) != -1) {
            fileOutputStream.write(buffer, 0, i);
        }

        fileOutputStream.close();
        inputStream.close();

        dataOutputStream.writeBytes(SUCCESS);
        dataOutputStream.close();

        log.debug("RECEIVE IMAGE: SUCCESS");
    } else {
        dataOutputStream.writeBytes(FAILURE);

        log.debug("RECEIVE IMAGE: FAILURE");
    }
}

From source file:com.joey.software.MoorFLSI.RepeatImageTextReader.java

public void saveData(File f) throws IOException {
    DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(f)));

    out.writeInt(imageData.size());/*from w w w.j  a v a  2s .c  o m*/
    out.writeInt(wide);
    out.writeInt(high);

    for (int i = 0; i < imageData.size(); i++) {
        System.out.println(i);
        out.writeLong(imageTime.get(i).getTime());
        for (int x = 0; x < wide; x++) {
            for (int y = 0; y < high; y++) {
                out.writeShort(imageData.get(i)[x][y]);
            }
        }
    }

    out.close();

}

From source file:com.aliyun.openservices.odps.console.mapreduce.runtime.MapReduceJob.java

private boolean writeConfig(String fileName) throws OdpsException {

    try {/*from   w  w  w  . j  a  va2s .  c o m*/
        DataOutputStream out = new DataOutputStream(
                new BufferedOutputStream(new FileOutputStream(new File(fileName))));

        JSONObject result = new JSONObject();

        if (!SetCommand.setMap.isEmpty()) {
            JSONObject obj = new JSONObject(SetCommand.setMap);
            result.put("settings", obj);
        }

        if (!SetCommand.aliasMap.isEmpty()) {
            JSONObject obj = new JSONObject(SetCommand.aliasMap);
            result.put("aliases", obj);
        }

        result.put("commandText", mrCmd.getCommandText());
        result.put("context", context.toJson());
        out.write(result.toString().getBytes(), 0, result.toString().getBytes().length);

        out.close();
    } catch (IOException e) {
        throw new OdpsException("MapReduce write config error: " + e.getMessage());
    } catch (JSONException je) {
        throw new OdpsException("MapReduce write config error: " + je.getMessage());
    }

    return true;
}

From source file:au.org.ala.spatial.util.RecordsSmall.java

private void makeUniquePoints() throws Exception {
    //make unique points and index
    points = new RandomAccessFile(filename + "records.csv.small.points", "r");
    double[] allPoints = getPointsAll();
    Coord[] p = new Coord[allPoints.length / 2];
    for (int i = 0; i < allPoints.length; i += 2) {
        p[i / 2] = new Coord(allPoints[i], allPoints[i + 1], i / 2);
    }// w  w w.  ja  va 2s .  c  om
    allPoints = null; //make available to GC
    Arrays.sort(p, new Comparator<Coord>() {
        public int compare(Coord o1, Coord o2) {
            return o1.longitude == o2.longitude
                    ? (o1.latitude == o2.latitude ? 0 : (o1.latitude - o2.latitude > 0.0 ? 1 : -1))
                    : (o1.longitude - o2.longitude > 0.0 ? 1 : -1);
        }
    });

    DataOutputStream outputUniquePoints = new DataOutputStream(
            new BufferedOutputStream(new FileOutputStream(filename + "records.csv.small.pointsUniquePoints")));
    DataOutputStream outputUniqueIdx = new DataOutputStream(
            new BufferedOutputStream(new FileOutputStream(filename + "records.csv.small.pointsUniqueIdx")));

    int pos = -1; //first point is set after pos++
    int[] newPos = new int[p.length];
    for (int i = 0; i < p.length; i++) {
        if (i == 0 || p[i].latitude != p[i - 1].latitude || p[i].longitude != p[i - 1].longitude) {
            outputUniquePoints.writeDouble(p[i].latitude);
            outputUniquePoints.writeDouble(p[i].longitude);
            pos++;
        }
        newPos[p[i].pos] = pos;
    }
    for (int i = 0; i < p.length; i++) {
        outputUniqueIdx.writeInt(newPos[i]);
    }

    outputUniqueIdx.flush();
    outputUniqueIdx.close();
    outputUniquePoints.flush();
    outputUniquePoints.close();

    points.close();
}

From source file:com.linkedin.pinot.core.segment.creator.impl.SegmentIndexCreationDriverImpl.java

/**
 * Writes segment creation metadata to disk.
 *///  w w  w.  ja va2 s.  co  m
void persistCreationMeta(File outputDir, long crc) throws IOException {
    final File crcFile = new File(outputDir, V1Constants.SEGMENT_CREATION_META);
    final DataOutputStream out = new DataOutputStream(new FileOutputStream(crcFile));
    out.writeLong(crc);

    long creationTime = System.currentTimeMillis();

    // Use the creation time from the configuration if it exists and is not -1
    try {
        long configCreationTime = Long.parseLong(config.getCreationTime());
        if (0L < configCreationTime) {
            creationTime = configCreationTime;
        }
    } catch (Exception nfe) {
        // Ignore NPE and NFE, use the current time.
    }

    out.writeLong(creationTime);
    out.close();
}

From source file:com.jamsuni.jamsunicodescan.MainActivity.java

public void testTTS(String msg) {

    String apiURL = "https://openapi.naver.com/v1/voice/tts.bin";

    BookInfo bookInfo = new BookInfo();

    try {//from  w  ww  .ja  v a  2  s . co  m
        String text = URLEncoder.encode(msg, "UTF-8");

        URL url = new URL(apiURL);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("POST");

        con.setRequestProperty("X-Naver-Client-Id", clientId);
        con.setRequestProperty("X-Naver-Client-Secret", clientSecret);

        // post request
        String postParams = "speaker=mijin&speed=0&text=" + text;
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(postParams);
        wr.flush();
        wr.close();
        int responseCode = con.getResponseCode();
        BufferedReader br;
        if (responseCode == 200) { // ? 
            InputStream is = con.getInputStream();
            int read = 0;
            byte[] bytes = new byte[1024];
            // ? ? mp3 ? ?
            String tempname = Long.valueOf(new Date().getTime()).toString();
            File f = new File(Environment.getExternalStorageDirectory() + "/" + tempname + ".mp3");
            f.createNewFile();
            OutputStream outputStream = new FileOutputStream(f);
            while ((read = is.read(bytes)) != -1) {
                outputStream.write(bytes, 0, read);
            }
            is.close();
        } else { // ? ?
            br = new BufferedReader(new InputStreamReader(con.getErrorStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = br.readLine()) != null) {
                response.append(inputLine);
            }
            br.close();
            System.out.println(response.toString());
        }

    } catch (Exception e) {
        System.out.println(e);
    }

    return;
}

From source file:se.leap.bitmaskclient.ProviderAPI.java

/**
 * Executes an HTTP request expecting a JSON response.
 *
 * @param url//from   w ww  . jav a 2  s . c  om
 * @param request_method
 * @param parameters
 * @return response from authentication server
 */
private JSONObject sendToServer(String url, String request_method, Map<String, String> parameters) {
    JSONObject json_response;
    HttpsURLConnection urlConnection = null;
    try {
        InputStream is = null;
        urlConnection = (HttpsURLConnection) new URL(url).openConnection();
        urlConnection.setRequestMethod(request_method);
        String locale = Locale.getDefault().getLanguage() + Locale.getDefault().getCountry();
        urlConnection.setRequestProperty("Accept-Language", locale);
        urlConnection.setChunkedStreamingMode(0);
        urlConnection.setSSLSocketFactory(getProviderSSLSocketFactory());

        DataOutputStream writer = new DataOutputStream(urlConnection.getOutputStream());
        writer.writeBytes(formatHttpParameters(parameters));
        writer.close();

        is = urlConnection.getInputStream();
        String plain_response = new Scanner(is).useDelimiter("\\A").next();
        json_response = new JSONObject(plain_response);
    } catch (ClientProtocolException e) {
        json_response = getErrorMessage(urlConnection);
        e.printStackTrace();
    } catch (IOException e) {
        json_response = getErrorMessage(urlConnection);
        e.printStackTrace();
    } catch (JSONException e) {
        json_response = getErrorMessage(urlConnection);
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        json_response = getErrorMessage(urlConnection);
        e.printStackTrace();
    } catch (KeyManagementException e) {
        json_response = getErrorMessage(urlConnection);
        e.printStackTrace();
    } catch (KeyStoreException e) {
        json_response = getErrorMessage(urlConnection);
        e.printStackTrace();
    } catch (CertificateException e) {
        json_response = getErrorMessage(urlConnection);
        e.printStackTrace();
    }

    return json_response;
}

From source file:CoolBarExamples.java

private void saveState(CoolBar coolBar, File file) throws IOException {
    DataOutputStream out = new DataOutputStream(new FileOutputStream(file));

    try {/*from  w  w w .  ja  va2s  . c o  m*/
        // Orders of items. 
        System.out.println("Item order: " + intArrayToString(coolBar.getItemOrder()));
        int[] order = coolBar.getItemOrder();
        out.writeInt(order.length);
        for (int i = 0; i < order.length; i++)
            out.writeInt(order[i]);

        // Wrap indices.
        System.out.println("Wrap indices: " + intArrayToString(coolBar.getWrapIndices()));
        int[] wrapIndices = coolBar.getWrapIndices();
        out.writeInt(wrapIndices.length);
        for (int i = 0; i < wrapIndices.length; i++)
            out.writeInt(wrapIndices[i]);

        // Sizes. 
        Point[] sizes = coolBar.getItemSizes();
        out.writeInt(sizes.length);
        for (int i = 0; i < sizes.length; i++) {
            out.writeInt(sizes[i].x);
            out.writeInt(sizes[i].y);
        }
    } finally {
        out.close();
    }

}

From source file:UploadTest.java

@Test
public void put_data_test() {
    String pid = "frl:6376979";
    try {/*from w w w .  j a  v a  2s  .c  om*/
        System.out.println(url);
        String charset = "UTF-8";
        File file = new File("/home/raul/test/frl%3A6376984/6376986.pdf");
        FileInputStream fi = new FileInputStream(file);

        httpCon.setDoOutput(true);
        httpCon.setDoInput(true);
        httpCon.setRequestMethod("PUT");
        httpCon.setRequestProperty("Connection", "Keep-Alive");
        httpCon.setRequestProperty("Content-Type", "application/pdf");
        httpCon.setRequestProperty("type", "multipart/form-data");
        httpCon.setRequestProperty("Accept", "application/data");
        httpCon.setRequestProperty("uploaded_file", file.getPath());
        System.out.println(file.getPath());
        DataOutputStream out = new DataOutputStream(httpCon.getOutputStream());
        System.out.println("130");
        Files.copy(file.toPath(), out);
        int bytesRead;
        byte[] dataBuffer = new byte[1024];
        while ((bytesRead = fi.read(dataBuffer)) != -1) {
            out.write(dataBuffer, 0, bytesRead);
        }
        System.out.println("137");
        out.flush();
        out.close();
        System.out.println("140");
        System.out.println("142");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:cit360.sandbox.BackEndMenu.java

public static final void smtpExample() {
    // declaration section:
    // smtpClient: our client socket
    // os: output stream
    // is: input stream
    Socket smtpSocket = null;/*w ww  . ja  v  a 2 s  .  co m*/
    DataOutputStream os = null;
    DataInputStream is = null;
    // Initialization section:
    // Try to open a socket on port 25
    // Try to open input and output streams
    try {
        smtpSocket = new Socket("localhost", 25);
        os = new DataOutputStream(smtpSocket.getOutputStream());
        is = new DataInputStream(smtpSocket.getInputStream());
    } catch (UnknownHostException e) {
        System.err.println("Did not recognize server: localhost");
    } catch (IOException e) {
        System.err.println("Was not able to open I/O connection to: localhost");
    }
    // If everything has been initialized then we want to write some data
    // to the socket we have opened a connection to on port 25
    if (smtpSocket != null && os != null && is != null) {
        try {

            os.writeBytes("HELO\n");
            os.writeBytes("MAIL From: david.banks0889@gmail.com\n");
            os.writeBytes("RCPT To: david.banks0889@gmail.com\n");
            os.writeBytes("DATA\n");
            os.writeBytes("From: david.banks0889@gmail.com\n");
            os.writeBytes("Subject: TEST\n");
            os.writeBytes("Hi there\n"); // message body
            os.writeBytes("\n.\n");
            os.writeBytes("QUIT");
            // keep on reading from/to the socket till we receive the "Ok" from SMTP,
            // once we received that then we want to break.
            String responseLine;
            while ((responseLine = is.readLine()) != null) {
                System.out.println("Server: " + responseLine);
                if (responseLine.contains("Ok")) {
                    break;
                }
            }
            // clean up:
            // close the output stream
            // close the input stream
            // close the socket
            os.close();
            is.close();
            smtpSocket.close();
        } catch (UnknownHostException e) {
            System.err.println("Trying to connect to unknown host: " + e);
        } catch (IOException e) {
            System.err.println("IOException:  " + e);
        }
    }
}