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:IntSort.java

public void readStream() {
    try {/*ww w . j  ava2  s.  co  m*/
        // Careful: Make sure this is big enough!
        // Better yet, test and reallocate if necessary      
        byte[] recData = new byte[50];

        // Read from the specified byte array
        ByteArrayInputStream strmBytes = new ByteArrayInputStream(recData);

        // Read Java data types from the above byte array
        DataInputStream strmDataType = new DataInputStream(strmBytes);

        if (rs.getNumRecords() > 0) {
            ComparatorInt comp = new ComparatorInt();

            int i = 1;
            RecordEnumeration re = rs.enumerateRecords(null, comp, false);
            while (re.hasNextElement()) {
                // Get data into the byte array          
                rs.getRecord(re.nextRecordId(), recData, 0);

                // Read back the data types      
                System.out.println("Record #" + i++);

                System.out.println("Name: " + strmDataType.readUTF());
                System.out.println("Dog: " + strmDataType.readBoolean());
                System.out.println("Rank: " + strmDataType.readInt());
                System.out.println("--------------------");

                // Reset so read starts at beginning of array 
                strmBytes.reset();
            }

            comp.compareIntClose();

            // Free enumerator
            re.destroy();
        }

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

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

From source file:com.inter.trade.view.slideplayview.util.AbFileUtil.java

/**
 * ??byte[].//from   www  .  ja va 2s. co m
 * @param imgByte byte[]
 * @param fileName ?????.jpg
 * @param type ???AbConstant
 * @param newWidth 
 * @param newHeight 
 * @return Bitmap 
 */
public static Bitmap getBitmapFormByte(byte[] imgByte, String fileName, int type, int newWidth, int newHeight) {
    FileOutputStream fos = null;
    DataInputStream dis = null;
    ByteArrayInputStream bis = null;
    Bitmap b = null;
    File file = null;
    try {
        if (imgByte != null) {
            File sdcardDir = Environment.getExternalStorageDirectory();
            String path = sdcardDir.getAbsolutePath() + downPathImageDir;
            file = new File(path + fileName);

            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            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();

            b = getBitmapFromSD(file, type, newWidth, newHeight);
        }

    } 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 b;
}

From source file:com.tvd.cocos2dx.popup.creator.file.FileUtils.java

public String readFromFile(String pFilePath) {
    FileInputStream fstream = null;
    DataInputStream inputStream = null;
    BufferedReader bufferedReader = null;
    mContent = "";
    try {//  w  ww.j  a  v  a 2s  .c  o  m
        File file = new File(pFilePath);
        if (!file.exists()) {
            System.err.println("ERROR::readFromFile pFilePath = " + pFilePath);
            NotificationCenter.getInstance()
                    .pushError("File " + pFilePath + " does not exist, create this file to continues");
            return null;
        }
        fstream = new FileInputStream(file);
        inputStream = new DataInputStream(fstream);
        bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

        StringBuilder builder = new StringBuilder();
        String lineContent = bufferedReader.readLine();
        while (lineContent != null) {
            builder.append(lineContent).append("\n");
            lineContent = bufferedReader.readLine();
        }
        mContent = builder.toString();
        fstream.close();
        inputStream.close();
        bufferedReader.close();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {

    }
    return mContent;
}

From source file:org.tacografo.file.FileBlockTGD.java

/**
 * Se encarga de leer los bytes del fichero he introducirlo en un
 * hasmap<FID,array bytes> los bloques bienen formado por TLV =
 * tag(FID)-longitud-value//from  w w  w . j  ava  2  s  .c om
 * @throws ErrorFile ocurrido cuando no es un fichero tgd o falla en la lectura de algun bloque
 * porque no encuentre el tag(fid)
 */
private void factorizar_bloques(String nombre_fichero) throws ErrorFile {
    FileInputStream fis = null;
    DataInputStream entrada = null;
    try {
        fis = new FileInputStream(nombre_fichero);
        entrada = new DataInputStream(fis);
        //lectura de bloques siempre y cuando la lectura del fid exista
        this.lectura_bloque(entrada);

    } catch (FileNotFoundException e) {
        System.out.println(e.getMessage());
    } catch (EOFException e) {
        // se produce cuando se llega al final del fichero
        //System.out.println(e.getMessage());
    } catch (IOException e) {
        System.out.println(e.getMessage());
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
            if (entrada != null) {
                entrada.close();
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

}

From source file:net.mohatu.bloocoin.miner.SubmitListClass.java

private void submit() {
    for (int i = 0; i < solved.size(); i++) {
        try {/*from  w ww .  j av  a2s .co  m*/
            Socket sock = new Socket(this.url, this.port);
            String result = new String();
            DataInputStream is = new DataInputStream(sock.getInputStream());
            DataOutputStream os = null;
            BufferedReader in = new BufferedReader(new InputStreamReader(is));
            solution = solved.get(i);
            hash = DigestUtils.sha512Hex(solution);

            String command = "{\"cmd\":\"check" + "\",\"winning_string\":\"" + solution
                    + "\",\"winning_hash\":\"" + hash + "\",\"addr\":\"" + MainView.getAddr() + "\"}";
            os = new DataOutputStream(sock.getOutputStream());
            os.write(command.getBytes());

            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                result += inputLine;
            }

            if (result.contains("\"success\": true")) {
                System.out.println("Result: Submitted");
                MainView.updateStatusText(solution + " submitted");
                Thread gc = new Thread(new CoinClass());
                gc.start();
            } else if (result.contains("\"success\": false")) {
                System.out.println("Result: Failed");
                MainView.updateStatusText("Submission of " + solution + " failed, already exists!");
            }
            is.close();
            os.close();
            os.flush();
            sock.close();
        } catch (UnknownHostException e) {
            MainView.updateStatusText("Submission of " + solution + " failed, connection failed!");
        } catch (IOException e) {
            MainView.updateStatusText("Submission of " + solution + " failed, connection failed!");
        }
    }
    Thread gc = new Thread(new CoinClass());
    gc.start();
}

From source file:org.apache.hadoop.mapred.TestShuffleHandler.java

/**
 * Verify client prematurely closing a connection.
 *
 * @throws Exception exception.//from  w ww .j av  a  2s .c  om
 */
@Test(timeout = 10000)
public void testClientClosesConnection() throws Exception {
    final ArrayList<Throwable> failures = new ArrayList<Throwable>(1);
    Configuration conf = new Configuration();
    conf.setInt(ShuffleHandler.SHUFFLE_PORT_CONFIG_KEY, 0);
    ShuffleHandler shuffleHandler = new ShuffleHandler() {
        @Override
        protected Shuffle getShuffle(Configuration conf) {
            // replace the shuffle handler with one stubbed for testing
            return new Shuffle(conf) {
                @Override
                protected MapOutputInfo getMapOutputInfo(String base, String mapId, int reduce, String user)
                        throws IOException {
                    return null;
                }

                @Override
                protected void populateHeaders(List<String> mapIds, String jobId, String user, int reduce,
                        HttpRequest request, HttpResponse response, boolean keepAliveParam,
                        Map<String, MapOutputInfo> infoMap) throws IOException {
                    // Only set response headers and skip everything else
                    // send some dummy value for content-length
                    super.setResponseHeaders(response, keepAliveParam, 100);
                }

                @Override
                protected void verifyRequest(String appid, ChannelHandlerContext ctx, HttpRequest request,
                        HttpResponse response, URL requestUri) throws IOException {
                }

                @Override
                protected ChannelFuture sendMapOutput(ChannelHandlerContext ctx, Channel ch, String user,
                        String mapId, int reduce, MapOutputInfo info) throws IOException {
                    // send a shuffle header and a lot of data down the channel
                    // to trigger a broken pipe
                    ShuffleHeader header = new ShuffleHeader("attempt_12345_1_m_1_0", 5678, 5678, 1);
                    DataOutputBuffer dob = new DataOutputBuffer();
                    header.write(dob);
                    ch.write(wrappedBuffer(dob.getData(), 0, dob.getLength()));
                    dob = new DataOutputBuffer();
                    for (int i = 0; i < 100000; ++i) {
                        header.write(dob);
                    }
                    return ch.write(wrappedBuffer(dob.getData(), 0, dob.getLength()));
                }

                @Override
                protected void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
                    if (failures.size() == 0) {
                        failures.add(new Error());
                        ctx.getChannel().close();
                    }
                }

                @Override
                protected void sendError(ChannelHandlerContext ctx, String message, HttpResponseStatus status) {
                    if (failures.size() == 0) {
                        failures.add(new Error());
                        ctx.getChannel().close();
                    }
                }
            };
        }
    };
    shuffleHandler.init(conf);
    shuffleHandler.start();

    // simulate a reducer that closes early by reading a single shuffle header
    // then closing the connection
    URL url = new URL(
            "http://127.0.0.1:" + shuffleHandler.getConfig().get(ShuffleHandler.SHUFFLE_PORT_CONFIG_KEY)
                    + "/mapOutput?job=job_12345_1&reduce=1&map=attempt_12345_1_m_1_0");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestProperty(ShuffleHeader.HTTP_HEADER_NAME, ShuffleHeader.DEFAULT_HTTP_HEADER_NAME);
    conn.setRequestProperty(ShuffleHeader.HTTP_HEADER_VERSION, ShuffleHeader.DEFAULT_HTTP_HEADER_VERSION);
    conn.connect();
    DataInputStream input = new DataInputStream(conn.getInputStream());
    Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
    Assert.assertEquals("close", conn.getHeaderField(HttpHeaders.CONNECTION));
    ShuffleHeader header = new ShuffleHeader();
    header.readFields(input);
    input.close();

    shuffleHandler.stop();
    Assert.assertTrue("sendError called when client closed connection", failures.size() == 0);
}

From source file:org.commoncrawl.service.queryserver.index.PositionBasedSequenceFileIndex.java

private ByteBuffer loadStreamIntoMemory(Path streamPath) throws IOException {
    //LOG.info("Loading Stream:" + streamPath.getAbsolutePath());
    if (!_fileSystem.exists(streamPath) || _fileSystem.getFileStatus(streamPath).isDir()) {
        throw new IOException("Stream Path:" + streamPath + " Points to Invalid File");
    } else {/*from   ww  w  . j  a v a 2  s  .  c  om*/
        DataInputStream inputStream = null;
        ByteBuffer bufferOut = null;
        try {

            //LOG.info("Allocating Buffer of size:" + streamPath.length() + " for Stream:" + streamPath.getAbsolutePath());
            bufferOut = ByteBuffer.allocate((int) _fileSystem.getFileStatus(streamPath).getLen());
            inputStream = _fileSystem.open(streamPath);
            long loadStart = System.currentTimeMillis();
            for (int offset = 0, totalRead = 0; offset < bufferOut.capacity();) {
                int bytesToRead = Math.min(16384, bufferOut.capacity() - totalRead);
                inputStream.read(bufferOut.array(), offset, bytesToRead);
                offset += bytesToRead;
                totalRead += bytesToRead;
            }
            //LOG.info("Load of Stream:" + streamPath.getAbsolutePath() + " Took:" + (System.currentTimeMillis() - loadStart) + " MS");
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }

        return bufferOut;
    }
}

From source file:net.mohatu.bloocoin.miner.SubmitList.java

private void submit() {
    for (int i = 0; i < solved.size(); i++) {
        try {/*from ww  w.  ja v  a  2s  . c  o  m*/
            Socket sock = new Socket(this.url, this.port);
            String result = new String();
            DataInputStream is = new DataInputStream(sock.getInputStream());
            DataOutputStream os = null;
            BufferedReader in = new BufferedReader(new InputStreamReader(is));
            solution = solved.get(i);
            hash = DigestUtils.sha512Hex(solution);

            String command = "{\"cmd\":\"check" + "\",\"winning_string\":\"" + solution
                    + "\",\"winning_hash\":\"" + hash + "\",\"addr\":\"" + Main.getAddr() + "\"}";
            os = new DataOutputStream(sock.getOutputStream());
            os.write(command.getBytes());

            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                result += inputLine;
            }

            if (result.contains("\"success\": true")) {
                System.out.println("Result: Submitted");
                Main.updateStatusText(solution + " submitted", Color.blue);
                Thread gc = new Thread(new Coins());
                gc.start();
            } else if (result.contains("\"success\": false")) {
                System.out.println("Result: Failed");
                Main.updateStatusText("Submission of " + solution + " failed, already exists!", Color.red);
            }
            is.close();
            os.close();
            os.flush();
            sock.close();
        } catch (UnknownHostException e) {
            e.printStackTrace();
            Main.updateStatusText("Submission of " + solution + " failed, connection failed!", Color.red);
        } catch (IOException e) {
            e.printStackTrace();
            Main.updateStatusText("Submission of " + solution + " failed, connection failed!", Color.red);
        }
    }
    Thread gc = new Thread(new Coins());
    gc.start();
}

From source file:eu.stratosphere.nephele.services.iomanager.IOManagerPerformanceBenchmark.java

private final void speedTestStream(int bufferSize) throws IOException {
    final Channel.ID tmpChannel = ioManager.createChannel();
    final IntegerRecord rec = new IntegerRecord(0);

    File tempFile = null;/*  w w  w.j a  v  a  2s .  c o m*/
    DataOutputStream daos = null;
    DataInputStream dais = null;

    try {
        tempFile = new File(tmpChannel.getPath());

        FileOutputStream fos = new FileOutputStream(tempFile);
        daos = new DataOutputStream(new BufferedOutputStream(fos, bufferSize));

        long writeStart = System.currentTimeMillis();

        int valsLeft = NUM_INTS_WRITTEN;
        while (valsLeft-- > 0) {
            rec.setValue(valsLeft);
            rec.write(daos);
        }
        daos.close();
        daos = null;

        long writeElapsed = System.currentTimeMillis() - writeStart;

        // ----------------------------------------------------------------

        FileInputStream fis = new FileInputStream(tempFile);
        dais = new DataInputStream(new BufferedInputStream(fis, bufferSize));

        long readStart = System.currentTimeMillis();

        valsLeft = NUM_INTS_WRITTEN;
        while (valsLeft-- > 0) {
            rec.read(dais);
        }
        dais.close();
        dais = null;

        long readElapsed = System.currentTimeMillis() - readStart;

        LOG.info("File-Stream with buffer " + bufferSize + ": write " + writeElapsed + " msecs, read "
                + readElapsed + " msecs.");
    } finally {
        // close if possible
        if (daos != null) {
            daos.close();
        }
        if (dais != null) {
            dais.close();
        }
        // try to delete the file
        if (tempFile != null) {
            tempFile.delete();
        }
    }
}

From source file:com.xperia64.timidityae.Globals.java

public static boolean initialize(final Activity a) {
    if (firstRun) {
        final File rootStorage = new File(
                Environment.getExternalStorageDirectory().getAbsolutePath() + "/TimidityAE/");
        if (!rootStorage.exists()) {
            rootStorage.mkdir();//from  w  ww  . ja v  a 2 s  . c o  m
        }
        File playlistDir = new File(rootStorage.getAbsolutePath() + "/playlists/");
        if (!playlistDir.exists()) {
            playlistDir.mkdir();
        }
        File tcfgDir = new File(rootStorage.getAbsolutePath() + "/timidity/");
        if (!tcfgDir.exists()) {
            tcfgDir.mkdir();
        }
        File sfDir = new File(rootStorage.getAbsolutePath() + "/soundfonts/");
        if (!sfDir.exists()) {
            sfDir.mkdir();
        }
        updateBuffers(updateRates());
        aRate = Integer.parseInt(prefs.getString("tplusRate",
                Integer.toString(AudioTrack.getNativeOutputSampleRate(AudioTrack.MODE_STREAM))));
        buff = Integer.parseInt(prefs.getString("tplusBuff", "192000")); // This is usually a safe number, but should probably do a test or something
        migrateFrom1X(rootStorage);
        final Editor eee = prefs.edit();
        firstRun = false;
        eee.putBoolean("tplusFirstRun", false);
        eee.putString("dataDir", Environment.getExternalStorageDirectory().getAbsolutePath() + "/TimidityAE/");
        if (new File(dataFolder + "/timidity/timidity.cfg").exists()) {
            if (manConfig = !cfgIsAuto(dataFolder + "/timidity/timidity.cfg")) {
                eee.putBoolean("manConfig", true);
            } else {
                eee.putBoolean("manConfig", false);
                ArrayList<String> soundfonts = new ArrayList<String>();
                FileInputStream fstream = null;
                try {
                    fstream = new FileInputStream(dataFolder + "/timidity/timidity.cfg");
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                // Get the object of DataInputStream
                DataInputStream in = new DataInputStream(fstream);
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                //Read File Line By Line
                try {
                    br.readLine(); // skip first line
                } catch (IOException e) {
                    e.printStackTrace();
                }
                String line;
                try {
                    while ((line = br.readLine()) != null) {
                        if (line.indexOf("soundfont \"") >= 0 && line.lastIndexOf('"') >= 0) {
                            try {
                                String st = line.substring(line.indexOf("soundfont \"") + 11,
                                        line.lastIndexOf('"'));
                                soundfonts.add(st);
                            } catch (ArrayIndexOutOfBoundsException e1) {
                                e1.printStackTrace();
                            }

                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    eee.putString("tplusSoundfonts", ObjectSerializer.serialize(soundfonts));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            eee.commit();
            return true;
        } else {
            // Should probably check if 8rock11e exists no matter what
            eee.putBoolean("manConfig", false);

            AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {

                ProgressDialog pd;

                @Override
                protected void onPreExecute() {
                    pd = new ProgressDialog(a);
                    pd.setTitle(a.getResources().getString(R.string.extract));
                    pd.setMessage(a.getResources().getString(R.string.extract_sum));
                    pd.setCancelable(false);
                    pd.setIndeterminate(true);
                    pd.show();
                }

                @Override
                protected Void doInBackground(Void... arg0) {

                    if (extract8Rock(a) != 777) {
                        Toast.makeText(a, "Could not extrct default soundfont", Toast.LENGTH_SHORT).show();
                    }
                    return null;
                }

                @Override
                protected void onPostExecute(Void result) {
                    if (pd != null)
                        pd.dismiss();
                    ArrayList<String> tmpConfig = new ArrayList<String>();
                    tmpConfig.add(rootStorage.getAbsolutePath() + "/soundfonts/8Rock11e.sf2");
                    try {
                        eee.putString("tplusSoundfonts", ObjectSerializer.serialize(tmpConfig));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    eee.commit();
                    writeCfg(a, rootStorage.getAbsolutePath() + "/timidity/timidity.cfg", tmpConfig);
                    ((TimidityActivity) a).initCallback();
                }

            };
            task.execute((Void[]) null);
            return false;
        }

    } else {
        return true;
    }
}