Byte Stream for Code Testing of Common Streams

Keywords: Java network Programming

Byte stream

Byte stream classes provide a rich environment for processing byte input/output. A byte stream can be of any other type
Objects are used together, including binary data. Such versatility makes byte streams important for many types of programs.
Since the byte stream classes are top-level in InputStream and OutputStream, we'll start by discussing these two classes.

InputStream

InputStream is an abstract class that defines the Java stream byte input pattern. All methods of this class raise an IOException exception under an error condition.

The Method of InputStream Definition

Method describe
int available( ) Returns the number of currently readable input bytes
void close( ) Close the input source. Reading after closing generates IOException exceptions
void mark(int numBytes) Place a tag at the current point of the input stream. The stream remains valid until numBytes are read
boolean markSupported( ) If the calling flow supports mark ()/reset (), it returns true
int read( ) If the next byte is readable, an integer is returned, and - 1 is returned when the end of the file is encountered.
int read(byte buffer[ ]) An attempt was made to read buffer.length bytes into the buffer and return the number of bytes actually read successfully. Return - 1 when encountering the end of the file
int read(byte buffer[ ], int offset,int numBytes) Trying to read numBytes from buffer[offset] in buffer, returning the number of bytes actually read. Return - 1 when encountering the end of the file
void reset( ) Reset the input pointer to the previously set flag
long skip(long numBytes) Ignore numBytes input bytes and return the number of bytes actually ignored

Output Stream

OutputStream is an abstract class that defines the stream byte output pattern. All methods of this class return a void value and raise an IOException exception in case of an error.
The Method of OutputStream Definition

Method describe
void close( ) Close the output stream. Closed write operations can produce IOException exceptions
void flush( ) Customize the output state so that each buffer is cleared, that is, refresh the output buffer
void write(int b) Write a single byte to the output stream. Note that the parameter is an integer, which allows you to call write () without converting the parameter to byte type.
void write(byte buffer[ ]) Write a complete byte array to an output stream
void write(byte buffer[ ], int offset,int numBytes) Write the contents of numBytes byte regions starting with buffer[offset]

FileInputStream

The FileInputStream class creates an InputStream class that can read bytes from a file. Its two commonly used constructors are as follows:

FileInputStream(String filepath)
FileInputStream(File fileObj)

They all raise FileNotFoundException exceptions. Here, filepath is the full name path of the file, and fileObj is the File object describing the file.
The following example creates two FileInputStreams classes that use the same disk file and each contains one of the above constructors:

FileInputStream f0 = new FileInputStream("/autoexec.bat")
File f = new File("/autoexec.bat");
FileInputStream f1 = new FileInputStream(f);

Although the first constructor may be more commonly used,
The second constructor allows you to examine the file further with the File method before assigning it to the input stream.

When a FileInputStream is created, it can be read publicly.
FileInputStream overloads six methods of the abstract class InputStream. The mark() and reset() methods are not overloaded. Any reset() attempt to use FileInputStream generates an IOException exception.
The following example shows how to read the subbounds of a single byte, byte array, and byte array. It also states
How to use available() to determine the number of bytes remaining and how to skip unnecessary bytes by skip(). The program reads its own source file, which must be in the current directory.

// Demonstrate FileInputStream.
import java.io.*;
class FileInputStreamDemo {
public static void main(String args[]) throws Exception {The first 17 Chapter Input/Output: Exploration java.jo 373
int size;
InputStream f =new FileInputStream("FileInputStreamDemo.java");
System.out.println("Total Available Bytes: " +(size = f.available()));
int n = size/40;
System.out.println("First " + n +" bytes of the file one read() at a time");

for (int i=0; i < n; i++) {
System.out.print((char) f.read());
}
System.out.println("\nStill Available: " + f.available());
System.out.println("Reading the next " + n +" with one read(b[])");

byte b[] = new byte[n];

if (f.read(b) != n) {
System.err.println("couldn't read " + n + " bytes.");
}
System.out.println(new String(b, 0, n));
System.out.println("\nStill Available: " + (size = f.available()));
System.out.println("Skipping half of remaining bytes with skip()");

f.skip(size/2);
System.out.println("Still Available: " + f.available());
System.out.println("Reading " + n/2 + " into the end of array");

if (f.read(b, n/2, n/2) != n/2) {
System.err.println("couldn't read " + n/2 + " bytes.");
}
System.out.println(new String(b, 0, b.length));
System.out.println("\nStill Available: " + f.available());
f.close();
}
}


//The following is the output of the program:
Total Available Bytes: 1433
First 35 bytes of the file one read() at a time
// Demonstrate FileInputStream.
im
Still Available: 1398
Reading the next 35 with one read(b[])
port java.io.*;
class FileInputS
Still Available: 1363
Skipping half of remaining bytes with skip()
Still Available: 682
Reading 17 into the end of array
port java.io.*;
read(b) != n) {
S
Still Available: 665

This deliberately created example illustrates three ways to read data, how to skip input, and how to check the number of data available in the stream.

FileOutput Stream

FileOutputStream creates a class OutputStream that can write bytes to a file. Its common constructors are as follows:

FileOutputStream(String filePath)
FileOutputStream(File fileObj)
FileOutputStream(String filePath, boolean append)

They can cause IOException or Security Exception exceptions. Here filePath is the full name path of the file.
fileObj is a File object that describes the file. If append is true, the file opens in search path mode.
The creation of FileOutputStream does not depend on the existence of a file. When creating an object, FileOutputStream creates it before opening the output file. In this case, if you try to open a read-only file, you will cause an IOException exception.

The following example creates a sample byte buffer. Mr. A forms a String object, and then uses the getBytes() method to take the byte array peer. Then three files are created. The first file1.txt will contain the bytes in the sample. The second file is file2.txt, which contains all bytes. The third and last file, file3.txt, contains only the last four
One-third.

Unlike FileInputStream class methods, all FileOutputStream class methods return a void type value. In case of an error, these methods will cause IOException exceptions.

// Demonstrate FileOutputStream.
import java.io.*;
class FileOutputStreamDemo {
public static void main(String args[]) throws Exception {
String source = "Now is the time for all good men\n"
+ " to come to the aid of their country\n"
+ " and pay their due taxes.";
byte buf[] = source.getBytes();
OutputStream f0 = new FileOutputStream("file1.txt");
for (int i=0; i < buf.length; i += 2) {
f0.write(buf[i]);
}
f0.close();
OutputStream f1 = new FileOutputStream("file2.txt");
f1.write(buf);
f1.close();
OutputStream f2 = new FileOutputStream("file3.txt");
f2.write(buf,buf.length-buf.length/4,buf.length/4);
f2.close();
}
}

Following is the content of each file after running the program.
First, file1.txt:
Nwi h iefralgo e
t oet h i ftercuty n a hi u ae.

Next, file2.txt:
Now is the time for all good men
to come to the aid of their country
and pay their due taxes.

Finally, file3.txt
nd pay their due taxes.

ByteArray Input Stream

ByteArray InputStream is an input stream that uses byte arrays as the source. This class has two constructors, each of which requires a byte array to provide the data source:

ByteArrayInputStream(byte array[ ])
ByteArrayInputStream(byte array[ ], int start, int numBytes)

Here, array is the input source. The second constructor creates an InputStream class, which is generated from a subset of byte arrays, starting with the character of the start specified index, and the length is determined by numBytes.
The following example creates two ByteArray InputStream and initializes them with the byte representation of the alphabet:

// Demonstrate ByteArrayInputStream.
import java.io.*;
class ByteArrayInputStreamDemo {
public static void main(String args[]) throws IOException {
String tmp = "abcdefghijklmnopqrstuvwxyz";
byte b[] = tmp.getBytes();
ByteArrayInputStream input1 = new ByteArrayInputStream(b);
ByteArrayInputStream input2 = new ByteArrayInputStream(b, 0,3);
}
}

The input1 object contains all the lowercase and lowercase letters in the alphabet, and input2 contains only the first three letters.
ByteArrayInputStream implements mark() and reset() methods. However, if mark() is not called, reset() sets a stream pointer at the beginning of the stream -- the first address of the byte array passed to the constructor.

The following example illustrates how to read the same input twice using the reset() method. In this case, we read the data and then use the small size.
Write and print "abc" in capital letters.

import java.io.*;
class ByteArrayInputStreamReset {
public static void main(String args[]) throws IOException {
String tmp = "abc";
byte b[] = tmp.getBytes();
ByteArrayInputStream in = new ByteArrayInputStream(b);
for (int i=0; i<2; i++) {
int c;
while ((c = in.read()) != -1) {
if (i == 0) {376 The first 2 Part Java library
System.out.print((char) c);
} else {
System.out.print(Character.toUpperCase((char) c));
}
}
System.out.println();
in.reset();
}
}
}

This example first reads each character from the stream and then prints it in lowercase. Then reset the stream and start reading from scratch.
This time, the letters are converted into capital letters before printing. The following is the output:
abc
ABC

ByteArray Output Stream

ByteArray Output Stream is an implementation that treats byte arrays as output streams. Byte Array Output Stream
There are two constructors, as follows:

ByteArrayOutputStream( )
ByteArrayOutputStream(int numBytes)

In the first form, a 32-byte buffer is generated. The second constructor generates a buffer with the same number of digits as the specified numBytes. Buffers are stored in the protected buf members of ByteArray Output Stream.

Buffer size increases automatically when needed.

The number of bytes saved by the buffer is saved by the protected count domain of ByteArray Output Stream.

The following example illustrates Byte Array Output Stream:
// Demonstrate ByteArrayOutputStream.

import java.io.*;
class ByteArrayOutputStreamDemo {
public static void main(String args[]) throws IOException {
ByteArrayOutputStream f = new ByteArrayOutputStream();
String s = "This should end up in the array";
byte buf[] = s.getBytes();
f.write(buf);
System.out.println("Buffer as a string");
System.out.println(f.toString());
System.out.println("Into array");
byte b[] = f.toByteArray();
for (int i=0; i<b.length; i++) {
System.out.print((char) b[i]);
}
System.out.println("\nTo an OutputStream()");
OutputStream f2 = new FileOutputStream("test.txt");
f.writeTo(f2);
f2.close();
System.out.println("Doing a reset");
f.reset();
for (int i=0; i<3; i++)
f.write('X');
System.out.println(f.toString());
}
}

After running the program, the following output is generated. Notice how the three X ends after calling reset().
Buffer as a string
This should end up in the array
Into array
This should end up in the array
To an OutputStream()
Doing a reset
XXX

This example writeTo() is a convenient method to write the content of f to test.txt, and check the content of the test.txt file generated in the previous example. The results are as follows:
This should end up in the array

Filtering byte stream

filtered stream is simply the packaging of the input stream (output stream) that transparently provides extended functionality at the bottom.
These streams are generally accessed by methods of ordinary classes (that is, a superclass of filtered streams). Typical extensions are buffering, character conversion and raw data conversion. These filtered byte streams are FilterInputStream and FilterOutputStream. Their constructors
The numbers are as follows:

FilterOutputStream(OutputStream os)
FilterInputStream(InputStream is)

These classes provide the same methods as the InputStream and OutputStream classes.

Buffer byte stream

For byte streams, buffered stream s extend a filter stream class by connecting memory buffers to input/output streams. This buffer allows Java to input/output multiple bytes at the same time, which improves program performance.
Because buffers are available, streams can be skipped, marked, and reset. The buffer byte stream classes are BufferedInputStream and BufferedOutputStream.

PushbackInputStream also implements buffer streams.
Buffered Input Stream
Buffering input/output is a very common performance optimization.

Java's BufferedInputStream class allows any
The InputStream class "wraps" into a buffer stream and improves its performance.
BufferedInputStream has two constructors:

BufferedInputStream(InputStream inputStream)
BufferedInputStream(InputStream inputStream, int bufSize)

The first form generates a buffer stream of default buffer length.

The second form of buffer size is passed in by bufSize. Several times the size of buffers, such as memory pages or disk blocks, can have a significant positive impact on execution performance.
But it depends on implementation. The optimal buffer length is generally associated with the host operating system, available memory space and machines.
Configuration is concerned.

Reasonable use of buffers does not require particularly complex operations. The average buffer size is 8192 bytes. It is usually a good way to set a smaller buffer for the input/output stream. In this way, low-level systems can be accessed from disk or network.
Read data blocks and store results in buffers. Therefore, even if you read byte data outside of InputStream at the same time, you can get fast storage operations in more than 99.9% of the time.

Buffering an input stream also provides a necessary basis for supporting backward movement within the stream of available buffers. In addition to the read() and skip() methods executed in any InputStream class, BufferedInputStream also supports mark() and skip() methods.
reset() method. BufferedInputStream.markSupported() returns true as a manifestation of this support.
The following example designs a scenario in which we can use mark() to remember where we are in the input stream and then use reset() to return to that location. This example illustrates how HTML entities refer to copyright information.
Condition. This reference begins with an ampersand ends with a semicolon (;), without any spaces. The example input consists of two & symbols to illustrate where reset() occurs and where it does not occur.

// Use buffered input.
import java.io.*;
class BufferedInputStreamDemo {
public static void main(String args[]) throws IOException {
String s = "This is a &copy; copyright symbol " +
"but this is &copy not.\n";
byte buf[] = s.getBytes();
ByteArrayInputStream in = new ByteArrayInputStream(buf);
BufferedInputStream f = new BufferedInputStream(in);
int c;
boolean marked = false;
while ((c = f.read()) != -1) {
switch(c) {
case '&':
if (!marked) {
f.mark(32);
marked = true;
} else {
marked = false;
}
break;
case ';':
if (marked) {
marked = false;
System.out.print("(c)");
} else
System.out.print((char) c);
break;
case ' ':
if (marked) {
marked = false;
f.reset();The first 17 Chapter Input/Output: Exploration java.jo 379
System.out.print("&");
} else
System.out.print((char) c);
break;
default:
if (!marked)
System.out.print((char) c);
break;
}}
}}

Note that this example uses mark(32), which saves the next 32 bytes read (this amount is sufficient for all entity references).

The following is the output of the program:
This is a © copyright symbol but this is &copy not.

Warning: The use of mark() in buffers is limited. This means that you can only define a parameter smaller than the size of the stream buffer for mark().

Buffered Output Stream
BufferedOutputStream is the same as any OutputStream except that an additional flush() method is used to ensure that the data buffer is written to the actual output device. Because BufferedOutputStream improves performance by reducing the time of system writing data, flush() method can be called to generate data to be written in buffer.

Unlike buffered input, buffered output does not provide additional functionality, and output buffers in Java are designed to improve performance.
Here are two constructors available:

BufferedOutputStream(OutputStream outputStream)
BufferedOutputStream(OutputStream outputStream, int bufSize)

The first form creates a buffer stream using a 512-byte buffer. In the second form, the size of the buffer is passed in by the bufSize parameter.
Pushback Input Stream
A novel use of buffering is push back. Pushback is used for input streams to allow bytes to be read and then returned (i.e., push back) to the stream.

The PushbackInputStream class implements this idea. It provides a machine.
To "peep" at what the input stream generates without being destroyed.
PushbackInputStream has two constructors:

PushbackInputStream(InputStream inputStream)
PushbackInputStream(InputStream inputStream, int numBytes)

The first form creates a stream object that allows a byte to be pushed back into the input stream.
The second form creates a

Push-back buffer flow with numBytes length buffer. It allows multiple bytes to be pushed back into the input stream.
In addition to having the same method as InputStream, PushbackInputStream provides unread() methods that represent
Next:

void unread(int ch)
void unread(byte buffer[ ])
void unread(byte buffer, int offset, int numChars)

The first form pushes back the low byte of ch, which will be the next byte returned by the subsequent call to read().
The second form returns bytes in the buffer buffer.

The third form pushes back the numChars from offset in buffer
Festival. If an attempt is made to return a byte when the push-back buffer is full, the IOException exception will be raised.
Java 2 has made some minor modifications to PushbackInputStream: it implements the skip() method.
The following example demonstrates how a programming language parser uses PushbackInputStream and unread() to handle the difference between the = = operator and the = operator.

// Demonstrate unread().
import java.io.*;
class PushbackInputStreamDemo {
public static void main(String args[]) throws IOException {
String s = "if (a == 4) a = 0;\n";
byte buf[] = s.getBytes();
ByteArrayInputStream in = new ByteArrayInputStream(buf);
PushbackInputStream f = new PushbackInputStream(in);
int c;
while ((c = f.read()) != -1) {
switch(c) {
case '=':
if ((c = f.read()) == '=')
System.out.print(".eq.");
else {
System.out.print("<-");
f.unread(c);
}
break;
default:
System.out.print((char) c);
break;
}}}}

The following is the output of the sample program. Note that = is replaced by ". eq" and = by "<-".

if (a .eq. 4) a <- 0;

Note: PushbackInputStream has the side effect of invalidating the mark() or reset() methods generated by InputStream.

Use markSupported() to check any stream classes you use mark ()/reset ().

SequenceInputStream

The SequenceInputStream class allows multiple InputStream streams to be connected. SequenceInputStream is constructed differently from any other InputStream. The SequenceInputStream constructor uses either a pair of InputStream or a pair of InputStream constructors
An Enumeration of InputStream is shown as follows:
S

equenceInputStream(InputStream first, InputStream second)
SequenceInputStream(Enumeration streamEnum)

Operationally, this class satisfies the requirement of reading the first InputStream and then going to read the second stream.
With Enumeration, it will continue to read all InputStream streams until the last one is read out.
Following is an example program that uses SequenceInputStream to output two file contents:

// Demonstrate sequenced input.
import java.io.*;
import java.util.*;
class InputStreamEnumerator implements Enumeration {
private Enumeration files;
public InputStreamEnumerator(Vector files) {
this.files = files.elements();
}
public boolean hasMoreElements() {
return files.hasMoreElements();
}
public Object nextElement() {
try {
return new FileInputStream(files.nextElement().toString());
} catch (Exception e) {
return null;
}
}
}
class SequenceInputStreamDemo {
public static void main(String args[]) throws Exception {
int c;
Vector files = new Vector();
files.addElement("/autoexec.bat");
files.addElement("/config.sys");
InputStreamEnumerator e = new InputStreamEnumerator(files);
InputStream input = new SequenceInputStream(e);
while ((c = input.read()) != -1) {
System.out.print((char) c);
}
input.close();
}
}

This example creates a Vector vector and adds two file names to it. It passes the name vector to
The InputStream Enumerator class is designed to provide a vector wrapper, and the elements returned by the vector are not file names, but open FileInputStream streams with these names. SequenceInputStream opens each file in turn, and the program types
The contents of two documents were printed.

PrintStream

PrintStream has all the formats of System.out that we have used in System File Handles since the beginning of this book.
Chemical properties. PrintStream has two constructors:

PrintStream(OutputStream outputStream)
PrintStream(OutputStream outputStream, boolean flushOnNewline)

When flushOnNewline controls every time Java refreshes the output stream, it outputs a newline character (\ n). If flushOnNewline is true, it refreshes automatically. If false, refresh cannot be done automatically. The first constructor does not support automatic refresh. Java's PrintStream object supports various types of print() and println() methods, including Object. If the parameter is not a simple type, the PrintStream method calls the toString() method of the object and prints the result.

Random Access File (Random Access File Class)

Random Access File wraps a randomly accessed file. Instead of deriving from InputStream and OutputStream, it implements DataInput and DataOutput interfaces that define basic input/output methods. It also supports location requests -- that is, file pointers can be placed inside files. It has two constructors:

RandomAccessFile(File fileObj, String access)
throws FileNotFoundException
RandomAccessFile(String filename, String access)
throws FileNotFoundException

In the first form, fileObj specifies the name of the file opened as a File object.
In the second form, the file name is passed in by the filename parameter. In both cases, access decides what file type to allow access to. If it is "r", then the file is readable and not writable. If it is "rw", the file is opened in read-write mode. The seek() method shown below sets the current location of the file pointer inside the file:

void seek(long newPos) throws IOException

Here, newPos means that the file pointer specifies a new location in bytes starting from the file. After calling the seek() method, the next read or write operation will occur in the new location of the file.
Random AccessFile implements standard input and output methods for reading and writing random access files. The following is a new method setLength() added to Java 2. It has the following forms:

void setLength(long len) throws IOException

This method sets the length of the file being called by specifying len. This method can grow or shorten a file. If the file is lengthened, the added part is undefined.

Posted by pchadwick83 on Wed, 31 Jul 2019 23:44:01 -0700