Example usage for java.io DataInputStream DataInputStream

List of usage examples for java.io DataInputStream DataInputStream

Introduction

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

Prototype

public DataInputStream(InputStream in) 

Source Link

Document

Creates a DataInputStream that uses the specified underlying InputStream.

Usage

From source file:J2MESortMixedRecordDataTypeExample.java

public void commandAction(Command command, Displayable displayable) {
    if (command == exit) {
        destroyApp(true);//w  w  w.j  a v  a2  s.c  om
        notifyDestroyed();
    } else if (command == start) {
        try {
            recordstore = RecordStore.openRecordStore("myRecordStore", true);
            byte[] outputRecord;
            String outputString[] = { "Mary", "Bob", "Adam" };
            int outputInteger[] = { 15, 10, 5 };
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            DataOutputStream outputDataStream = new DataOutputStream(outputStream);
            for (int x = 0; x < 3; x++) {
                outputDataStream.writeUTF(outputString[x]);
                outputDataStream.writeInt(outputInteger[x]);
                outputDataStream.flush();
                outputRecord = outputStream.toByteArray();
                recordstore.addRecord(outputRecord, 0, outputRecord.length);
                outputStream.reset();
            }
            outputStream.close();
            outputDataStream.close();

            String[] inputString = new String[3];
            byte[] byteInputData = new byte[300];
            ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData);
            DataInputStream inputDataStream = new DataInputStream(inputStream);
            StringBuffer buffer = new StringBuffer();
            comparator = new Comparator();
            recordEnumeration = recordstore.enumerateRecords(null, comparator, false);
            while (recordEnumeration.hasNextElement()) {
                recordstore.getRecord(recordEnumeration.nextRecordId(), byteInputData, 0);
                buffer.append(inputDataStream.readUTF());
                buffer.append(inputDataStream.readInt());
                buffer.append("\n");
                inputDataStream.reset();
            }
            alert = new Alert("Reading", buffer.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
            inputDataStream.close();
            inputStream.close();
            recordstore.closeRecordStore();
            if (RecordStore.listRecordStores() != null) {
                RecordStore.deleteRecordStore("myRecordStore");
                comparator.compareClose();
                recordEnumeration.destroy();
            }
        } catch (Exception error) {
            alert = new Alert("Error Removing", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
    }
}

From source file:J2MEMixedRecordEnumerationExample.java

public void commandAction(Command command, Displayable displayable) {
    if (command == exit) {
        destroyApp(true);/* w  w  w  .  java 2  s.  c  o  m*/
        notifyDestroyed();
    } else if (command == start) {
        try {
            recordstore = RecordStore.openRecordStore("myRecordStore", true);
            byte[] outputRecord;
            String outputString[] = { "First Record", "Second Record", "Third Record" };
            int outputInteger[] = { 15, 10, 5 };
            boolean outputBoolean[] = { true, false, true };
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            DataOutputStream outputDataStream = new DataOutputStream(outputStream);
            for (int x = 0; x < 3; x++) {
                outputDataStream.writeUTF(outputString[x]);
                outputDataStream.writeBoolean(outputBoolean[x]);
                outputDataStream.writeInt(outputInteger[x]);
                outputDataStream.flush();
                outputRecord = outputStream.toByteArray();
                recordstore.addRecord(outputRecord, 0, outputRecord.length);
            }
            outputStream.reset();
            outputStream.close();
            outputDataStream.close();
            StringBuffer buffer = new StringBuffer();
            byte[] byteInputData = new byte[300];
            ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData);
            DataInputStream inputDataStream = new DataInputStream(inputStream);
            recordEnumeration = recordstore.enumerateRecords(null, null, false);
            while (recordEnumeration.hasNextElement()) {
                recordstore.getRecord(recordEnumeration.nextRecordId(), byteInputData, 0);
                buffer.append(inputDataStream.readUTF());
                buffer.append("\n");
                buffer.append(inputDataStream.readBoolean());
                buffer.append("\n");
                buffer.append(inputDataStream.readInt());
                buffer.append("\n");
                alert = new Alert("Reading", buffer.toString(), null, AlertType.WARNING);
                alert.setTimeout(Alert.FOREVER);
                display.setCurrent(alert);
            }
            inputStream.close();
            recordstore.closeRecordStore();
            if (RecordStore.listRecordStores() != null) {
                RecordStore.deleteRecordStore("myRecordStore");
                recordEnumeration.destroy();
            }
        } catch (Exception error) {
            alert = new Alert("Error Removing", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
    }

}

From source file:SecurityManagerTest.java

private boolean accessOK() {
    int c;/*from  w w w .  ja v a2 s . co m*/
    DataInputStream in = new DataInputStream(System.in);
    String response;

    System.out.println("What's the secret password?");
    try {
        response = in.readLine();
        if (response.equals(password))
            return true;
        else
            return false;
    } catch (IOException e) {
        return false;
    }
}

From source file:com.simiacryptus.util.Util.java

/**
 * Binary stream stream./*from  ww w.j av a  2 s  . c  om*/
 *
 * @param path       the path
 * @param name       the name
 * @param skip       the skip
 * @param recordSize the record size
 * @return the stream
 * @throws IOException the io exception
 */
public static Stream<byte[]> binaryStream(final String path, @javax.annotation.Nonnull final String name,
        final int skip, final int recordSize) throws IOException {
    @javax.annotation.Nonnull
    final File file = new File(path, name);
    final byte[] fileData = IOUtils.toByteArray(
            new BufferedInputStream(new GZIPInputStream(new BufferedInputStream(new FileInputStream(file)))));
    @javax.annotation.Nonnull
    final DataInputStream in = new DataInputStream(new ByteArrayInputStream(fileData));
    in.skip(skip);
    return com.simiacryptus.util.Util.toIterator(new BinaryChunkIterator(in, recordSize));
}

From source file:de.dfki.resc28.ole.resources.Repository.java

public Response createAsset(
        @HeaderParam(HttpHeaders.ACCEPT) @DefaultValue(Constants.CT_TEXT_TURTLE) final String acceptType,
        String fileUri) {/* w  w w. j ava2s . c  om*/
    try {
        @SuppressWarnings("resource")
        CloseableHttpClient http = ProxyConfigurator.createHttpClient();
        HttpGet request = new HttpGet(fileUri);

        request.setHeader("Accept", "text/plain"); // TODO: set accept-header from inputFormat!
        HttpResponse response = (HttpResponse) http.execute(request);

        if (response.getStatusLine().getStatusCode() == 200) {
            DataInputStream input = new DataInputStream(
                    new BufferedInputStream(response.getEntity().getContent()));
            String ID = UUID.randomUUID().toString();
            AssetListener assetListener = new AssetListener(ID, fileUri);
            DistributionListener distributionListener = new DistributionListener(ID, fileUri);

            LDrawLexer lexer = new LDrawLexer(new ANTLRInputStream(input));
            LDrawParser parser = new LDrawParser(new CommonTokenStream(lexer));
            ParseTreeWalker walker = new ParseTreeWalker();
            ParseTree tree = parser.file();
            walker.walk(assetListener, tree);
            walker.walk(distributionListener, tree);

            Model assetModel = assetListener.getModel();
            fGraphStore.addToNamedGraph(Util.joinPath(Server.fAssetBaseUri, ID), assetModel);

            Model distributionModel = distributionListener.getModel();
            fGraphStore.addToNamedGraph(Util.joinPath(Server.fDistributionBaseUri, ID), distributionModel);

            final Model repoModel = ModelFactory.createDefaultModel();//fGraphStore.getNamedGraph(Util.joinPath(Server.fBaseURI, "repo"));
            Resource repo = repoModel.getResource(Util.joinPath(Server.fBaseURI, "repo"));
            Resource asset = repoModel.createResource(Util.joinPath(Server.fBaseURI, "repo/assets/", ID));
            repoModel.add(repo, DCAT.dataset, asset);
            fGraphStore.addToNamedGraph(Util.joinPath(Server.fBaseURI, "repo"), repoModel);

            return Response.ok().status(Status.CREATED).contentLocation(new URI(asset.getURI())).build();

        } else {
            return Response.status(Status.INTERNAL_SERVER_ERROR).build();
        }
    } catch (Exception e) {
        throw new WebApplicationException();
    }
}

From source file:com.datatorrent.lib.io.fs.HdfsOutputOperatorTest.java

private int readFile(String path, final String val) {
    BufferedReader br = null;/*from w  ww.  ja  v  a  2  s.  c o  m*/
    try {
        FileInputStream fstream = new FileInputStream(path);
        DataInputStream in = new DataInputStream(fstream);
        br = new BufferedReader(new InputStreamReader(in));
        String strLine;
        int count = 0;
        while ((strLine = br.readLine()) != null) {
            Assert.assertEquals("Comparing the values", val, strLine);
            count++;
        }
        return count;
    } catch (Exception e) {
        return -1;
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
            }
        }
    }
}

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

/** convert file content to a string.
 *
 * @param file The file to open/*  www  .  j  av 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:hu.unideb.inf.rdfizers.rpm.ModelBuilder.java

private ModelBuilder(InputStream is, String uri) {
    in = new DataInputStream(is);
    this.uri = uri;
}

From source file:com.github.ambry.utils.UtilsTest.java

@Test
public void testReadStrings() throws IOException {
    // good case/*w w w. j a  v  a2s  .c o m*/
    ByteBuffer buffer = ByteBuffer.allocate(10);
    buffer.putShort((short) 8);
    String s = getRandomString(8);
    buffer.put(s.getBytes());
    buffer.flip();
    String outputString = Utils.readShortString(new DataInputStream(new ByteBufferInputStream(buffer)));
    Assert.assertEquals(s, outputString);
    // 0-length
    buffer.rewind();
    buffer.putShort(0, (short) 0);
    outputString = Utils.readShortString(new DataInputStream(new ByteBufferInputStream(buffer)));
    Assert.assertTrue(outputString.isEmpty());

    // failed case
    buffer.rewind();
    buffer.putShort((short) 10);
    buffer.put(s.getBytes());
    buffer.flip();
    try {
        outputString = Utils.readShortString(new DataInputStream(new ByteBufferInputStream(buffer)));
        Assert.assertTrue(false);
    } catch (IllegalArgumentException e) {
        Assert.assertTrue(true);
    }
    buffer.rewind();
    buffer.putShort(0, (short) -1);
    try {
        outputString = Utils.readShortString(new DataInputStream(new ByteBufferInputStream(buffer)));
        Assert.fail("Should have encountered exception with negative length.");
    } catch (IllegalArgumentException e) {
    }

    // good case
    buffer = ByteBuffer.allocate(40004);
    buffer.putInt(40000);
    s = getRandomString(40000);
    buffer.put(s.getBytes());
    buffer.flip();
    outputString = Utils.readIntString(new DataInputStream(new ByteBufferInputStream(buffer)),
            StandardCharsets.UTF_8);
    Assert.assertEquals(s, outputString);
    // 0-length
    buffer.rewind();
    buffer.putInt(0, 0);
    outputString = Utils.readShortString(new DataInputStream(new ByteBufferInputStream(buffer)));
    Assert.assertTrue(outputString.isEmpty());

    // failed case
    buffer.rewind();
    buffer.putInt(50000);
    buffer.put(s.getBytes());
    buffer.flip();
    try {
        outputString = Utils.readIntString(new DataInputStream(new ByteBufferInputStream(buffer)),
                StandardCharsets.UTF_8);
        fail("Should have failed");
    } catch (IllegalArgumentException e) {
        // expected.
    }

    buffer.rewind();
    buffer.putInt(0, -1);
    try {
        Utils.readIntString(new DataInputStream(new ByteBufferInputStream(buffer)), StandardCharsets.UTF_8);
        Assert.fail("Should have encountered exception with negative length.");
    } catch (IllegalArgumentException e) {
        // expected.
    }
}

From source file:gridool.util.xfer.RecievedFileWriter.java

public final void handleRequest(@Nonnull final SocketChannel inChannel, @Nonnull final Socket socket)
        throws IOException {
    final StopWatch sw = new StopWatch();
    if (!inChannel.isBlocking()) {
        inChannel.configureBlocking(true);
    }/*from  w  ww  . jav a 2 s .  co  m*/

    InputStream in = socket.getInputStream();
    DataInputStream dis = new DataInputStream(in);

    String fname = IOUtils.readString(dis);
    String dirPath = IOUtils.readString(dis);
    long len = dis.readLong();
    boolean append = dis.readBoolean();
    boolean ackRequired = dis.readBoolean();
    boolean hasAdditionalHeader = dis.readBoolean();
    if (hasAdditionalHeader) {
        readAdditionalHeader(dis, fname, dirPath, len, append, ackRequired);
    }

    final File file;
    if (dirPath == null) {
        file = new File(baseDir, fname);
    } else {
        File dir = FileUtils.resolvePath(baseDir, dirPath);
        file = new File(dir, fname);
    }

    preFileAppend(file, append);
    final FileOutputStream dst = new FileOutputStream(file, append);
    final String fp = file.getAbsolutePath();
    final ReadWriteLock filelock = accquireLock(fp, locks);
    final FileChannel fileCh = dst.getChannel();
    final long startPos = file.length();
    try {
        NIOUtils.transferFully(inChannel, 0, len, fileCh); // REVIEWME really an atomic operation?
    } finally {
        IOUtils.closeQuietly(fileCh, dst);
        releaseLock(fp, filelock, locks);
        postFileAppend(file, startPos, len);
    }
    if (ackRequired) {
        OutputStream out = socket.getOutputStream();
        DataOutputStream dos = new DataOutputStream(out);
        dos.writeLong(len);
        postAck(file, startPos, len);
    }

    if (LOG.isDebugEnabled()) {
        SocketAddress remoteAddr = socket.getRemoteSocketAddress();
        LOG.debug("Received a " + (append ? "part of file '" : "file '") + file.getAbsolutePath() + "' of "
                + len + " bytes from " + remoteAddr + " in " + sw.toString());
    }
}