Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
I'm looking for a hash function that: Hashes textual strings well (e.g. few collisions) Is written in Java, and widely used Bonus: works on several fields (instead of me concatenating them and applying the hash on the concatenated string) Bonus: Has a 128-bit variant. Bonus: Not CPU intensive.
We have a system where customers, mainly European enter texts (in UTF-8) that has to be distributed to different systems, most of them accepting UTF-8, but now we must also distribute the texts to a US system which only accepts US-Ascii 7-bit So now we'll need to translate all European characters to the nearest US-Ascii. Is there any Java libraries to help with this task? Right now we've just...
I am constructing an array of bytes in java and I don't know how long the array will be. I want some tool like Java's StringBuffer that you can just call .append(byte b) or .append(byte[] buf) and have it buffer all my bytes and return to me a byte array when I'm done. Is there a class that does for bytes what StringBuffer does for Strings? It does not look like the ByteBuffer class is wha...
In Python you can use StringIO for a file-like buffer for character data. Memory-mapped file basically does similar thing for binary data, but it requires a file that is used as the basis. Does Python have a file object that is intended for binary data and is memory only, equivalent to Java's ByteArrayOutputStream? The use-case I have is I want to create a ZIP file in memory, and ZipFile requi...
I have a function that takes an object of a certain type, and a PrintStream to which to print, and outputs a representation of that object. How can I capture this function's output in a String? Specifically, I want to use it as in a toString method.
I have been tearing my hair out on this and thus I am looks for some help . I have a loop of code that performs the following //imports ommitted public void afterPropertiesSet() throws Exception{ //building of URL list ommitted // urlMap is a HashMap <String,String> created and populated just prior for ( Object urlVar : urlMap.keySet() ){ String myURLvar = urlMap.ge...
I am having a requirement wherein i have to create a zip file from a list of available files. The files are of different types like txt,pdf,xml etc.I am using java util classes to do it. The requirement here is to maintain a maximum file size of 5 mb. I should select the files from list based on timestamp, add the files to zip until the zip file size reaches 5 mb. I should skip the remaining ...
How can I create an InputStream object from a XML Document or Node object to be used in xstream? I need to replace the ??? with some meaningful code. Thanks. Document doc = getDocument(); InputStream is = ???; MyObject obj = (MyObject) xstream.fromXML(is);
We have this use case where we would like to compress and store objects (in-memory) and decompress them as and when required. The data we want to compress is quite varied, from float vectors to strings to dates. Can someone suggest any good compression technique to do this ? We are looking at ease of compression and speed of decompression as the most important factors. Thanks.
I want to read data from file and unmarshal it to Parcel. In documentation it is not clear, that FileInputStream has method to read all its content. To implement this, I do folowing: FileInputStream filein = context.openFileInput(FILENAME); int read = 0; int offset = 0; int chunk_size = 1024; int total_size = 0; ArrayList<byte[]> chunks = new ArrayList<byte[]>(); chunks.add(new ...
I would like to know that if java/scala has the "string object that could act as file" as StringIO in python ? I figure that it would be better than writing and reading alot of temporary file. I prefer scala but java one should be fine too.
I have a Java class, where I'm reading data in via an InputStream byte[] b = null; try { b = new byte[in.available()]; in.read(b); } catch (IOException e) { e.printStackTrace(); } It works perfectly when I run my app from the IDE (Eclipse). But when I export my project and it's packed in a JAR, the read command doesn't read all the data. How could I f...
Not sure about how I am supposed to do this. Any help would be appreciated
I am about to write junit tests for a XML parsing Java class that outputs directly to an OutputStream. For example xmlWriter.writeString("foo"); would produce something like <aTag>foo</aTag> to be written to the outputstream held inside the XmlWriter instance. The question is how to test this behaviour. One solution would of course be to let the OutputStream be a FileOutputStream an...
I'm making a SOAP request with cfhttp due to SSL certificates to retrieve a document. We have limited access to the server, so I'm not sure if we can adjust the server to get the certificats added to the CF keystore. (http://www.coldfusionmuse.com/index.cfm/2005/01/29/keystore) The responseBody returns a ByteArrayOutputStream which holds the content of the soap message and document contents (...
I have a REST webservice that listens to POST requests and grabs hold of an XML payload from the client and stores it initially as an InputStream i.e. on the Representation object you can call getStream(). I want to utilise the XML held in the InputStream and I am begining to think it would be wise to persist it, so I can interrogate the data multiple times - as once you read through it, the o...
Is this: ByteBuffer buf = ByteBuffer.allocate(1000); ...the only way to initialize a ByteBuffer? What if I have no idea how many bytes I need to allocate..? Edit: More details: I'm converting one image file format to a TIFF file. The problem is the starting file format can be any size, but I need to write the data in the TIFF to little endian. So I'm reading the stuff I'm eventually going...
I have a byte array I want to assign as follows: First byte specifies the length of the string: (byte)string.length() 2nd - Last bytes contain string data from string.getBytes() Other than using a for loop, is there a quick way to initialize a byte array using bytes from two different variables?
In Java, I have a method public int getNextFrame( byte[] buff ) that reads from a file into the buffer and returns the number of bytes read. I am reading from .MJPEG that has a 5byte value, say "07939", followed by that many bytes for the jpeg. The problem is that the JPEG byte size could overflow the buffer. I cannot seem to find a neat solution for the allocation. My goal is to not create...
What does this statement, "Closing a ByteArrayOutputStream has no effect" (http://java.sun.com/javase/6/docs/api/java/io/ByteArrayOutputStream.html#close()) mean? I want to make sure the memory in ByteArrayOutputStream gets released. Does ByteArrayOutputStream.close() really release the memory? Thanks.
Lazy programmer alert. :) Cassandra stores column values as bytes (Java example). Specifying a LongType comparator compares those bytes as a long. I want the value of a long into a Cassandra-friendly byte[]. How? I poked around for awhile. I think you people can help me faster. EDIT: Both Alexander and Eli's answers agreed with this reverse transformation. Thanks!
  /*
   * Copyright 1994-2006 Sun Microsystems, Inc.  All Rights Reserved.
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   *
   * This code is free software; you can redistribute it and/or modify it
   * under the terms of the GNU General Public License version 2 only, as
   * published by the Free Software Foundation.  Sun designates this
   * particular file as subject to the "Classpath" exception as provided
   * by Sun in the LICENSE file that accompanied this code.
  *
  * This code is distributed in the hope that it will be useful, but WITHOUT
  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  * version 2 for more details (a copy is included in the LICENSE file that
  * accompanied this code).
  *
  * You should have received a copy of the GNU General Public License version
  * 2 along with this work; if not, write to the Free Software Foundation,
  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  *
  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  * CA 95054 USA or visit www.sun.com if you need additional information or
  * have any questions.
  */
 
 package java.io;
 
This class implements an output stream in which the data is written into a byte array. The buffer automatically grows as data is written to it. The data can be retrieved using toByteArray() and toString().

Closing a ByteArrayOutputStream has no effect. The methods in this class can be called after the stream has been closed without generating an IOException.

Author(s):
Arthur van Hoff
Since:
JDK1.0
 
 
 public class ByteArrayOutputStream extends OutputStream {

    
The buffer where data is stored.
 
     protected byte buf[];

    
The number of valid bytes in the buffer.
 
     protected int count;

    
Creates a new byte array output stream. The buffer capacity is initially 32 bytes, though its size increases if necessary.
 
     public ByteArrayOutputStream() {
         this(32);
     }

    
Creates a new byte array output stream, with a buffer capacity of the specified size, in bytes.

Parameters:
size the initial size.
Throws:
java.lang.IllegalArgumentException if size is negative.
 
     public ByteArrayOutputStream(int size) {
         if (size < 0) {
             throw new IllegalArgumentException("Negative initial size: "
                                                + size);
         }
          = new byte[size];
     }

    
Writes the specified byte to this byte array output stream.

Parameters:
b the byte to be written.
 
     public synchronized void write(int b) {
         int newcount =  + 1;
         if (newcount > .) {
              = Arrays.copyOf(, Math.max(. << 1, newcount));
         }
         [] = (byte)b;
          = newcount;
     }

    
Writes len bytes from the specified byte array starting at offset off to this byte array output stream.

Parameters:
b the data.
off the start offset in the data.
len the number of bytes to write.
    public synchronized void write(byte b[], int offint len) {
        if ((off < 0) || (off > b.length) || (len < 0) ||
            ((off + len) > b.length) || ((off + len) < 0)) {
            throw new IndexOutOfBoundsException();
        } else if (len == 0) {
            return;
        }
        int newcount =  + len;
        if (newcount > .) {
             = Arrays.copyOf(, Math.max(. << 1, newcount));
        }
        System.arraycopy(bofflen);
         = newcount;
    }

    
Writes the complete contents of this byte array output stream to the specified output stream argument, as if by calling the output stream's write method using out.write(buf, 0, count).

Parameters:
out the output stream to which to write the data.
Throws:
IOException if an I/O error occurs.
    public synchronized void writeTo(OutputStream outthrows IOException {
        out.write(, 0, );
    }

    
Resets the count field of this byte array output stream to zero, so that all currently accumulated output in the output stream is discarded. The output stream can be used again, reusing the already allocated buffer space.

    public synchronized void reset() {
         = 0;
    }

    
Creates a newly allocated byte array. Its size is the current size of this output stream and the valid contents of the buffer have been copied into it.

Returns:
the current contents of this output stream, as a byte array.
See also:
size()
    public synchronized byte toByteArray()[] {
        return Arrays.copyOf();
    }

    
Returns the current size of the buffer.

Returns:
the value of the count field, which is the number of valid bytes in this output stream.
See also:
count
    public synchronized int size() {
        return ;
    }

    
Converts the buffer's contents into a string decoding bytes using the platform's default character set. The length of the new String is a function of the character set, and hence may not be equal to the size of the buffer.

This method always replaces malformed-input and unmappable-character sequences with the default replacement string for the platform's default character set. The java.nio.charset.CharsetDecoder class should be used when more control over the decoding process is required.

Returns:
String decoded from the buffer's contents.
Since:
JDK1.1
    public synchronized String toString() {
        return new String(, 0, );
    }

    
Converts the buffer's contents into a string by decoding the bytes using the specified charsetName. The length of the new String is a function of the charset, and hence may not be equal to the length of the byte array.

This method always replaces malformed-input and unmappable-character sequences with this charset's default replacement string. The java.nio.charset.CharsetDecoder class should be used when more control over the decoding process is required.

Parameters:
charsetName the name of a supported charset
Returns:
String decoded from the buffer's contents.
Throws:
UnsupportedEncodingException If the named charset is not supported
Since:
JDK1.1
    public synchronized String toString(String charsetName)
        throws UnsupportedEncodingException
    {
        return new String(, 0, charsetName);
    }

    
Creates a newly allocated string. Its size is the current size of the output stream and the valid contents of the buffer have been copied into it. Each character c in the resulting string is constructed from the corresponding element b in the byte array such that:
     c == (char)(((hibyte & 0xff) << 8) | (b & 0xff))
 

Deprecated:
This method does not properly convert bytes into characters. As of JDK 1.1, the preferred way to do this is via the toString(String enc) method, which takes an encoding-name argument, or the toString() method, which uses the platform's default character encoding.
Parameters:
hibyte the high byte of each resulting Unicode character.
Returns:
the current contents of the output stream, as a string.
See also:
size()
toString(java.lang.String)
toString()
    @Deprecated
    public synchronized String toString(int hibyte) {
        return new String(hibyte, 0, );
    }

    
Closing a ByteArrayOutputStream has no effect. The methods in this class can be called after the stream has been closed without generating an IOException.

    public void close() throws IOException {
    }
New to GrepCode? Check out our FAQ X