CH1(chat).docx
Document Details
Tags
Full Transcript
**Client, Server** 1. A server offers a service to clients that connect to it. 2. The server runs on a host machine. 3. A client starts communication with the server. 4. Servers commonly provide services like hosting web pages. 5. Web browsers (e.g., Firefox, Chrome) are clients used to ac...
**Client, Server** 1. A server offers a service to clients that connect to it. 2. The server runs on a host machine. 3. A client starts communication with the server. 4. Servers commonly provide services like hosting web pages. 5. Web browsers (e.g., Firefox, Chrome) are clients used to access web servers. **Streams** 1. Java I/O is built on streams. 2. Input streams read data; output streams write data. 3. All output /(input) streams share basic read /(write) methods. 4. Filter streams can be added to modify data during reading or writing. 5. Readers and writers help programs handle text instead of bytes. **Output Stream (Write)** Java's basic output class is java.io.OutputStream. Key methods: 1. write(int b) - Writes a byte. 2. write(byte\[\] data) - Writes an array of bytes. 3. write(byte\[\] data, int off, int len) - Writes a portion of an array. 4. flush() - forces any buffered data to be written. 5. close() - Closes the stream and frees resources. **Advantages of the close() method:** a\) **close()** frees up any resources the stream is using, like file handles or network ports. b\) If the stream is connected to a network, closing it will end that connection. c\) After an output stream is closed, trying to write to it will cause an IOException. d\) Not closing a stream in a long-running program can cause resource leaks, such as unused file handles or network ports staying open. **Why Flush Streams?** Flush before closing to avoid data loss. Not flushing can cause hard-to-diagnose errors. **\ ** **Input Stream (read)** Java's basic input class is java.io.InputStream. Key methods: 1. int read() - Reads a byte. 2. int read(byte\[\] data) - Reads into an array. 3. int read(byte\[\] data, int off, int len) - Reads into an array with an offset. **Note**: All the above three read() methods return --1 to signal the end of the stream. - This means the end of the stream has been reached. It acts as a flag that tells the program, \"I\'ve reached the end, and there\'s no more data to process". 4. long skip(long n) - Skips bytes. 5. int available() - Returns bytes available to read. 6. close() - Closes the stream and frees resources. **Filter Stream** - **InputStream** and **OutputStream** handle basic reading and writing of bytes, either one at a time or in groups. - Java offers filter classes that can be added to these raw streams to convert the raw bytes into other formats or vice versa. - There are two types of filters: **filter streams** and **readers/writers**. - **Filter streams** work with raw data in bytes, for example, by compressing the data or treating it as binary numbers. **Readers and writers** deal with text in various formats, like **UTF-8** or **ISO 8859-1**. - All filter output streams use the same **write()**, **close()**, and **flush()** methods as **OutputStream**. - All filter input streams use the same **read()**, **close()**, and **available()** methods as **InputStream**. - Filters are connected to streams through their constructor **Buffered Streams** The **BufferedOutputStream** class temporarily stores data in a buffer (a byte array) until the buffer is full or the stream is flushed. - Once full, it writes all the data at once to the output stream. - Writing many bytes in one go is much faster than writing small amounts multiple times. - **Constructors of BufferedOutputStream:** 1. BufferedOutputStream(OutputStream out) 2. BufferedOutputStream(OutputStream out, int bufferSize) The **BufferedInputStream** class uses a buffer to store data. - When you call a read() method, it first checks the buffer for the requested data. - If the buffer is empty, only then does it read from the actual source. - **Constructors of BufferedInputStream:** 1. BufferedInputStream(InputStream in) 2. BufferedInputStream(InputStream in, int bufferSize) **\ ** **Print Stream** ![](media/image2.png)The **PrintStream** class is commonly used because **System.out** is a PrintStream. However, you can attach other output streams to a PrintStream using these two constructors: 1. **PrintStream(OutputStream out)** 2. **PrintStream(OutputStream out, boolean autoFlush)** **Note**: PrintStream includes the **print()** and **println()** methods for printing data. **Predefined Streams** All Java programs automatically import the **java.lang** package, which includes a class called **System**. This class has three predefined stream variables: **in**, **out**, and **err**. 1. **System.out**: This is the standard output stream, usually set to the console. 2. **System.in**: This is the standard input stream, typically reading from the keyboard. 3. **System.err**: This is the standard error stream, which also outputs to the console. **Note**: - **System.in** is an **InputStream** object. - **System.out** and **System.err** are **PrintStream** objects. - Although these are byte streams, they are commonly used to read and write characters to and from the console. **Readers and Writers** 1. The **java.io.Reader** class defines how to read characters, while the **java.io.Writer** class defines how to write characters. 2. Unlike input and output streams that use bytes, readers and writers work with Unicode characters. 3. The **FileReader** and **FileWriter** classes are used for reading from and writing to files. **Writer Class:** - The **Writer** class is abstract and is similar to **java.io.OutputStream**. It has five **write()** methods, plus **flush()** and **close()** methods. **Methods of the Writer Class:** 1. **write(char\[\] text, int offset, int length)**: Writes a portion of a character array. 2. **write(int c)**: Writes a single character. 3. **write(char\[\] text)**: Writes an entire character array. 4. **write(String s)**: Writes a string. 5. **write(String s, int offset, int length)**: Writes part of a string. 6. **flush()**: Clears the stream, ensuring all data is written out. 7. **close()**: Closes the stream and releases resources. **OutputStreamWriter Class:** - The **OutputStreamWriter** takes characters from a Java program, converts them to bytes using a specified encoding, and writes them to an underlying output stream. **Reader Class** The **Reader** class is similar to the **java.io.InputStream** class and is abstract. **Methods of the Reader Class:** 1. **int read(char\[\] text, int offset, int length)**: Reads characters into a specified part of a character array. 2. **int read()**: Reads a single character and returns it. 3. **int read(char\[\] text)**: Reads characters into an entire character array. 4. **long skip(long n)**: Skips over **n** characters. 5. **boolean ready()**: Checks if the reader can be read without blocking; returns **true** if it\'s ready. 6. **close()**: Closes the reader and releases resources. **Note**: The **ready()** method tells you if the reader can read data right away without waiting. **InputStreamReader & BufferedReader** **InputStreamReader**: - This class reads bytes from an underlying input stream and converts them into characters using a specified encoding. **BufferedReader**: - When you read from a **BufferedReader**, it gets text from a buffer instead of directly from the underlying input stream. This makes reading more efficient. **BufferedReader** includes the usual methods found in the **Reader** class. **Constructors of BufferedReader**: 1. **BufferedReader(Reader in, int bufferSize)**: Creates a BufferedReader with a specified buffer size. 2. **BufferedReader(Reader in)**: Creates a BufferedReader with a default buffer size. **Note**:\ The **BufferedReader** class has a **readLine()** method that reads a single line of text and returns it as a string. **BufferedWriter** When a program writes to a **BufferedWriter**, the text is stored in a buffer. The text is only sent to the underlying output stream when the buffer is full or when you manually flush it. **BufferedWriter** includes the usual methods found in the **Writer** class. **Constructors of BufferedWriter**: 1. **BufferedWriter(Writer out)**: Creates a BufferedWriter with a default buffer size. 2. **BufferedWriter(Writer out, int bufferSize)**: Creates a BufferedWriter with a specified buffer size. **\ ** **PrintWriter** The **PrintWriter** class is a modern alternative to the **PrintStream** class and is preferred for use. It has nearly the same methods as **PrintStream**. **Constructors of PrintWriter**: 1. **PrintWriter(Writer out)**: Creates a PrintWriter with a specified Writer. 2. **PrintWriter(Writer out, boolean autoFlush)**: Creates a PrintWriter with a specified Writer and optional auto-flushing. 3. **PrintWriter(OutputStream out)**: Creates a PrintWriter with a specified OutputStream. 4. **PrintWriter(OutputStream out, boolean autoFlush)**: Creates a PrintWriter with a specified OutputStream and optional auto-flushing. **Note**: The **PrintWriter** class has methods that are almost identical to those in **PrintStream**. **File Handling** 1. The File class is part of the java.io package, so you need to import this package in any file-handling program. 2. To read from a text file, you use a FileReader object, and to write to a text file, you use a FileWriter object. 3. Both FileReader and FileWriter constructors can take either: - A String (the file name) - A File object (created from the file name) **Example of Creating File Objects:** File inFile = new File(\"input.txt\"); File outFile = new File(\"output.txt\"); **Example of Creating FileReader and FileWriter objects:** FileReader in = new FileReader(inFile); FileWriter out = new FileWriter(outFile); **Problem with FileReader and FileWriter**: - **FileReader** and **FileWriter** are not flexible enough for efficient reading and writing. To improve this, you can: 1. Wrap a **BufferedReader** around a **FileReader** to read from a file. 2. Wrap a **PrintWriter** around a **FileWriter** to write to a file. - **Example**: **Note**: - Use the **readLine()** method from **BufferedReader** to read lines and **print()** or **println()** from **PrintWriter** to write data. - Always close the file using the **close()** method to flush the output buffer and write any remaining data to the disk.**\ ** **Reading and Writing Files -- FileInputStream & FileOutputStream** Java provides classes and methods to read and write files. Two commonly used classes are **FileInputStream** and **FileOutputStream**, which handle byte streams for file operations. To open a file, create an object of these classes and pass the file name as an argument to the constructor. **Constructors**: 1. **FileInputStream(String fileName)** throws **FileNotFoundException** 2. **FileOutputStream(String fileName)** throws **FileNotFoundException** Here, **fileName** is the name of the file you want to open. **Note**: - For **FileInputStream**, if the file doesn't exist, a **FileNotFoundException** is thrown. - For **FileOutputStream**, if the file can\'t be opened or created, a **FileNotFoundException** is also thrown. - Always close the file when you\'re done using the **close()** method. **File Methods** 1. **boolean canRead()** -- Returns true if the file can be read, otherwise false. 2. **boolean canWrite()** -- Returns true if the file can be written to, otherwise false. 3. **boolean delete()** -- Deletes the file and returns true for success, false for failure. 4. **boolean exists()** -- Returns true if the file exists, otherwise false. 5. **String getName()** -- Returns the name of the file. 6. **boolean isDirectory()** -- Returns true if the object is a directory, otherwise false. 7. **boolean isFile()** -- Returns true if the object is a file, otherwise false. 8. **long length()** -- Returns the file size in bytes. 9. **String\[\] list()** -- If it\'s a directory, returns an array of file names inside it. 10. **File\[\] listFiles()** -- Similar to list(), but returns an array of File objects. 11. **boolean createNewFile()** -- Creates a new file if one doesn't already exist, returning true for success. 12. **String getParent()** -- Returns the parent directory of the file. 13. **String getPath()** -- Returns the file's path. 14. **String getAbsolutePath()** -- Returns the file's absolute path. **Command Line Parameters**: When running a Java program, you can pass additional values (parameters) along with the program name. These values are received by the main method as an array of Strings. For example, if the array is called args, you can access the values as args\[0\], args\[1\], args\[2\], and so on. **\ ** **Serialization** 1. **Serialization** is the process of saving an object\'s state to a byte stream. This is helpful for saving your program\'s state to a file or other storage, and you can restore it later using deserialization. 2. Objects from any class that implements the **Serializable** interface can be saved and retrieved from storage as complete objects, without breaking them down into smaller parts. 3. The **ObjectOutputStream** class is used to save entire objects to a file. 4. The **ObjectInputStream** class is used to read those objects back from the file. **Ports and Sockets** 1. A **port** is a logical connection on a computer, identified by a number between 1 and 65,535. 2. Each port can be assigned to a specific server or service. 3. Ports 1--1023 are reserved for standard services, known as \"well-known\" ports (e.g., port 80 for web servers). 4. Applications using non-standard services should use ports between 1024 and 65,535. 5. A **socket** represents one end of a communication link between two processes. 6. When a client wants to connect to a server, it creates a socket on its side of the connection. 7. When the server receives the request (on a specific port), it creates a new socket dedicated to communicating with that client. **Why Sockets?** 1. In many applications, multiple clients may request the same service simultaneously. 2. A typical example is when many web browsers (potentially thousands) request web pages from the same server. 3. ![](media/image4.png)The server needs a way to differentiate between clients and maintain separate communication with each one. This is done using **sockets**.