Skip to main content

I/O and Java Applets


7.1 I/O Stream in Java

In Java, an I/O stream (short for Input/Output stream) is a fundamental concept used for reading data from and writing data to various sources and destinations, such as files, network connections, or memory. It provides a way to transfer data in a sequential and consistent manner, regardless of the source or destination.

I/O streams are typically categorized into two main types:

            Input Streams: These streams are used for reading data from a source. They allow you to retrieve data from various sources, like files, keyboard input, or network sockets. Some common classes that represent input streams include FileInputStream, BufferedInputStream, and ObjectInputStream.

             

            Output Streams: These streams are used for writing data to a destination. They allow you to send data to various destinations, like files, console output, or network sockets. Common classes for output streams include FileOutputStream, BufferedOutputStream, and ObjectOutputStream.

I/O streams can be further categorized based on the type of data they handle:

       Byte Streams: These streams deal with raw binary data, typically reading and writing data as bytes. InputStream and OutputStream are the base classes for byte streams.

       Character Streams: These streams handle character data, typically in the form of text. They are used for reading and writing characters in a character encoding-specific way. Reader and Writer are the base classes for character streams.


import java.io.File;

import java.io.FileOutputStream;

import java.io.FileInputStream;

import java.io.IOException;

public class FileCreateReadWrite {

    public static void main(String[] args) {


        try {

            //  Step 1: Create File

            File file = new File("example.txt");

            if (file.createNewFile()) {

                System.out.println("File created: " + file.getName());

            } else {

                System.out.println("File already exists.");

            }


            //  Step 2: Write to File

            try (FileOutputStream fos = new FileOutputStream(file)) {

                String data = "Hello! This file is created and written using Java.";

                fos.write(data.getBytes());

                System.out.println("Data written successfully.");

            }


            //  Step 3: Read from File

            try (FileInputStream fis = new FileInputStream(file)) {

                int ch;

                System.out.println("Reading file content:");


                while ((ch = fis.read()) != -1) {

                    System.out.print((char) ch);

                }

            }


        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}

This program creates a file using createNewFile(), writes data using FileOutputStream.write(), and reads the file using FileInputStream.read() to display its content on the console.



Read and Write Console

In Java, you can read and write to the console using the standard input and output streams. These streams are represented by the following classes:

  • System.out (standard output):
    This is an instance of PrintStream and is used to write data to the console.
  • System.in (standard input):
    This is an instance of InputStream and is used to read data from the console, typically representing keyboard input.

 Writing to the Console

To write data to the console, you can use the System.out object, which is an instance of PrintStream. You can use methods like print() or println() to display text or other data on the console:

  • The print() method writes the text without moving to a new line.
  • The println() method adds a newline character, moving to the next line.
System.out.print("This is some text.");
System.out.println("This is a new line of text.");

 Reading from the Console

To read data from the console, you can use the System.in stream. However, working directly with System.in can be a bit low-level because it reads data as bytes.

To read character data or full lines of text more easily, you can wrap System.in with a Reader or use the Scanner class for convenient input processing.

Example using Scanner

import java.util.Scanner;

public class ConsoleInputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter your name: ");
String name = scanner.nextLine();

System.out.println("Hello, " + name + "!");

scanner.close(); // Close the scanner when you're done with it.
}
}


Java Applets

Java applets were small Java programs designed to run within a web browser. They were a way to add interactive and dynamic content to web pages in the 1990s and early 2000s. Java applets provided a means to create animations, games, and other interactive features in a web page, similar to how JavaScript is used today.

Key Features

  1. Platform Independence:
    Java applets could run on any system with a JVM, making them platform independent.
  2. Security Model:
    They operated in a sandbox environment that restricted access to the system for security.
  3. Interactivity:
    Applets allowed creation of interactive features like animations and games.
  4. Object-Oriented:
    They were developed using Java, which supports object-oriented programming.

Limitations

  1. Security Concerns:
    Java applets had security vulnerabilities that made them unsafe over time.
  2. Browser Support Removed:
    Modern browsers stopped supporting Java plugins required for applets.
  3. Performance Issues:
    Applets were slow to load and run compared to modern technologies.
  4. Complexity:
    They were difficult to develop and required additional setup to run.

 Java Applet Program + HTML 

Java Applet Code

import java.applet.Applet;
import java.awt.Graphics;

public class HelloApplet extends Applet {
public void paint(Graphics g) {
g.drawString("Hello Applet", 50, 50);
}
}

 HTML File to Run Applet

<html>
<head>
<title>Java Applet Example</title>
</head>
<body>

<h2>My First Java Applet</h2>

<applet code="HelloApplet.class" width="300" height="200">
</applet>

</body>
</html>

 How It Works 

  • First, the Java applet program is written and compiled to generate a .class file.
  • Then, an HTML file is created to embed the applet.
  • The <applet> tag is used to load the compiled class file.
  • When the HTML file is opened, the browser automatically runs the applet.
  • The paint() method is called and the output is displayed inside the applet window.

Keep in mind that most modern web browsers will not support Java applets, and they may even prompt users to enable deprecated plugins, which is a security risk. For this reason, it's strongly recommended to use alternative web technologies like JavaScript and HTML5 for creating interactive web content.

If you need interactivity and dynamic content in your web application, consider using JavaScript and HTML5, which are widely supported and more secure alternatives.

Comments

Popular posts from this blog

Function of OS 1. Process Management The operating system helps in running many programs at the same time. It keeps track of each running program (called a process), decides which one should run next, and stops or starts them as needed. It makes sure that all the programs get a fair chance to use the CPU.   2. Memory Management The OS manages the computer's memory (RAM). It decides which program will use how much memory and keeps track of it. When a program is closed, it frees up the memory so that other programs can use it. This helps the computer run smoothly without crashing.   3. File System Management The operating system helps us to create, save, open, and delete files. It organizes files in folders and keeps them safe. It also controls who can open or edit a file to protect our data.   4. Device Management The OS controls all the input and output devices like the keyboard, mouse, printer, and monitor. It tells the devices what to do and makes su...

UNIT 3 Array in C#

  Array in C# An array is a collection of variables of the same data type , stored in contiguous memory locations , and accessed using a common name and index . Each item in an array is called an element , and the index of arrays in C# starts from 0 .     Key Points About Arrays in C#: 1.       Elements are stored in contiguous memory locations. 2.       Index starts from 0. So, for an array of size 5, valid indexes are 0 to 4. 3.       Arrays are reference types and are allocated on the heap. 4.       C# array is an object of base type System.Array . 5.       Array elements can be of any type , including another array (array of arrays). 6.       Jagged array (array of arrays) elements are reference types and are initialized to null . 7.       Arrays can be single-dimensi...

Unit 5 SEP

  Software analysis and Design tools Software Analysis and Design Tools are special computer programs that help developers and designers in every stage of making software. These tools make it easier to understand, plan, design, and document a software system so that the final product works well and meets user needs. They help in collecting requirements by recording what users want, modeling the system using diagrams such as flowcharts and UML, and designing the structure and interface of the software. These tools also help in creating documentation for clear communication, analyzing the design to find and fix problems early, and supporting teamwork by allowing different people to work together on the same project smoothly. Introduction of ER Model The Entity-Relationship (ER) Model is a conceptual model used to design and represent the logical structure of a database . It shows entities, their attributes, and relationships among them. Example: A Student enr...