• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Type conversion between Bytes and Strings

 
lance sykes
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why would the values printed at the bottom of the script be different? Also this works fine on some OS's but not on others???

String contentType = request.getContentType();
System.out.println("Content type is :: " +contentType);
if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
DataInputStream in = new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();

byte dataBytes[] = new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;
while (totalBytesRead < formDataLength) {
byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
totalBytesRead += byteRead;
}

String file = new String(dataBytes);

out.println(file.getBytes().length);
out.println(dataBytes.length);

Why would these give different results???
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64994
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch, lance.

Please take the time to choose the appropriate forum for your questions. This forum is devoted to questions on JSP technology. As your question is not JSP-specific, I've moved it for you to the Java in General (intermediate) forum.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The conversion between raw bytes and characters is done according to an encoding -- a two-way mapping. There is more than one possible encoding: in fact, there are many. When you create a String using "new String(byte[])," the local machine's default encoding is used. That may or may not be the same encoding as was used by the original data; if these don't match, then the two numbers you're printing may not match. String does have a constructor that lets you specify an encoding.

The HTTP headers will often tell you the "Content-encoding" of the data included.
 
lance sykes
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks...I thought this may be the case but was unsure how to view the encoding....thankyou for the insight
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic