JavaIO and Applet

Embed Size (px)

Citation preview

  • 8/22/2019 JavaIO and Applet

    1/47

    1Information Science and Engineering

  • 8/22/2019 JavaIO and Applet

    2/47

    2Information Science and Engineering

    Stream

    A stream is an abstraction that either produces or consumes

    information.

    * Byte Stream* Character Stream

    BufferedInputStream

    BufferedOutputStream

    ByteArrayInputStream

    ByteArrayOutputStreamFilterOutputStream

    FilterInputStream

    PrintStream

    InputStream

    DataInputStream

    RandomAccessFileDataOutputStream

    SequenceInputStream

    BufferedReader

    BufferedWriter

    InputStreamReader

    CharArrayWriterCharArrayReader

    LineNumberReader

    FileWriter

    Reader

    File

    FileDescriptorFileInputStream

    PrintWriter

    FilterWriter

    FilterReader

    FileOutputStream

  • 8/22/2019 JavaIO and Applet

    3/47

    3Information Science and Engineering

    Reading Console Input

    console input is accomplished by reading from System.in

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    BufferedReader :

    BufferedReader(Reader inputReader)

    int read( ) throws IOException

    String readLine( ) throws IOException

  • 8/22/2019 JavaIO and Applet

    4/47

    4Information Science and Engineering

    import java.io.*;

    class BRRead {

    public static void main(String args[]) throws IOException

    {char c;

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    System.out.println("Enter characters, 'q or Q' to quit.");

    // read characters

    do {

    c = (char) br.read();System.out.println(c);

    } while(c != 'q' || c !=Q );

    }

    }

  • 8/22/2019 JavaIO and Applet

    5/47

    5Information Science and Engineering

    import java.io.*;

    class BRReadLines

    {public static void main(String args[]) throws IOException

    {

    // create a BufferedReader using System.in

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    String str;

    System.out.println("Enter lines of text.");str = br.readLine();

    System.out.println(str);

    }

    }

    void write(int byteval) throws IOException

  • 8/22/2019 JavaIO and Applet

    6/47

    6Information Science and Engineering

    PrintWriter Class

    PrintWriter(OutputStream outputStream, boolean flushOnNewline)

    PrintWriter pw = new PrintWriter(System.out, true);

    import java.io.*;

    public class PrintWriterDemo

    {public static void main(String args[])

    {

    PrintWriter pw = new PrintWriter(System.out, true);

    pw.println("This is a string");

    int i = -7;

    pw.println(i);

    double d = 4.5e-7;

    pw.println(d);

    }

    }

  • 8/22/2019 JavaIO and Applet

    7/47

    7Information Science and Engineering

    java.lang

    Integer

    CharacterFloat

    Double

    Short

    Byte

    Boolean etc.,

    class DoubleDemo

    {

    public static void main(String args[])

    {

    Double d1 = new Double(3.14159);Double d2 = new Double("314159E-5");

    System.out.println(d1 + " = " + d2 + " -> " + d1.equals(d2));

    }

    }

  • 8/22/2019 JavaIO and Applet

    8/47

    8Information Science and Engineering

    static short parseShort(String str) throws NumberFormatException

    static int parseInteger(String str) throws NumberFormatException

    static int parseInt(String str, int radix) throws NumberFormatException

    static long parseLong(String str) throws NumberFormatException

  • 8/22/2019 JavaIO and Applet

    9/47

    9Information Science and Engineering

    import java.io.*;

    class ParseDemo

    {

    public static void main(String args[]) throws IOException

    {BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    String str;

    int I;

    try {

    System.out.println(Enter a number : );

    str = br.readLine();

    i = Integer.parseInt(str);

    }

    catch(NumberFormatException e)

    {

    System.out.println("Invalid format");

    }

    System.out.println(Given number is : + i);

    }

    }Integer.toBinaryString(num)

  • 8/22/2019 JavaIO and Applet

    10/47

    10Information Science and Engineering

    Reading and Writing Files

    FileInputStream(String fileName) throws FileNotFoundException

    FileOutputStream(String fileName) throws FileNotFoundException

    void close( ) throws IOException

    int read( ) throws IOException

    void write(int byteval) throws IOException

  • 8/22/2019 JavaIO and Applet

    11/47

    11Information Science and Engineering

    import java.io.*;

    class ShowFile {

    public static void main(String args[])

    throws IOException

    {int i;

    FileInputStream fin;

    try {

    fin = new FileInputStream(abc.txt);

    }

    catch(FileNotFoundException e){

    System.out.println("File Not Found");

    return;

    }

    do

    {i = fin.read();

    if(i != -1) System.out.print((char) i);

    } while(i != -1);

    fin.close();

    }

    }

  • 8/22/2019 JavaIO and Applet

    12/47

    12Information Science and Engineering

    try {

    fout = new FileOutputStream(args[1]);

    }

    catch(FileNotFoundException e){

    System.out.println("Error Opening Output File");

    return;

    }

    fout.write(i);

  • 8/22/2019 JavaIO and Applet

    13/47

    13Information Science and Engineering

    File

    A File object is used to obtain or manipulate the information associated with a

    disk file, such as the permissions, time, date, and directory path, and tonavigate subdirectory hierarchies.

    File(String directoryPath)

    File(String directoryPath, String filename)

    File(File dirObj, String filename)

    File(URI uriObj)

    Example:

    File f1 = new File("/");

    File f2 = new File("/","autoexec.bat");

    File f3 = new File(f1,"autoexec.bat");

  • 8/22/2019 JavaIO and Applet

    14/47

    14Information Science and Engineering

    import java.io.File;

    class FileDemo

    {

    static void p(String s) { System.out.println(s); }

    public static void main(String args[])

    {

    File f1 = new File("/java/COPYRIGHT");

    p("File Name: " + f1.getName());

    p("Path: " + f1.getPath());p("Abs Path: " + f1.getAbsolutePath());

    p("Parent: " + f1.getParent());

    p(f1.exists() ? "exists" : "does not exist");

    p(f1.canWrite() ? "is writeable" : "is not writeable");

    p(f1.canRead() ? "is readable" : "is not readable");

    p("is " + (f1.isDirectory() ? "" : "not" + " a directory"));p(f1.isFile() ? "is normal file" : "might be a named pipe");

    p(f1.isAbsolute() ? "is absolute" : "is not absolute");

    p("File last modified: " + f1.lastModified());

    p("File size: " + f1.length() + " Bytes");

    }

    }

  • 8/22/2019 JavaIO and Applet

    15/47

    15Information Science and Engineering

    boolean renameTo(File newName);

    boolean delete( );

    void deleteOnExit( )

    boolean isHidden( )

    Removes the file associated with the

    invoking object when the Java Virtual

    Machine terminates.

    Returns true if the invoking file is

    hidden. Returns false otherwise.

    boolean setLastModified(long millisec)

    boolean setReadOnly( )

    Sets the time stamp on the invoking

    file to that specified by millisec, whichis the number of milliseconds from

    January 1, 1970, Coordinated

    Universal Time (UTC).

    Sets the invoking file to read-only.

  • 8/22/2019 JavaIO and Applet

    16/47

    16Information Science and Engineering

    import java.io.File;

    class DirList

    {

    public static void main(String args[])

    { String dirname = "/java";

    File f1 = new File(dirname);

    if (f1.isDirectory())

    {

    System.out.println("Directory of " + dirname);

    String s[] = f1.list();for (int i=0; i < s.length; i++)

    {

    File f = new File(dirname + "/" + s[i]);

    if (f.isDirectory()) {

    System.out.println(s[i] + " is a directory");

    }else {

    System.out.println(s[i] + " is a file");

    }

    } else { System.out.println(dirname + " is not a directory"); }

    }

    }

  • 8/22/2019 JavaIO and Applet

    17/47

    17Information Science and Engineering

    Using FilenameFilter

    String[ ] list(FilenameFilterFFObj)

    boolean accept(File directory, String filename)

    import java.io.*;

    public class OnlyExt implements FilenameFilter

    {

    String ext;

    public OnlyExt(String ext)

    {

    this.ext = "." + ext;

    }

    public boolean accept(File dir, String name)

    {

    return name.endsWith(ext);

    }

    }

  • 8/22/2019 JavaIO and Applet

    18/47

    18Information Science and Engineering

    import java.io.*;

    class DirListOnly

    {

    public static void main(String args[]){

    String dirname = "/java";

    File f1 = new File(dirname);

    FilenameFilter only = new OnlyExt("html");

    String s[] = f1.list(only);

    for (int i=0; i < s.length; i++){

    System.out.println(s[i]);

    }

    }

    }

  • 8/22/2019 JavaIO and Applet

    19/47

    19Information Science and Engineering

  • 8/22/2019 JavaIO and Applet

    20/47

    20Information Science and Engineering

  • 8/22/2019 JavaIO and Applet

    21/47

    21Information Science and Engineering

    An applet is a Java program that runs on aweb page

    Applets can be run from:

    Internet ExplorerNetscape Navigator (sometimes)

    appletviewer

    An application is a Java program that runs all

    by itself

  • 8/22/2019 JavaIO and Applet

    22/47

    22Information Science and Engineering

    The Applet class

    To create an applet, you must import theApplet class

    This class is in the java.applet package

    The Applet class contains code that workswith a browser to create a display window

    Capitalization matters!

    applet and Applet are different names

    import java.applet.Applet;

  • 8/22/2019 JavaIO and Applet

    23/47

    23Information Science and Engineering

    The java.awtpackage includes classes for:

    Drawing lines and shapes

    Drawing letters

    Setting colorsChoosing fonts

    paintneeds to be told where on the screen it can draw

    public void paint(Graphics g)

    AWT methods :

    g.drawString(String", int x, int y);

    g.setColor(Color.RED);

    g.drawRect( left, top , width , height);

    g.fillRect(left, top , width , height);etc

  • 8/22/2019 JavaIO and Applet

    24/47

    24Information Science and Engineering

    import java.awt.*;

    import java.applet.*;

    public class SimpleApplet extends Applet

    { public void paint(Graphics g)

    {

    g.drawString(Hello World! ", 20, 20);

    }

    }

    public void init ()

    public void start ()

    public void stop ()

    public void destroy ()public void paint (Graphics)

    Also:

    public void repaint()

    public void update (Graphics)

    public void showStatus(String)

    public String getParameter(String)

    Applet methods :

  • 8/22/2019 JavaIO and Applet

    25/47

    25Information Science and Engineering

    init()

    start()

    stop()

    destroy()

    do some work

  • 8/22/2019 JavaIO and Applet

    26/47

    26Information Science and Engineering

    How to RUN :

  • 8/22/2019 JavaIO and Applet

    27/47

    27Information Science and Engineering

    import java.applet.Applet;

    import java.awt.Graphics;

    import java.awt.Color;public class SimpleApplet extends Applet

    {

    String text = "I'm a simple applet";

    public void init()

    {

    text = "I'm a simple applet";setBackground(Color.cyan);

    }

    public void start()

    {

    System.out.println("starting...");

    }public void stop()

    {

    System.out.println("stopping...");

    }

    public void destroy(){

    System.out.println("preparing to unload...");

    }

    public void paint(Graphics g)

    {

    System.out.println("Paint");g.setColor(Color.blue);

    g.drawRect(0, 0, getSize().width -1,

    getSize().height -1);

    g.setColor(Color.red);

    g.drawString(text, 15, 25);

    }}

  • 8/22/2019 JavaIO and Applet

    28/47

    28Information Science and Engineering

    Sample Graphics methods

    g.drawRect(x, y, width, height);g.fillRect(x, y, width, height);

    g.drawOval(x, y, width, height);

    g.fillOval(x, y, width, height);

    g.setColor(Color.red);

    g.drawString(Hello, 20, 20); Hello

  • 8/22/2019 JavaIO and Applet

    29/47

    29Information Science and Engineering

    Color.black Color.magenta

    Color.blue Color.orangeColor.cyan Color.pink

    Color.darkGray Color.red

    Color.gray Color.white

    Color.green Color.yellow

    Color.lightGray

    setBackground(Color.cyan);

    setForeground(Color.red);

  • 8/22/2019 JavaIO and Applet

    30/47

    30Information Science and Engineering

    // Using the Status Window.

    import java.awt.*;

    import java.applet.*;

    /*

    */

    public class StatusWindow extends Applet

    {

    public void init(){

    setBackground(Color.cyan);

    }

    // Display msg in applet window.

    public void paint(Graphics g)

    {g.drawString("This is in the applet window.", 10, 20);

    showStatus("This is shown in the status window.");

    }

    }

  • 8/22/2019 JavaIO and Applet

    31/47

    31Information Science and Engineering

    import java.awt.*;

    import java.applet.*;

    public class SimpleBanner extends Applet implements Runnable

    {String msg = " A Simple Moving Banner.";

    Thread t = null;

    int state;

    boolean stopFlag;

    // Set colors and initialize thread.

    public void init() {

    setBackground(Color.cyan);

    setForeground(Color.red);

    }

    // Start threadpublic void start() {

    t = new Thread(this);

    stopFlag = false;

    t.start();

    }

    public void run() {

  • 8/22/2019 JavaIO and Applet

    32/47

    32Information Science and Engineering

    public void run() {

    char ch;

    for( ; ; ) {

    try {

    repaint();

    Thread.sleep(250);ch = msg.charAt(0);

    msg = msg.substring(1, msg.length());

    msg += ch;

    if(stopFlag)

    break;

    } catch(InterruptedException e) { }}

    }

    public void stop() {

    stopFlag = true;

    t = null;

    }// Display the banner.

    public void paint(Graphics g) {

    g.drawString(msg, 50, 30);

    }

    }

  • 8/22/2019 JavaIO and Applet

    33/47

    33Information Science and Engineering

    The HTML APPLET Tag

    < APPLET

    [CODEBASE = codebaseURL]CODE = appletFile

    [ALT = alternateText]

    [NAME = appletInstanceName]

    WIDTH =pixels HEIGHT = pixels

    [ALIGN = alignment]

    [VSPACE =pixels] [HSPACE = pixels]>

    [< PARAM NAME =AttributeName VALUE = AttributeValue>]

    [< PARAM NAME =AttributeName2 VALUE = AttributeValue>]

    . . .

    [HTML Displayed in the absence of Java]

  • 8/22/2019 JavaIO and Applet

    34/47

    34Information Science and Engineering

    // Applet program to Use Parameters

    import java.awt.*;

    import java.applet.*;

    public class ParamDemo extends Applet

    {

    String SName;

    int Sage;

    boolean active;// Initialize the string to be displayed.

    public void start()

    {

    String param;

  • 8/22/2019 JavaIO and Applet

    35/47

    35Information Science and Engineering

    SName = getParameter(StuName");

    if(SName == null)

    SName = "Not Found";

    param = getParameter(age");

    try {if(param != null) // if not found

    Sage = Integer.parseInt(param);

    else

    Sage = 0;

    } catch(NumberFormatException e) {

    Sage = 0;}

    }

    public void paint(Graphics g)

    {

    g.drawString(Student name : " + SName, 0, 10);

    g.drawString(Student age : " + Sage, 0, 26);}

    }

  • 8/22/2019 JavaIO and Applet

    36/47

    36Information Science and Engineering

    getDocumentBase( ) and getCodeBase( )

    import java.awt.*;

    import java.applet.*;

    import java.net.*;

    public class Bases extends Applet

    {

    public void paint(Graphics g)

    {

    String msg;

    URL url = getCodeBase(); // get code base

    msg = "Code base: " + url.toString();

    g.drawString(msg, 10, 20);

    url = getDocumentBase(); // get document base

    msg = "Document base: " + url.toString();g.drawString(msg, 10, 40);

    }

    }

  • 8/22/2019 JavaIO and Applet

    37/47

    37Information Science and Engineering

    AppletContext and showDocument( )

    showDocument( ) method defined by the AppletContext interface

    import java.awt.*;

    import java.applet.*;

    import java.net.*;

    public class ACDemo extends Applet

    {

    public void start()

    {

    AppletContext ac = getAppletContext();

    URL url = getCodeBase(); // get url of this applet

    try {

    ac.showDocument(new URL(url+"Test.html"));

    } catch(MalformedURLException e) {showStatus("URL not found");

    }

    }

    }

  • 8/22/2019 JavaIO and Applet

    38/47

    38Information Science and Engineering

    JSP JAVA Server Pages

    JSP Tags

  • 8/22/2019 JavaIO and Applet

    39/47

    39Information Science and Engineering

    Your Age is :

    Your name is :

    Your Age is :

  • 8/22/2019 JavaIO and Applet

    40/47

    40Information Science and Engineering

  • 8/22/2019 JavaIO and Applet

    41/47

    41Information Science and Engineering

    Methods :

    Your value is :

  • 8/22/2019 JavaIO and Applet

    42/47

    42Information Science and Engineering

    10) { %>

    X value is greater then 10

    X value is less then 10

    Use of if statement

  • 8/22/2019 JavaIO and Applet

    43/47

    43Information Science and Engineering

    JDBCClass driver_class=null;

    try {driver_class = Class.forName("com.mysql.jdbc.Driver");

    } catch (ClassNotFoundException e) {

    e.printStackTrace();

    }

    System.out.println("Found driver " + driver_class);

    Connection connection=null;

    try {

    connection = DriverManager.getConnection

    ("jdbc:mysql://localhost:3306/ecs160tutorial","tutorialuser","123456");} catch (SQLException e) {

    e.printStackTrace();

    }

  • 8/22/2019 JavaIO and Applet

    44/47

    44Information Science and Engineering

    Statement statement = connection.createStatement();

    statement.execute("SELECT * FROM simple_table");

    ResultSet resset = statement.getResultSet();

    System.out.println("Row Name Last_Name");while(resset.next())

    {

    System.out.print(resset.getRow());

    System.out.print(" " + resset.getString("name"));

    System.out.println(" " + resset.getString("last_name"));

    }resset.close();

  • 8/22/2019 JavaIO and Applet

    45/47

    45Information Science and Engineering

    import java.sql.*

  • 8/22/2019 JavaIO and Applet

    46/47

    46Information Science and Engineering

  • 8/22/2019 JavaIO and Applet

    47/47