aspose file tools*
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
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: 61601
    
  67

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: 24187
    
  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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Type conversion between Bytes and Strings