My task is:
Clients connect to ServerSocket and send files with any encoding what they want(UTF-8, ISO-8859-5, CP1251 e.g.).
When Server receive file content, script must insert it into MySQL.
As the encoding can be different, I need save file content like ByteArray(?).
Byt I dont know how get ByteArray from Socket.getInputStream().
Please help with this.
Thanks in advance!
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] tmp = new byte[4096];
int ret = 0;
while((ret = inputStream.read(tmp)) > 0)
{
bos.write(tmp, 0, ret);
}
byte[] myArray = bos.toByteArray();
Commons IO - http://commons.apache.org/io/
toByteArray(Reader input, String encoding)
Get the contents of a Reader as a byte[] using the specified character encoding.
http://commons.apache.org/io/api-release/org/apache/commons/io/IOUtils.html
Related
I am writing a web service in JAVA using Apache CXF.
So, I have a method whose prototype is following:
public Response upload(#Multipart("id") int Id,
#Multipart("file") Attachment attachment) {
Now, I want to convert this attachment to byte[] . How can I do it?
Here is how you can read the content of the attachment and store it inside a byte array. Alternatively you can write directly to an OutputStream and skip the conversion to byte[].
DataHandler dataHandler = attachment.getDataHandler();
final byte[] data;
try (InputStream inputStream = dataHandler.getInputStream()) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
final byte[] buffer = new byte[4096];
for (int read = inputStream.read(buffer); read > 0; read = inputStream.read(buffer)) {
outputStream.write(buffer, 0, read);
}
data = outputStream.toByteArray();
}
//todo write data to BLOB
If you want to be more memory efficient or if the attachment does not fit into memory, you can write directly to the blob's output stream. Just replace the ByteArrayOutputStream with OutputStream outputStream = blob.setBinaryStream(1);
I have a FileOutputStream in java that is reading the contents of UDP packets and saving them to a file. At the end of reading them, I sometimes want to convert the encoding of the file. The problem is that currently when doing this, it just ends up doubling all the contents of the file. The only workaround that I could think to do would be to create a temp file with the new encoding and then save it as the original file, but this seems too hacky.
I must be just overlooking something in my code:
if(mode.equals("netascii")){
byte[] convert = new byte[(int)file.length()];
FileInputStream input = new FileInputStream(file);
input.read(convert);
String temp = new String(convert);
convert = Charset.forName("US-ASCII").encode(temp).array();
fos.write(convert);
}
JOptionPane.showMessageDialog(frame, "Read Successful!");
fos.close();
}
Is there anything suspect?
Thanks in advance for any help!
The problem is the array of bytes you've read from the InputStream will be converted as if its ascii chars, which I'm assuming its not. Specify the InputStream encoding when converting its bytes to String and you'll get a standard Java string.
I've assumed UTF-16 as the InputStream's encoding here:
byte[] convert = new byte[(int)file.length()];
FileInputStream input = new FileInputStream(file);
// read file bytes until EOF
int r = input.read(convert);
while(r!=-1) r = input.read(convert,r,convert.length);
String temp = new String(convert, Charset.forName("UTF-16"));
I am using this approach for storing data in a file from responce of Server.
ByteArrayOutputStream outstream = new ByteArrayOutputStream();
response.getEntity().writeTo(outstream);
byte[] responseBody = outstream.toByteArray();
String data = new String(responseBody);
FileOutputStream out = new FileOutputStream(new File(my_path));
out.write(data.getBytes());
out.flush();
out.close();
It's working fine and my file gets created and size of it is 3786 bytes.
Now consider this ,
ByteArrayOutputStream outstream = new ByteArrayOutputStream();
response.getEntity().writeTo(outstream);
byte[] responseBody = outstream.toByteArray();
FileOutputStream out = new FileOutputStream(new File(my_path));
out.write(responseBody);
out.flush();
out.close();
it gives filesize of 1993 bytes.
Can anybody help me understand this , Does this new String(responseBody) do something to responcebytes like some encoding ?
Any help would be appreciated.
Yes, constructing a String from bytes decodes the bytes according to the current default character encoding (if one is not explicitly specified). Also String.getBytes() does the same in reverse (and may not necessarily produce the same sequence of bytes that was used to create it).
A String holds text. If your data is raw binary data and is intended to be treated as such, you should not be storing it in a String, you should be storing it in a byte[].
There is no need to have String data at all in that first bit, just write the byte[] to the file:
byte[] responseBody = outstream.toByteArray();
String data = new String(responseBody);
...
out.write(data.getBytes());
Can just be:
byte[] responseBody = outstream.toByteArray();
...
out.write(responseBody);
I know that there are some similar questions in the site, but they could not provide me a helpful answer. What is the best/most efficient way to read a .bin file in Java line by line? Which classes and methods should someone use to open it and get the data? Could Bufferedreader do the job or is it only for text files;
Binary file don't have lines, but you must know the format of the file to know what structure exists (headers, structs,etc) and write a parser.
You can use BufferedInputStream, see the following:
http://www.javapractices.com/topic/TopicAction.do?Id=245
Read structured data from binary file -?
This should do it.
public byte[] readFromStream(InputStream inputStream) throws Exception
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
byte[] data = new byte[4096];
int count = inputStream.read(data);
while(count != -1)
{
dos.write(data, 0, count);
count = inputStream.read(data);
}
return baos.toByteArray();
}
I'm compressing a string using PHP's gzcompress() function:
http://us2.php.net/manual/en/function.gzcompress.php
I'd like to take the output from the PHP compression function and decompress the string in Java. Can anyone send me down the right path?
Thanks so much!
have a look to GZIPInputStream:
GZIPInputStream gzipInputStream = new GZIPInputStream(new FileInputStream(inFilename));
byte[] buf = new byte[1024];
int len;
while ((len = gzipInputStream.read(buf)) > 0) {
// buf contains uncompressed data
}
This is very old, but it might just contain the right info to get you started: http://java.sun.com/developer/technicalArticles/Programming/compression/
Put the data into a ByteArrayInputStream, then you should be able to decode it with GZipInputStream.
To get the bytes out of the String, try getBytes("ISO-8859-1"). This encoding won't change the incoming bytes.