Você está na página 1de 47

Information Science and Engineering

Stream
A stream is an abstraction that either produces or consumes information. * Byte Stream * Character Stream BufferedInputStream BufferedOutputStream ByteArrayInputStream ByteArrayOutputStream FilterOutputStream FilterInputStream PrintStream InputStream DataInputStream RandomAccessFile DataOutputStream SequenceInputStream BufferedReader BufferedWriter InputStreamReader CharArrayWriter CharArrayReader LineNumberReader FileWriter Reader File FileDescriptor FileInputStream PrintWriter FilterWriter FilterReader FileOutputStream
Information Science and Engineering
2

Reading Console Input


console input is accomplished by reading from System.in BufferedReader : BufferedReader(Reader inputReader) int read( ) throws IOException String readLine( ) throws IOException

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

Information 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 ); } }

Information 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

Information 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); } }
Information Science and Engineering
6

java.lang
Integer Character Float 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)); } }
Information Science and Engineering
7

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

Information 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)
Information Science and Engineering
9

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

Information Science and Engineering

10

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(); } } Information Science and Engineering

11

try {
fout = new FileOutputStream(args[1]); } catch(FileNotFoundException e) { System.out.println("Error Opening Output File"); return; } fout.write(i);

Information Science and Engineering

12

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 to navigate 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");

Information Science and Engineering

13

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"); } } Information Science and Engineering

14

boolean renameTo(File newName);


boolean delete( );

void deleteOnExit( )

Removes the file associated with the invoking object when the Java Virtual Machine terminates.

boolean isHidden( )

Returns true if the invoking file is hidden. Returns false otherwise.


Sets the time stamp on the invoking file to that specified by millisec, which is the number of milliseconds from January 1, 1970, Coordinated Universal Time (UTC).

boolean setLastModified(long millisec)

boolean setReadOnly( )

Sets the invoking file to read-only.


Information Science and Engineering
15

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"); } } } 16 Information Science and Engineering

Using FilenameFilter String[ ] list(FilenameFilter FFObj) 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); } }
Information Science and Engineering
17

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]); } } }

Information Science and Engineering

18

Information Science and Engineering

19

Information Science and Engineering

20

An applet is a Java program that runs on a web page


Applets can be run from:
Internet Explorer Netscape Navigator (sometimes) appletviewer

An application is a Java program that runs all by itself

Information Science and Engineering

21

The Applet class


To create an applet, you must import the Applet class
This class is in the java.applet package

The Applet class contains code that works with a browser to create a display window Capitalization matters!
applet and Applet are different names import java.applet.Applet;
Information Science and Engineering
22

The java.awt package includes classes for: Drawing lines and shapes Drawing letters Setting colors Choosing fonts
paint needs 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

Information Science and Engineering

23

Applet methods : public void init ()


public void public void public void public void start () stop () destroy () paint (Graphics)

Also:
public void repaint() public void update (Graphics) public void showStatus(String) public String getParameter(String) import java.awt.*; import java.applet.*; public class SimpleApplet extends Applet { public void paint(Graphics g) { g.drawString(Hello World! ", 20, 20); } }
Information Science and Engineering
24

init() start()
do some work

stop() destroy()
Information Science and Engineering
25

How to RUN : <applet code=AppletClassName" width=200 height=60> </applet>


Save this code in runApp.html file <html> <body> <applet code="SimpleApplet" width=200 height=60> </applet> </body> </html>

OR
c:\> appletviewer runApp.html

Information Science and Engineering

26

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); } }

Information Science and Engineering

27

Sample Graphics methods


g.drawString(Hello, 20, 20);
g.drawRect(x, y, width, height);

Hello

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


g.drawOval(x, y, width, height); g.fillOval(x, y, width, height); g.setColor(Color.red);
Information Science and Engineering
28

setBackground(Color.cyan); setForeground(Color.red); Color.black Color.blue Color.cyan Color.darkGray Color.gray Color.green Color.lightGray Color.magenta Color.orange Color.pink Color.red Color.white Color.yellow

Information Science and Engineering

29

// Using the Status Window. import java.awt.*; import java.applet.*; /* <applet code="StatusWindow" width=300 height=50> </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."); } }
Information Science and Engineering
30

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 thread public void start() { t = new Thread(this); stopFlag = false; t.start(); }
Information Science and Engineering
31

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); } }
Information Science and Engineering
32

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] </APPLET>

Information Science and Engineering

33

<applet code="ParamDemo" width=300 height=80> <param name=fontName value=Courier> <param name=fontSize value=14> <param name=leading value=2> <param name=accountEnabled value=true> </applet> // 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;
Information Science and Engineering
34

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); } }

Information Science and Engineering

35

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); } }

Information Science and Engineering

36

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"); } } }
Information Science and Engineering
37

JSP JAVA Server Pages


JSP Tags <%

JSP Code

%>

<%-<%! <%@ <%= <%

Comment Line
Declaration Section Directive tags Expression Tag Script Tags

--%>
%> %> %> %>

Information Science and Engineering

38

<HTML>
<BODY> <%! int AGE=30; String name=new String(ABC; <P> Your Age is : <%=age%> </P> <P> Your name is : <%=name%> </P> </BODY> </HTML> <HTML> <BODY> <%! int AGE=30; %> <P> Your Age is : <%=age%> </P> </BODY> </HTML>

%>

Information Science and Engineering

39

<%@ page import=import java.sql.*; %> <%@ include file=keogh\book.html %> <%@ taglib uri=MyTags.tld %>

Information Science and Engineering

40

Methods :

<HTML> <BODY> <%! Boolean abc(int x) { return (x*20); } %> <P> Your value is : <%=abc(10)%> </P> </BODY> </HTML>

Information Science and Engineering

41

<HTML> <BODY> <%! Int x=10; %> <% if(x>10) { %> <p><b> X value is greater then 10 </b></p> <% } else { %> <p><b> X value is less then 10 </b></p> <% } %> <P> Use of if statement </P> </BODY> </HTML>

Information Science and Engineering

42

JDBC
Class 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(); }

Information Science and Engineering

43

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();

Information Science and Engineering

44

import java.sql.*

Information Science and Engineering

45

Information Science and Engineering

46

Information Science and Engineering

47

Você também pode gostar