• 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


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


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

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

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

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

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

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

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

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

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

    • Google Chrome 149.0.7827.156 (offline installer) by Razvan Serea The web browser is arguably the most important piece of software on your computer. You spend much of your time online inside a browser: when you search, chat, email, shop, bank, read the news, and watch videos online, you often do all this using a browser. Google Chrome is a browser that combines a minimal design with sophisticated technology to make the web faster, safer, and easier. Use one box for everything--type in the address bar and get suggestions for both search and Web pages. Thumbnails of your top sites let you access your favorite pages instantly with lightning speed from any new tab. Desktop shortcuts allow you to launch your favorite Web apps straight from your desktop. Chrome has many useful features built in, including automatic full-page translation and access to thousands of apps, extensions, and themes from the Chrome Web Store. Google Chrome is one of the best solutions for Internet browsing giving you high level of security, speed and great features. This update includes 33 security fixes. [N/A][516496659] Critical CVE-2026-12437: Use after free in WebShare. Reported by Google on 2026-05-25 [N/A][516947912] Critical CVE-2026-12438: Inappropriate implementation in WebView. Reported by Google on 2026-05-27 [N/A][519728275] Critical CVE-2026-12439: Use after free in Digital Credentials. Reported by Google on 2026-06-03 [N/A][519731619] Critical CVE-2026-12440: Use after free in DigitalCredentials. Reported by Google on 2026-06-03 [N/A][520157118] Critical CVE-2026-12441: Use after free in File Input. Reported by Google on 2026-06-05 [N/A][521950423] Critical CVE-2026-12442: Use after free in Passwords. Reported by Google on 2026-06-09 [N/A][522566295] Critical CVE-2026-12443: Use after free in Web Authentication. Reported by Google on 2026-06-11 [N/A][513160088] High CVE-2026-12444: Out of bounds read in Chromoting. Reported by Google on 2026-05-14 [N/A][513199795] High CVE-2026-12445: Use after free in Extensions. Reported by Google on 2026-05-14 [N/A][513313107] High CVE-2026-12446: Insufficient data validation in Passwords. Reported by Google on 2026-05-14 [N/A][513405023] High CVE-2026-12447: Heap buffer overflow in WebRTC. Reported by Google on 2026-05-15 [N/A][513458233] High CVE-2026-12448: Inappropriate implementation in WebView. Reported by Google on 2026-05-15 [N/A][513480539] High CVE-2026-12449: Use after free in Chromoting. Reported by Google on 2026-05-15 [N/A][514531776] High CVE-2026-12450: Inappropriate implementation in Media. Reported by Zhixin Tu on 2026-05-19 [N/A][514741076] High CVE-2026-12451: Use after free in DigitalCredentials. Reported by Google on 2026-05-19 [N/A][515462244] High CVE-2026-12452: Use after free in Downloads. Reported by Google on 2026-05-21 [N/A][516448843] High CVE-2026-12453: Insufficient validation of untrusted input in Input. Reported by Google on 2026-05-25 [N/A][516926968] High CVE-2026-12454: Race in Safe Browsing. Reported by Google on 2026-05-27 [N/A][517069848] High CVE-2026-12455: Use after free in Tab Strip. Reported by Google on 2026-05-27 [N/A][517124587] High CVE-2026-12456: Insufficient validation of untrusted input in Extensions. Reported by Google on 2026-05-27 [N/A][517153117] High CVE-2026-12457: Insufficient data validation in Extensions. Reported by Google on 2026-05-27 [N/A][517258337] High CVE-2026-12458: Incorrect security UI in Passwords. Reported by Google on 2026-05-27 [N/A][517406035] High CVE-2026-12459: Inappropriate implementation in Serial. Reported by Google on 2026-05-28 [N/A][517484284] High CVE-2026-12460: Insufficient policy enforcement in File System Access. Reported by Google on 2026-05-28 [N/A][517727318] High CVE-2026-12461: Out of bounds read in WebRTC. Reported by Google on 2026-05-29 [N/A][517916024] High CVE-2026-12462: Use after free in Media. Reported by Google on 2026-05-29 [N/A][518042749] High CVE-2026-12463: Inappropriate implementation in Views. Reported by Google on 2026-05-30 [N/A][519358344] High CVE-2026-12464: Use after free in Browser. Reported by Google on 2026-06-03 [N/A][520189702] High CVE-2026-12465: Insufficient validation of untrusted input in Metrics. Reported by Google on 2026-06-05 [N/A][520199394] High CVE-2026-12466: Heap buffer overflow in WebRTC. Reported by Google on 2026-06-05 [N/A][520202726] High CVE-2026-12467: Use after free in Extensions. Reported by Google on 2026-06-05 [N/A][521485244] High CVE-2026-12468: Inappropriate implementation in Updater. Reported by Google on 2026-06-08 [N/A][521618871] High CVE-2026-12469: Uninitialized Use in GPU. Reported by Google on 2026-06-09 Important to know! The offline installer links do not include the automatic update feature. Download web installer: Google Chrome Web 32-bit | Google Chrome 64-bit | Freeware Download: Google Chrome Offline Installer 64-bit | Direct Link | 131.0 MB Download: Google Chrome Offline Installer 32-bit | Direct Link | 119.0 MB Download page: Google Chrome Portable Download: Chrome ARM64 | Direct Link View: Chrome Website | Release Notes Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • they couldnt do W11 LTSC so the support lasts longer....
    • The fact that the pref is not enabled by default tells you that what you see is what you get...for now. Hopefully the final version will have all the quirks ironed out.
    • It's enterprise, not consumer. And "...affected scenarios involve third-party software..." Would be good to know that in headline, not way down in the article. Instead, you lead with Windows update, which is not very helpful and misleading, IMHO. Just saying.
  • Recent Achievements

    • Week One Done
      suprememobiles48 earned a badge
      Week One Done
    • One Month Later
      Windows Guy earned a badge
      One Month Later
    • One Month Later
      Prasann earned a badge
      One Month Later
    • Week One Done
      Prasann earned a badge
      Week One Done
    • First Post
      Dys Topia earned a badge
      First Post
  • Popular Contributors

    1. 1
      +primortal
      503
    2. 2
      +Edouard
      173
    3. 3
      PsYcHoKiLLa
      97
    4. 4
      Steven P.
      85
    5. 5
      ATLien_0
      71
  • Tell a friend

    Love Neowin? Tell a friend!