• 0

WHILE loops and InputStreams


Question

18 answers to this question

Recommended Posts

  • 0


ByteArrayInputStream is = ...;
ByteArrayOutputStream os = ...;
byte[] buf = new byte[4096];
int read;
while ((read=is.read(buf, 0, 4096)) {
//Do something with contents of buf
//Like write to a ByteArrayOutputStream
os.write(buf, 0, read);
}
os.toByteArray();
[/CODE]

Of course you can use a third party library such as Apache commons-io and its IOUtils class to read the whole thing without a loop. Larger buffer sizes may be beneficial too, but it may just depend on what you're doing with what you're reading.

  • 0
  On 01/12/2012 at 08:56, kjordan2001 said:


ByteArrayInputStream is = ...;
ByteArrayOutputStream os = ...;
byte[] buf = new byte[4096];
int read;
while ((read=is.read(buf, 0, 4096)) {
//Do something with contents of buf
//Like write to a ByteArrayOutputStream
os.write(buf, 0, read);
}
os.toByteArray();
[/CODE]

Of course you can use a third party library such as Apache commons-io and its IOUtils class to read the whole thing without a loop. Larger buffer sizes may be beneficial too, but it may just depend on what you're doing with what you're reading.

cheers :p will have to try it .... im just trying to read 256b nothing huge

  • 0
  On 01/12/2012 at 08:56, kjordan2001 said:


ByteArrayInputStream is = ...;
ByteArrayOutputStream os = ...;
byte[] buf = new byte[4096];
int read;
while ((read=is.read(buf, 0, 4096)) {
//Do something with contents of buf
//Like write to a ByteArrayOutputStream
os.write(buf, 0, read);
}
os.toByteArray();
[/CODE]

Of course you can use a third party library such as Apache commons-io and its IOUtils class to read the whole thing without a loop. Larger buffer sizes may be beneficial too, but it may just depend on what you're doing with what you're reading.

refering back to this .... how do I write information to the new byte xD i have never worked with bytes before xD , obviously i see your write thing ...but I dont understand it so im not going to use it xD do i need to byte up a string and then add it to the new byte

  • 0

what would i need to do to this ... to send and receive just bytes... the whole point is to send the bytes and then it converted into a string on the other side (this is to sort out a previous issue I have with sending encrypted strings and them not keeping formating )


import java.io.*;
import java.net.*;
public class chatServer
{
public static void main (String[] args) throws IOException
{
ServerSocket serverSocket = null;

try
{
serverSocket = new ServerSocket (4444);
}
catch (IOException e)
{
System.err.println ("Could not listen on port: 4444.");
System.exit (1);
}

System.out.println ("Server - Listening on port 4444");
Socket clientSocket = null;

try
{
clientSocket = serverSocket.accept ();
}
catch (IOException e)
{
System.err.println ("Accept failed."); System.exit(1);
}

PrintWriter out = new PrintWriter (clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader (new InputStreamReader (clientSocket.getInputStream ()));
String toClient, fromClient;
toClient = "Hello";
System.out.println ("Server Message: " + toClient);
out.println (toClient);
fromClient = in.readLine ();
System.out.println ("Client Message: " + fromClient);
out.close ();
in.close ();
clientSocket.close ();
serverSocket.close ();
}
}
[/CODE]

  • 0


import java.io.*;
import java.net.*;
public class chatServer
{
public static void main (String[] args) throws IOException
{
ServerSocket serverSocket = null;

try
{
serverSocket = new ServerSocket (4444);
}
catch (IOException e)
{
System.err.println ("Could not listen on port: 4444.");
System.exit (1);
}

System.out.println ("Server - Listening on port 4444");
Socket clientSocket = null;

try
{
clientSocket = serverSocket.accept ();
}
catch (IOException e)
{
System.err.println ("Accept failed."); System.exit(1);
}

PrintWriter out = new PrintWriter (clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader (new InputStreamReader (clientSocket.getInputStream ()));
String toClient, fromClient;
toClient = "Hello";
System.out.println ("Server Message: " + toClient);
out.println (toClient);
CharArrayWriter os = new CharArrayWriter();
char[] buf = new char[4096];
int read;
while ((read=in.read(buf, 0, 4096)) {
os.write(buf, 0, read);
}
fromClient = os.toString();
System.out.println ("Client Message: " + fromClient);
out.close ();
in.close ();
clientSocket.close ();
serverSocket.close ();
}
}
[/CODE]

Since you're just passing strings and using a BufferedReader which is character specific, I've change it to a CharArrayWriter which is the equivalent of a ByteArrayOutputStream.

You may also want to call flush() on your PrintWriter to send the data to the client immediately if you'll be keeping it open longer than you are now.

  • 0
  On 05/12/2012 at 23:33, kjordan2001 said:

Since you're just passing strings and using a BufferedReader which is character specific, I've change it to a CharArrayWriter which is the equivalent of a ByteArrayOutputStream.

You may also want to call flush() on your PrintWriter to send the data to the client immediately if you'll be keeping it open longer than you are now.

ye it will be open longer I have code from that but I have stripped it down to bare basics just to play around and get to understanding it.... so lets say I wanted to send a massive string .... and recieve it all the other side in the same format as its sent ? what would I do ... I have written a huge encryption chat program and got it working except for the decrypting on the receiving side because when it sends the encrypted string the format never sends the same for some reason and I dunno why .... if I start a private chat with you would you be able to help me ?

I am really stuck REALLY stuck this problem of the encrypted string is just messing with me

  • 0

when i send an encrypted string it has a size of 256 .... when I receive it I get it in seval patches between 1-256 bits a time ... I know it works cause by pure chance it sent correct once and decrypted ... but every other time it messes up the spaces, lines, formatting ... only gets a certain amount and starts processing before the rest comes through etc

  • 0
  On 06/12/2012 at 00:50, SPEhosting said:

when i send an encrypted string it has a size of 256 .... when I receive it I get it in seval patches between 1-256 bits a time ... I know it works cause by pure chance it sent correct once and decrypted ... but every other time it messes up the spaces, lines, formatting ... only gets a certain amount and starts processing before the rest comes through etc

Are you calling flush() when you're sending? You were also using readline before instead of reading the whole string. Use the modified code I posted and that should read everything in. Not sure what happened to it, but the forum seems to have devoured the greater than 0 on the while loop (i.e. read until there's nothing left). You could also try using UDP which is less reliable on whether you'll know you sent the message fine, but it also sends it all at once. You also may want to develop a message format with a delimiter string and possibly a header that would let your receiver know the size of the message it should expect.

  • 0
  On 06/12/2012 at 03:50, kjordan2001 said:

Are you calling flush() when you're sending? You were also using readline before instead of reading the whole string. Use the modified code I posted and that should read everything in. Not sure what happened to it, but the forum seems to have devoured the greater than 0 on the while loop (i.e. read until there's nothing left). You could also try using UDP which is less reliable on whether you'll know you sent the message fine, but it also sends it all at once. You also may want to develop a message format with a delimiter string and possibly a header that would let your receiver know the size of the message it should expect.

ok i shall give that a go... but with your code it keeps telling me im trying to convert an int to a booleen ....obviously its something to do with the equals ... but ye it seems to dislike me ...

  • 0

also i copied and pasted your code in ? but im assume as you said it removed the another while statement you had previously.

I fixed the code, now just trying to get it to actually read the input...


import java.io.*;
import java.net.*;
public class chatServer
{
public static void main (String[] args) throws IOException
{
ServerSocket serverSocket = null;
try
{
serverSocket = new ServerSocket (4444);
}
catch (IOException e)
{
System.err.println ("Could not listen on port: 4444.");
System.exit (1);
}
System.out.println ("Server - Listening on port 4444");
Socket clientSocket = null;
try
{
clientSocket = serverSocket.accept ();
}
catch (IOException e)
{
System.err.println ("Accept failed."); System.exit(1);
}
PrintWriter out = new PrintWriter (clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader (new InputStreamReader (clientSocket.getInputStream ()));
String toClient, fromClient;
toClient = "Hello";
System.out.println ("Server Message: " + toClient);
out.println (toClient);
CharArrayWriter os = new CharArrayWriter();
char[] buf = new char[4096];
int read;
while ((read=in.read(buf, 0, 4096))==0) {
System.out.println("x
os.write(buf, 0, read);

}
fromClient = os.toString();
System.out.println ("Client Message: " + fromClient);
out.close ();
in.close ();
clientSocket.close ();
serverSocket.close ();
}
}
[/CODE]

  • 0
  On 06/12/2012 at 14:39, kjordan2001 said:

It should be while read greater than 0. For some reason Neowin is taking out the >.

while ((read > in.read(buf, , 4096))==) {

is that what you mean ? sorry I am not following what you are trying to say (i know what you are saying but I dont see where i have to put the > ... :p )

  • 0
  On 06/12/2012 at 16:19, kjordan2001 said:

while ((read=in.read(buf, , 4096)) > ) {

it works :D if I can get my final program working cause of you....then I want to have your babies ... O.o I dont know how but im sure science will help us

  • 0
  On 06/12/2012 at 16:19, kjordan2001 said:

while ((read=in.read(buf, , 4096)) > ) {

this is going good so far :D just one smmmallllll issue .... the code I have at the moment only works if the sending is within the while loop (which is fine) but its adding all the previous messages on to it :3 imma try flushing it but im pretty sure that will just clear everything except the last byte

  • 0
  On 07/12/2012 at 04:54, SPEhosting said:

this is going good so far :D just one smmmallllll issue .... the code I have at the moment only works if the sending is within the while loop (which is fine) but its adding all the previous messages on to it :3 imma try flushing it but im pretty sure that will just clear everything except the last byte

It's not something like you're re-using the CharArrayWriter instance without calling reset() on it, is it?

  • 0
  On 07/12/2012 at 16:47, kjordan2001 said:

It's not something like you're re-using the CharArrayWriter instance without calling reset() on it, is it?

it might be O.o .... im not that knowledgeable on all these things yet ... I only know whatI have used and i have never used the reset xD last year all my work was mainly GUI and logic based rather then using all the libraries :p i will look into this reset function .... I tried nulling it so javas garbage collection would handle it but that messed things up

  • 0
  On 07/12/2012 at 16:47, kjordan2001 said:

It's not something like you're re-using the CharArrayWriter instance without calling reset() on it, is it?

ok reset and all that works BUT OMG 2bytes are being added somewhere and I dont know why or how ... it says on the sending side its 256...then on the recieving side when it goes to decrypt it... its apprently 258 ...

This topic is now closed to further replies.
  • Posts

    • ...so more bloat is added (that naturally is always running in the background, using resources) that will report that you have a lot of bloat (and also a few more ads were also added but that has nothing to do with anything, right...).
    • Thank you for replying! Is MP600 also good? Where I'm looking they don't have MP700. I was also looking at Corsair T500, that comes with heatsink.
    • As someone who was born in 1980, I’m feeling this.
    • Amazon Deal: This Vifa Stockholm 2.0 is one of the best sounding bluetooth speakers by Sayan Sen A few days back we covered some great JBL bluetooth speaker deals across several of its popular models. The discounts are still live and you can check them out in this dedicated piece. Meanwhile for those who prefer more powerful home cinema sound systems, Nakamichi and Samsung are offering the Dragon and Shockwafe models, and the Q-series models, respectively, at their best ever prices. However, if you are someone who is looking for a bit of both, the portability of a bluetooth speaker and the fidelity of a good sounding hi-fi system then the Vifa Stockholm 2.0 Bluetooth Soundbar is something you should look at as it's currently a nice deal (purchase link under the specs table below). While you are not getting a subwoofer with the Vifa Stockholm as it is a 2.0 system, Vifa promises lows down to 42 Hz at +3dB and that should be pretty good for a device lacking a dedicated bass unit; it does pack passive radiators to help with the bass. The Stockholm 2.0 is praised for its sound quality (SQ) and one of the reasons behind it is becasue it has three-way drivers. The technical specifications of the Vifa Stockholm 2.0 Bluetooth Soundbar are given below: Specification Frequency Response 42 Hz – 20 kHz @ ±3 dB Materials Frame: One-piece die-cast aluminium; Enclosure: ABS reinforced; Grills: Kvadrat textile Connectivity Bluetooth® Qualcomm aptX™ HD audio; Wi-Fi Direct & networked (2.4 GHz); Wired optical or analog (3.5 mm mini-jack); USB-disk; Vifa®HOME, Vifa®LINK, Vifa®PLAY Driver Units Tweeter: 2 × 28 mm soft-dome drivers; Midrange: 2 × 80 mm aluminium-cone drivers; Woofer: 4 × 100 mm flat sandwich-cone drivers (force-balanced, backed by 4 passive radiators) Other Features Apple AirPlay & DLNA streaming; DSP signal processing; 6-channel high-performance power amplifier Get it at the link below: Vifa Stockholm 2.0 Bluetooth Soundbar, Nordic Design Soundbar, Smart APP Multi-Room System (Slate Black): $1156.99 (Sold and Shipped by Amazon US) This Amazon deal is US-specific and not available in other regions unless specified. If you don't like it or want to look at more options, check out the Amazon US deals page here. Get Prime (SNAP), Prime Video, Audible Plus or Kindle / Music Unlimited. Free for 30 days. As an Amazon Associate, we earn from qualifying purchases.
    • Explzh 9.81 by Razvan Serea Explzh is a free Windows archive manager for creating, extracting and managing archives. The program supports many different types of archives, including zip, 7z, rar, tar, ace, lzh, arj, cab, iso, img, msi, sfx and more. Apart from archive creation and extraction, you will also be able to verify compressed data for errors, initiate repair routines, split data into multiple items, and more. It additionally allows you to password protect your data and attach digital signatures to files. Key features of Explzh: Explorer-like GUI and operability. LHA, ZIP (ZIPX), JAR, CAB, RAR, TAR, TAR.XXX, 7z, ARJ, WIM, CHM, PE, HFS, NSIS Format Installer, ISO, InstallShield, MSI, and several other formats... Support for more archive formats by introducing the integrated archiver DLL. Self-extracting archive creation function that can create high-performance automatic installers. Digital signature addition function to created self-extracting archive. Office 2007 or later document compression / image optimization re-archiving function. Supports compression and decompression of Unicode file names. Supports compression and expansion exceeding 4GB. AES encryption function. You can create a robust secure ZIP encryption archive. Thumbnail function of image file. In-library file search function. . Equipped with archive file conversion function. File split function. The split file has a self-consolidation function, and can concatenate files larger than 4GB. (No need for batch file or connection software) UU (XX) Encode, Base64 decode function. FTP upload function Supports Windows 11 shell integration extended context menu. Explzh 9.81 changelog: Improved to send update notifications to the shell when making changes such as additional compression to existing zip and 7-zip files. This also updates the Explorer view of the open file in real time. (If the drop target feature is enabled, you can easily create an encrypted ZIP by dragging and dropping onto the ZIP icon while holding down the Ctrl key.) When the zip drop target setting is enabled, the "Compressed (zipped) Folder" item will be added to the "New" shell context menu if it does not already exist. Password manager bug fix: Fixed a bug that caused the app to crash when reading password.dat (password data) when changing authentication method. Updated to Visual Studio 2022 v.17.14.9. Download: Explzh 64-bit | Explzh 32-bit | ~6.0 MB (Freeware) Download: Explzh ARM64 | 5.9 MB View: Explzh Home Page | Screenshot | Themes Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • Week One Done
      Snake Doc earned a badge
      Week One Done
    • One Month Later
      Johnny Mrkvička earned a badge
      One Month Later
    • Week One Done
      Sender88 earned a badge
      Week One Done
    • Dedicated
      Daniel Pinto earned a badge
      Dedicated
    • Explorer
      DougQuaid went up a rank
      Explorer
  • Popular Contributors

    1. 1
      +primortal
      611
    2. 2
      Michael Scrip
      199
    3. 3
      ATLien_0
      190
    4. 4
      +FloatingFatMan
      138
    5. 5
      Xenon
      125
  • Tell a friend

    Love Neowin? Tell a friend!