开发者

Writing a string to an OutputStream without using int onebyte

开发者 https://www.devze.com 2023-02-08 15:48 出处:网络
This is a total beginner q开发者_如何转开发uestion, I\'ve spent the past hour searching both stackoverflow and Google, but I haven\'t found what I\'m looking for, hopefully someone here can point me i

This is a total beginner q开发者_如何转开发uestion, I've spent the past hour searching both stackoverflow and Google, but I haven't found what I'm looking for, hopefully someone here can point me in the right direction.

I'm trying to write a string to an OutputStream, which I will then use to write data to a MySQL database. I've successfully retrieved data from a MySQL (from a .php, implementing JSON and RESTful), so I have some idea of what I'm doing, I think. I'm creating a method which will take a string and return an output stream, and I'm having trouble writing to an output stream, because when I try to initialize one, it creates an anonymous inner class with the write(int oneByte) method. That's not what I want.

private static OutputStream convertStringtoStream(String string) {
    byte[] stringByte = string.getBytes();
    OutputStream os = new OutputStream() {

        @Override
        public void write(int oneByte) throws IOException {
            /** I'd rather this method be something like
            public void write(byte[] bytes), but it requires int oneByte*/
        }
    };
    //return os here
}

As you can see, I want to write to my OutputStream with the buffer, not a single byte. I'm sure this is simple question, but I've not been able to find an answer, or even sample code which does what I want. If someone could point me in the right direction I'd really appreciate it. Thanks.


Your method could look like this, but I'm not sure what it would accomplish. How would you use the returned OutputStream?

private static OutputStream convertStringtoStream(String string) {
    byte[] stringByte = string.getBytes();
    ByteArrayOutputStream bos = new ByteArrayOutputStream(string.length());
    bos.write(stringByte);
    return bos;
}

Also, note that using String.getBytes() might get you into trouble in the long run because it uses the system's default encoding. It's better to choose an explicit encoding and use the String.getBytes(Charset) method.


Instead of using the abstract OutputStream class, you might want to use ByteArrayOutputStream which allows you to write a buffer. Even better perhaps would be ObjectOutputStream which would allow you to write string directly since string is serializable. Hope that helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号