It's not a secret anymore!*
The moose likes Java in General and the fly likes Type conversion between Bytes and Strings Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Type conversion between Bytes and Strings" Watch "Type conversion between Bytes and Strings" New topic
Author

Type conversion between Bytes and Strings

lance sykes
Greenhorn

Joined: Jul 27, 2006
Posts: 2
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

Joined: Jan 10, 2002
Posts: 60765
    
  65

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.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

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.


[Jess in Action][AskingGoodQuestions]
lance sykes
Greenhorn

Joined: Jul 27, 2006
Posts: 2
Thanks...I thought this may be the case but was unsure how to view the encoding....thankyou for the insight
 
Don't get me started about those stupid light bulbs.
 
subject: Type conversion between Bytes and Strings
 
Similar Threads
JSP Page For Uploading a File to Destination Folder
error in uploading zip file
problem in uploading a file
Problem with displaying image using jsp
Large File Size Upload Problem