Professional Documents
Culture Documents
Input Output
Input Output
1. Exceptions
2. Types of Input-Output Operations
3. Streams
4. Communication on serial and parallel ports
5. Native Methods
1. Exceptions
Definition: An exception is an event, which occurs during the execution
of a program that disrupts the normal flow of the program's instructions
Source: Java Tutorial
.
Signaling
An exception is signaled if:
an expression evaluation violates language normal
an error appears at loading or linking a program
a resource limits are exceeded.
Exceptions are unusual events that happen outside normal or desired
program behavior.
Behavior
Throwing exceptions
Exceptional conditions exception object is ejected from the current
context.
The exception object is created with new operator. It contains information
about the cause.
Handling
Exception handler mechanism to recover exception state recovery
Class behavior when exceptions occur. The programmers are warned
(notified) about the possibilities of exception occurring.
Object
Trowable
Error
RuntimeException
Exception
NullPointerException
ExceptiaMea
AlteClase cu
Exceptii
10
11
Exception subclasses
Runtime exceptions
ArrayIndexOutOfBoundsException referin la o variabil care nu exist
n obiect (index inexistent) s-a depit limita unui tablou
SecurityException a aprut o excepie legat de securitate ncercare de
accesare de metode, clase sau variabile care nu au fost declarate publice
NullPointerException se ncearc folosirea unui pointer cu valoarea null,
adic folosirea unei variabile nainte ca aceasta s fie configurat ca
referin a obiectului sau dup ce a fost eliminat.
ArithmeticException pentru o operaie nepermis (ex. mprire cu zero)
StringOutOfBoundsException indicele este in afara domeniului stabilit
NumberFormatException se ncearc transformarea unui ir de caractere
cu format necorespunztor ntr-un numr
Tiberiu Leia: Software Engineering Input-output operations
12
13
File exception
EOFException - s-a detectat sfritul fiierului i se ncearc citirea din el
n continuare
Transmission exception
MalformedURLException adresa URL nu are formatul corect
(corespunztor)
14
Exception handling
try { //marcare inceput de bloc protejat = guard region
//protected method body or instruction sequence that leads to exception
............................
} // end of protected block
catch (ClassExceptie1 numeExceptie1) // preluare exceptie
{
//secventa_executata_la_aparitia_exceptiei;
}
catch (ClassExceptie2 numeExceptie2) { ... }
finally {
//secventa de cod executata in final (in oricare caz)release of the memory
}
Tiberiu Leia: Software Engineering Input-output operations
15
Catching an exception
Ex:
try {
................
}catch (IOException e) {
System.out.println(Eroare: +e.getMessage());
}
16
17
Exception throwing
launching = signaling = throwing
throw new ExceptiaMea;
Ex.:
if(ref==null) throw new NullPointerException("ref=null");
18
Exception
+metPericuloasa()
MainClass
<<exception>>
ExceptiaMea
+toString()
+getMessage()
+printStack()
+daInformatii()
19
20
21
Rethrowing exception
22
23
2. Input-output operations
<They perform information interchange between a program
and its environment >
Streams
Native methods
Graphical windows - GUI
Communication system
24
3. Streams
read()
Source
InputStream
OutputStream
Program
Destination
write()
print()
25
Senses:
input stream
output stream
Byte streams accept:
numerical data
executable program and
bytecode
26
Source:
files on the same computer
keyboard
input channel - Internet (Intranet)
other thread or program etc.
Destination:
files
monitor - screen
output channel - Internet (Intranet)
other thread or program
printer etc.
27
28
29
Classes:
BufferedInputStream - adaug funcionalitate la alt flux de intrare prin
asocierea unui buffer - clasele vor avea n plus metodele mark i reset.
BufferedOutputStream - implementeaz un flux de ieire cu buffer
BufferedReader - permite citirea unui text dintr-un flux de intrare de tip
caracter. Pune caracterele n buffer astfel nct realizeaz citiri eficiente de
caractere, tablouri i linii.
BufferedWriter - permite scrierea unui text ntr-un flux de ieire de tip
caracter. Pune caracterele n buffer ceea ce permite scrieri eficiente de
caractere singulare, tablouri i string-uri.
ByteArrayInputStream - are un buffer intern care conine octei ce pot fi
citii din flux.
ByteArrayOutputStream - implementeaz un flux de ieire n care se scriu
datele ntr-un tablou de octei.
Tiberiu Leia: Software Engineering Input-output operations
30
31
32
33
34
35
Byte Streams
Reading a character from keyboard
Class System
Clasa System a fost conceput pentru rezolvarea operaiilor I/E simple,
apelarea colectorului de reziduuri, furnizarea timpului curent, ieiri forate
din program, obinerea sau setarea proprietilor sistemului. Aceasta are
cmpurile:
System.in pentru citiri (intrri) standard
System.out pentru scrieri (ieiri) standard i
System.err pentru erori.
Cmpurile menionate sunt membri statici ai clasei System avnd
definiiile:
public static final PrintStream out
public static final InputStream in
Tiberiu Leia: Software Engineering Input-output operations
36
Class InputStream
public abstract class InputStream extends Object
Metode:
available() - returneaz un numr de octei care sunt disponibili n flux fr
a bloca firul
close() - servete la nchiderea fluxului
public synchronized void mark(int n) - marcheaz poziia curent n flux, n
fiind numrul maxim de octei care pot fi citii nainte ca marcajul s
devin invalid
public synchronized void markSupported() - testeaz dac fluxul accept
metodele mark i reset
37
38
Class OutputStream
Metoda write() - permite scrierea octeilor n fluxuri de ieire. Are forme
care scriu un octet, un tablou de octei sau un segment dintr-un tablou de
octei. Ca i metoda read(), blocheaz firul care ncearc s scrie pn la
terminarea operaiei.
Metoda flush() - determin scrierea imediat ntr-un flux de ieire cu
buffer.
Metoda close() - determin ca orice dat scris n flux s fie memorat
nainte ca fluxul s fie dezalocat i eliminat.
39
Class PrinStream
PrintStream(OutputStream out) constructor
Metode:
print(boolean b)
print(float f) i variantele similare
print(Object o)
print(char[] c)
println(boolean b) etc.
println(String s)
write(byte[] buf, int off, int len)
40
Exemplu:
try {
char citCar = (char)(System.in.read());
int disp = System.in.available();
System.in.skip(disp);
System.out.print(disp);
} catch (IOException e) {}
MainClass
+main(): void
PrintStream
+print(String): void
+println(String): void
<<final>>
System
+in: InputStream
+out: PrintStream
<<abstract>>
InputStream
+read(byte[]): int
+skip(int): long
+available(): int
41
42
43
BufferedStreams
Scop: To reduce this kind of overhead, the Java platform implements
buffered I/O streams. Buffered input streams read data from a memory area
known as a buffer; the native input API is called only when the buffer is
empty. Similarly, buffered output streams write data to a buffer, and the
native output API is called only when the buffer is full.
Probleme: golirea = flushing
autoflash n constructor
Buffer justification: different speeds of producer and consumer
44
File Streams
File,
FileDescriptor,
FilePermision
FileInputStream,
FileOuputStream
FileReader,
FileWriter.
45
Class File
Un obiect File reprezint un fiier din sistemul nativ. Clasa File are
constructorii:
File(String cale);
File(String cale, String nume);
File(File dir, String nume);
Parametrul cale este calea ctre fiier, nume numele, iar dir permite
utilizarea unui alt obiect File ca director.
Metodele: canRead(), canWrite(), delete(), equals(Object), exists(),
getName(), getParent(), getPath(), lastModified(), length(), list(), mkdir(),
renameTo(File), toString().
46
47
48
Exception Handling
byte b;
try {
FileInputStream fluxIn=new FileInputStream(fisierNou.dat);
b=fluxIn.read()//citeste din flux
}
catch (IOException e)
{
System.out.println(Eroare la citire +e);
}
Dac read() furnizeaz 1, citirea s-a terminat (nu mai are ce citi din flux).
49
Scrierea n fiier:
FileOutputStream outStream =new FileOutputStream(fisierIesire.dat);
sau
File fil=new File(fisierIesire.dat);
FileOutputStream outStream=new FileOutputStream(fil);
outStream.write(n); //unde n este int, boolean, float, double etc.
i la scriere trebuie tratat o excepie posibil.
50
51
RandomAccessFile
public class RandomAccessFile extends Object implements DataOutput,
DataInput
nceput
Offset
Sfrit
Fiier
Fig. x.
Tiberiu Leia: Software Engineering Input-output operations
52
53
54
55
writeByte(int)
writeBytes(String)
writeChar()
writeChars(String)
writeDouble(double) convertete un argument double ntr-un long
folosind metoda doubleToLongBits din clasa Double i apoi scrie valoarea
mrimii long n fiier ca o cantitate de cte 8 bii, cu primul octet cel
superior.
write(int)
Toate metodele de mai sus arunc IOException.
56
57
58
Provides a formatted prompt, then reads a single line of text from the console.
char[] readPassword()
Reads a password or passphrase from the console with echoing disabled
char[] readPassword(String fmt, Object... args)
Provides a formatted prompt, then reads a password or passphrase from the
console with echoing disabled.
PrintWriter writer()
Retrieves the unique PrintWriter object associated with this console.
59
Data Streams
Classes DataInputStream and DataOutputStream
sunt utilizate la crearea unor fluxuri care pot prelucra diferite tipuri de
date primitive.
Clasa DataInputStream implementeaz interfaa DataInput. Se creeaz astfel
un set de metode care permit citirea unor tipuri de date primitive (int, float,
short, etc.) i a unor obiecte (de tip tablou).
Fluxul este creat prin intermediul constructorului:
public DataInputStream(InputStream in)
60
61
62
63
64
Clasa BufferedOutputStream
Un obiect din aceast clas adaug metode la un obiect din clasa
OutputStream.
Clasa implementeaz un flux de ieire pe buffer. La apelul unei
instruciuni de ieire a unei date, aceasta este scris mai nti ntr-un buffer i
apoi n fluxul de la baza lui.
Dac bufferul se umple se nchide fluxul de ieire pe buffer sau poate fi
golit explicit.
Are doi constructori:
public BufferedOutputStream(OutputStream out) - creeaz un flux de ieire
pentru date cu bufferul avnd dimensiunea de 512 octei
public BufferedOutputStream(OutputStream out, int len) - creeaz un flux
de ieire pentru date cu bufferul avnd dimensiunea de len octei.
65
Metode:
public synchronized void flush() throws IOException - golete bufferul
fluxului de ieire fornd octeii s fie scrii n fluxul pe care se bazeaz
public synchronized void write(byte b[], int off, int len) throws IOException
- scrie len octei din tabloul de octei specificat ncepnd de la offsetul off.
66
Character Streams
Classes Reader and Writer
Pentru a transfera obiecte de tip String exist clasele Writer i
BufferedWriter:
public abstract class Writer extends Object
este folosit la scrierea de fluxuri de caractere.
O subclas a ei poate implementa metodele write(char[],int,int), flush() i
close().
Are constructorii:
Writer()
Writer(Object) - creeaz un flux de caractere Writer care se sincronizeaz
pe obiectul dat.
Clasa Writer are metodele: close(), flush(), write(char[]),
write(char[],int,int), write(int), write(String), write(String,int,int).
Tiberiu Leia: Software Engineering Input-output operations
67
Correspondences:
InputStream InputStreamReader
OutputStream OutputStreamWriter
FileInputStream FileReader
FileOutputStream FileWriter
StringBufferedInputStream StringReader (exist i StringWriter)
ByteArrayInputStream CharArrayReader
ByteArrayOutputStream CharArrayWriter
PipedInputStream PipedReader
PipedOutputStream PipedWriter
68
69
Modifiers
Exist urmtoarele corespondene ntre modificatorii comportamentelor
fluxurilor: FilterInputStream FilterReader
FilterOutputStream FilterWriter
BufferedIntputStream - BufferedReader
BufferedOutputStream BufferedWriter
PrintStream PrintWriter
LineNumberInputStream LineNumberReader
Clasa BufferedWriter definit
public class BufferedWriter extends Writer
scrie un text ca un flux de ieire de caractere. Caracterele sunt puse ntr-un
buffer astfel nct se pot realiza operaii eficiente de scriere a unui singur
caracter, a unui tablou sau a unui string.
Tiberiu Leia: Software Engineering Input-output operations
70
Are constructorii:
BufferedWriter(Writer)
BufferedWriter(Writer,int)
Metodele clasei BufferedWriter sunt similare cu cele ale clasei pe care o
extinde: close(), flush(), newLine() (scrie un separator de linie),
write(char[],int,int), write(int), write(String,int,int).
Clasele Reader i BuffredReader sunt similare cu cele dou de mai sus, dar
cu modificare sensului fluxului i evident schimbarea metodelor write() cu
read().
71
72
ieire
intrare
?BufferedOutputStream ?BufferedInputStream
?FileOutputStream
?FileInputStream
test.dat
new
new
new
writeInt( )
close( )
new
new
new
readInt( )
close( )
73
74
Are constructorii:
StringTokenizer(String str, String delim, boolean returnSimbol)
StringTokenizer(String str, String delim)
StringTokenizer(String str)
unde
str este irul de caractere care trebuie separat
delim este o list cu caractere de delimitare
returnSimbol precizeaz dac se vrea ca delimitatorul s fie returnat ca
simbol.
75
76
77
Exemplu
String str="Exemplu de sir Tokenizer";
StringTokenizer stk=new StringTokenizer(str," ");
//parcurgerea listei de simboluri
while(stk.hasMoreTokens()) {
System.out.println("simbol= " +stk.nextToken());
}
//le poate numara numai pe cele ramase
//numararea simbolurilor din sir
StringTokenizer stk1=
new StringTokenizer(str," ");
System.out.println("Nr.simboluri= "+stk1.countTokens());
stk1.nextToken();
System.out.println("Nr.simboluri= " +stk1.countTokens());
Tiberiu Leia: Software Engineering Input-output operations
78
Clasa StreamTokenizer
extinde clasa Object.
Poate prelua un flux de intrare pe care l transform n jetoane care pot fi
citite (preluate) unul cte unul.
Transformarea este controlat de o tabel i un numr de indicatoare care
pot fi puse n stri diferite artnd dac:
terminatorii de linie pot fi returnai ca jetoane sau tratai ca spaii albe care
separ jetoanele
trebuie recunoscute comentarii n stilul C++ care s fie srite
sunt convertite n litere mici caracterele indicatorilor.
Un obiect StreamTokenizer rupe coninutul unui flux dup jetoane.
Acestea sunt cele mai mici uniti recunoscute de un algoritm pentru
transformarea unui text. Se poate utiliza un astfel de obiect pentru
prelucrarea oricrui fiier text (inclusiv HTML).
79
80
81
82
83
84
85
86
87
17.6
766.6
88
Tem:
1) S se construiasc o aplicaie care culege ntrebri de la un profesor
mpreun cu rspunsurile lor.
2) S se construiasc o aplicaie care interogheaz un elev cu ntrebrile date
i i evalueaz rspunsurile. La urm i scrie nota pe ecran.
89
Object Streams
Serialization and Deserialization
Implementation of lightweight components persistency
Use to store objects or collection of objects on files
to transmit objects or collection of objects through Internet
90
91
Obiectele pot fi stocate permanent folosind un fiier. Pentru scrie sau citire
se conecteaz la acel fiier un flux de intrare sau de ieire.
Dac fluxul este unul pentru socluri de reea, obiectele pot fi reconstituite pe
o alt gazd (alt calculator) sau ntr-un alt proces (sau program).
92
Clasa ObjectInputStream
Este utilizat pentru deserializarea datelor primitive i a obiectelor scrise
cu o instan a clasei ObjectOutputStream. Ea garanteaz c tipul obiectului
citit se potrivete cu cel care se atepta s fie citit.
Cmpurile declarate transient sau static sunt ignorate de la serializare (i
deci stocare). Citirea unui obiect este similar celei de apelare a unui
constructor (la execuia operatorului new) fr a i se da argumente.
Constructorul clasei creeaz un flux de intrare pe obiecte care citete
dintr-un obiect InputStream.
Clasa ObjectInputStream are metodele: available(), close(),
defaultReadObject(), enableResolveObject(boolean), read(), read(byte[]),
read(byte[],int,int), read(int), readBoolean(), readByte(), readChar(),
readDouble(), readFloat(), readFully(byte[]), readFully(byte[],int,int),
readInt(), readLine(), readLong(), readObject(), readShort(),
readStreamHeader(), readUnsignedByte(), readUnsignedShort(),
Tiberiu Leia: Software Engineering Input-output operations
93
readUTF(), registerValidation(ObjectInputValidation,int),
resolveClass(ObjectStreamClass) i skipBytes(int).
94
Clasa ObjectOutputStream
Este utilizat la scrierea tipurilor de date primitive i a obiectelor ntr-un
flux OutputStream. Se poate scrie orice obiect care implementeaz interfaa
Serializable. Constructorul clasei creeaz un flux de ieire pe obiecte care
scrie ntr-un obiect OutputStream.
Are metodele: annotatedClass(), close(), defaultWriteObject(),
enableReplaceObject(boolean), flush(), replaceObject(Object),
reset(),write(byte[]), write(byte[],int,int), write(int), writeBoolean(boolean),
writeByte(int), writeBytes(String), writeChar(int), writeChar(String),
writeDouble(double), writeFloat(float), writeInt(int), writeLong(long),
writeObject(Object), writeShort(short), writeStreamHeader(), i
writeUTF(String).
95
Metoda writeObject() este cea care scrie obiectul n flux. Pot fi scrise cu ea
String-uri, tablouri (obiecte simple), date primitive sau obiecte complexe. Ea
este definit astfel:
public final void writeObject(Object obj) throws IOException,
InvalidClassException, NotSerializableException
Citirea obiectelor se face cu:
public final Object readObject() throws OptionalDataException,
ClassNotFoundException, IOException
Clasele care sunt serializate trebuie s implementeze interfaa Serializable
sau Externalizable.
Exempul de implementare a interfeei Serializable este dat n clasa Vector
(definit diferit de cea din pachetul java.util) a programului urmtor.
Tiberiu Leia: Software Engineering Input-output operations
96
PersistentObjectClass
Externalizable interface
adds() the methods
writeExternal() and
readExternal().
+attribute1
+method1()
97
98
Specificaia programului:
Construiete un obiect (obj1) de tip String
Construiete un obiect (obj2) de tip Vector.
Construiete un flux de ieire de tip fiier fisIesire care construiete un
fiier temp.tmp
Construiete un flux de ieire de tip obiect obIesireSerie
Serializeaz obiectul obj1 i-l scrie n fiierul temp.tmp
Serializeaz obiectul obj2 i-l scrie n fiierul temp.tmp
nchide fluxul de ieire obIesireSerie
Construiete un flux de intrare de tip fiier fisIntrare pe fiierul temp.tmp
Construiete un flux de intrare de tip obiect obIntrareSerie
Citete serial primul obiect din fiierul temp.tmp i-l depune n obiectul
obInS1
Afieaz coninutul obiectului obInS1
Tiberiu Leia: Software Engineering Input-output operations
99
Citete serial al doilea obiect din fiierrul temp.tmp i-l depune n obiectul
vctRezultat.
Afieaz coninutul obiectului vctRezultat.
Verific utilizarea obiectului vctRezultat prin apelarea metodelor sale
(scrieVector(), citesteVector())
Afiseaz rezultatele operaiilor asupra obiectului vctRezultat
nchide fluxul de intrare obIntrareSerie.
100
101
102
103
try {System.in.read();}catch(IOException e) {}
try {
//construieste un flux de intrare pt. fisier
FileInputStream fisIntrare=
new FileInputStream("temp.tmp");
//construieste un flux de intrare pt. obiecte
ObjectInputStream obIntrareSerie=
new ObjectInputStream(fisIntrare);
//primul obiect primit din fisier este:
String obInS1=(String)obIntrareSerie.readObject();
System.out.println(obInS1);//scrie primul obiect
//al doilea obiect primit din fisier este:
Vector vctRezultat=(Vector)obIntrareSerie.readObject();
System.out.println("Vector citit serial: tab[0]="+
vctRezultat.citesteVector(0)+
" tab[1]="+vctRezultat.citesteVector(1)+" tab[2]="+
vctRezultat.citesteVector(2));
Tiberiu Leia: Software Engineering Input-output operations
104
105
106
Aggregation
ClassB
ClassA
+link(ClassD)
+metB()
+link(ClassE)
+metA()
Association by
method
Association by
constructor
ClassC
Association by method
ClassD
ClassE
+metC()
+link(ClassD)
+metE()
+link(CLassE)
+metD()
Association by method
MainClass
+main()
ClassF
+metF()
107
108
Y: Salveaz i obiectul
agregat de tip ClassB
pe care l agregheaz
109
File
Student
ArrayList
+add(Object)
+1
ObjectOutputStream
+writeObject(Object)
1
ListaExcursie
+add(Object)
MainClass
ObjectInputStream
+readObject(): Object
+main()
Specification: Build 3 lists with the same students. Verify the list
persistency: Save one on a file and delete it. After that, bring back the
deleted list from the file.
Tiberiu Leia: Software Engineering Input-output operations
110
import java.util.*;
import java.io.*;
public class ListaExcursie extends ArrayList implements Serializable{
String nume;
public ListaExcursie(String numeExcursie) {
super();
nume=numeExcursie;
}
}
111
import java.io.*;
public class Student implements Serializable{
String nume;
String grupa;
public Student(String nm, String gr) {
nume=new String(nm);
grupa=new String(gr);
}
public String toString() {
return "Student"+nume+"; grupa"+grupa;
}
}
112
113
try{
ObjectOutputStream os=new ObjectOutputStream(
new FileOutputStream("temp.tmp"));
os.writeObject(lista);
os.close();
lista=null;
st1=null;
System.out.println(st1);
ObjectInputStream is=
new ObjectInputStream(new FileInputStream("temp.tmp"));
ArrayList lista2=(ArrayList) is.readObject();
System.out.println("lista: "+lista);
System.out.println("st1: "+st1);
System.out.println("lista2: "+lista2);
}catch(IOException e) {System.out.println("Eroare la deserializare");}
catch(ClassNotFoundException e) {System.out.println("Eroare: n-a gasit clasa!");
}
}
}
Tiberiu Leia: Software Engineering Input-output operations
114
115
javax.comm
Class ParallelPort
java.lang.Object
javax.comm.CommPort
javax.comm.ParallelPort
public abstract class ParallelPort
extends CommPort
A parallel communications port. ParallelPort describes the low-level interface to a parallel
communications port made available by the underlying system. ParallelPort defines the
minimum required functionality for parallel communications ports.
116
Field Summary
static int LPT_MODE_ANY
Picks the best available mode.
static int LPT_MODE_ECP
Enhanced capabilities port.
static int LPT_MODE_EPP
Extended parallel port.
static int LPT_MODE_NIBBLE
Nibble Mode.
static int LPT_MODE_PS2
Byte mode.
static int LPT_MODE_SPP
Compatibility mode.
Fields inherited from class javax.comm.CommPort
name
Constructor Summary
Tiberiu Leia: Software Engineering Input-output operations
117
ParallelPort()
Method Summary
abstract void addEventListener(ParallelPortEventListener lsnr)
Registers a ParallelPortEventListener object for
ParallelPortEvents.
abstract int getMode()
Gets the currently configured mode.
abstract int getOutputBufferFree()
Gets the number of bytes available in the output buffer.
abstract boolean isPaperOut()
Checks if the port is indicating an "Out of Paper" state.
abstract boolean isPrinterBusy()
Checks if the port is indicating a "Printer Busy" state.
abstract boolean isPrinterError()
Checks if the printer has encountered an error.
abstract boolean isPrinterSelected()
Checks if the printer is in selected state.
Tiberiu Leia: Software Engineering Input-output operations
118
boolean isPrinterTimedOut()
Checks if the printer has timed out.
abstract void notifyOnBuffer(boolean notify)
Expresses interest in being notified when the output buffer is
empty.
abstract void notifyOnError(boolean notify)
Expresses interest in being notified of port errors.
abstract void removeEventListener()
Deregisters event listener registered using
addEventListener.
abstract void restart()
Restarts output after an error.
abstract int setMode(int mode)
Sets the printer port mode.
abstract void suspend()
Suspends output.
abstract
119
disableReceiveTimeout, enableReceiveFraming,
enableReceiveThreshold, enableReceiveTimeout, getInputBufferSize,
getInputStream, getName, getOutputBufferSize, getOutputStream,
getReceiveFramingByte, getReceiveThreshold, getReceiveTimeout,
isReceiveFramingEnabled, isReceiveThresholdEnabled,
isReceiveTimeoutEnabled, setInputBufferSize, setOutputBufferSize,
toString
120
javax.comm
Class SerialPort
java.lang.Object
javax.comm.CommPort
javax.comm.SerialPort
public abstract class SerialPort
extends CommPort
An RS-232 serial communications port. SerialPort describes the low-level interface to a serial
communications port made available by the underlying system. SerialPort defines the
minimum required functionality for serial communications ports.
Author:
Jagane Sundar
See Also:
CommPort, CommPortIdentifier
Field Summary
static int DATABITS_5
5 data bit format.
Tiberiu Leia: Software Engineering Input-output operations
121
122
static
static
static
static
static
static
123
Method Summary
abstract void addEventListener(SerialPortEventListener lsnr)
Registers a SerialPortEventListener object to listen for
SerialEvents.
abstract int getBaudRate()
Gets the currently configured baud rate.
abstract int getDataBits()
Gets the currently configured number of data bits.
abstract int getFlowControlMode()
Gets the currently configured flow control mode.
abstract int getParity()
Get the currently configured parity setting.
abstract int getStopBits()
Gets the currently defined stop bits.
abstract boolean isCD()
Gets the state of the CD (Carrier Detect) bit in the UART, if
supported by the underlying implementation.
Tiberiu Leia: Software Engineering Input-output operations
124
boolean isCTS()
Gets the state of the CTS (Clear To Send) bit in the UART, if
supported by the underlying implementation.
abstract boolean isDSR()
Gets the state of the DSR (Data Set Ready) bit in the UART, if
supported by the underlying implementation.
abstract boolean isDTR()
Gets the state of the DTR (Data Terminal Ready) bit in the
UART, if supported by the underlying implementation.
abstract boolean isRI()
Gets the state of the RI (Ring Indicator) bit in the UART, if
supported by the underlying implementation.
abstract boolean isRTS()
Gets the state of the RTS (Request To Send) bit in the UART, if
supported by the underlying implementation.
abstract void notifyOnBreakInterrupt(boolean enable)
Expresses interest in receiving notification when there is a break
interrupt on the line.
abstract void notifyOnCarrierDetect(boolean enable)
abstract
125
abstract
abstract
abstract
abstract
abstract
abstract
126
abstract
abstract
abstract
abstract
abstract
abstract
overrun error.
void notifyOnParityError(boolean enable)
Expresses interest in receiving notification when there is a parity
error.
void notifyOnRingIndicator(boolean enable)
Expresses interest in receiving notification when the RI (Ring
Indicator) bit changes.
void removeEventListener()
Deregisters event listener registered using
addEventListener.
void sendBreak(int millis)
Sends a break of millis milliseconds duration.
void setDTR(boolean dtr)
Sets or clears the DTR (Data Terminal Ready) bit in the UART, if
supported by the underlying implementation.
void setFlowControlMode(int flowcontrol)
Sets the flow control mode.
void setRcvFifoTrigger(int trigger)
Deprecated. This was advisory only.
127
abstract
abstract
128
javax.comm
Class ParallelPortEvent
java.lang.Object
java.util.EventObject
javax.comm.ParallelPortEvent
All Implemented Interfaces:
java.io.Serializable
public class ParallelPortEvent
extends java.util.EventObject
A parallel port event.
129
Field Summary
int eventType
Deprecated. Replaced by getEventType method.
static int PAR_EV_BUFFER
The port's output buffer is empty.
static int PAR_EV_ERROR
An error occurred on the port.
Fields inherited from class java.util.EventObject
source
Constructor Summary
ParallelPortEvent(ParallelPort srcport,
int eventtype, boolean oldvalue, boolean newvalue)
Tiberiu Leia: Software Engineering Input-output operations
130
131
javax.comm
Class SerialPortEvent
java.lang.Object
java.util.EventObject
javax.comm.SerialPortEvent
All Implemented Interfaces:
java.io.Serializable
public class SerialPortEvent
extends java.util.EventObject
A serial port event.
Author:
Jagane Sundar
See Also:
SerialPort, SerialPortEventListener, EventObject, Serialized Form
Field Summary
static int BI
Break interrupt.
Tiberiu Leia: Software Engineering Input-output operations
132
static int CD
Carrier detect.
static int CTS
static
static
static
static
static
static
static
Clear to send.
int DATA_AVAILABLE
Data available at the serial port.
int DSR
Data set ready.
int eventType
Deprecated. Replaced by getEventType method.
int FE
Framing error.
int OE
Overrun error.
int OUTPUT_BUFFER_EMPTY
Output buffer is empty.
int PE
Parity error.
int RI
133
Ring indicator.
Fields inherited from class java.util.EventObject
source
Constructor Summary
SerialPortEvent(SerialPort srcport, int eventtype,
boolean oldvalue, boolean newvalue)
Constructs a SerialPortEvent with the specified serial port, event type, old and new
values.
Method Summary
int getEventType()
Gets the type of this event.
boolean getNewValue()
Gets the new value of the state change that caused the SerialPortEvent to
be propagated.
boolean getOldValue()
Gets the old value of the state change that caused the SerialPortEvent to
Tiberiu Leia: Software Engineering Input-output operations
134
be propagated.
Methods inherited from class java.util.EventObject
getSource, toString
135
136
137
138
139
140
141
142
143
144
145
146
Se creeaz cte un fiier antret pentru fiecare fiier .class. Metodele apar n
fiierul ClasaPrincipala.h n urmtoarea form:
JNIExport modificator JNICALL
Java_ClasaPrincipala_metodaNativa1(JNIEnv *, jobject);
Aceasta are doi parametrii chiar dac nu a fost declarat n metod nici unul.
Primul este un pointer (indicator) de interfa JNIEnv. Prin aceasta codul
nativ acceseaz parametrii i obiectele transferate din aplicaia Java. Al
doilea parametru este jobject care se refer tocmai la obiectul curent. Este
echivalent cu this din Java. Pentru o metod de instan nativ, argumentul
jobject este o referin la obiectul curent. Pentru o metod de clas nativ,
argumentul va referi clasa Java a metodei.
147
148
Exemplu:
#include <jni.h>
#include "ClasaPrincipala.h"
#include <stdio.h>
JNIExport void JNICALL Java_ClasaPrincipala_metodaNativa1(JNIEnv *,
jobject obj) {
printf("Mesaj scris de metoda nativa! \n");
}
.................
149
Tip nativ
jboolean
jbyte
jchar
jshort
jint
jlong
jfloat
jdouble
void
Lungime n bii
8, fr semn
8
16, fr semn
16
32
64
32
64
n/a
150
Obiectele Java dac sunt date ca argumente, ele sunt transmise prin
referine.
Toate referinele obiectelor Java au tipul jobject.
Se pot crea obiecte Java n metode native i returnate ca rezultate
apelatorului.
Dup implementarea metodelor native, trebuie s se construiasc
biblioteca dinamic ce este ncrcat de ctre clasa care declar metodele
native.
151
152
static {
System.loadLibrary("aritmetica");
}
//declara metodele native
public native int add(int x,int y);
public native int mult(int x,int y);
public native int comp(int x,int y);
//declara si implementeaza metode Java
public void set(int x, int y) {
xVal=x;
yVal=y;
}
public int get(int i) {
if (i==1) return xVal;
else return yVal;
}
}
153
154
155
*/
JNIEXPORT jint JNICALL Java_ClCuNative_comp
(JNIEnv *, jobject, jint, jint);
/*
* Class:
ClCuNative
* Method:
mult
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_ClCuNative_mult
(JNIEnv *, jobject, jint, jint);
#ifdef __cplusplus
}
#endif
#endif
156
157
{
printf("S-a accesat in C metoda mult(");
printf("%d",x);
printf(",");
printf("%d",y);
printf(")");
printf("\n");
return(x*y);
}
JNIEXPORT jint JNICALL
Java_ClCuNative_comp(JNIEnv *env, jobject obj, jint x, jint y)
{
printf("S-a accesat in C metoda comp(");
printf("%d",x);
printf(",");
printf("%d",y);
printf(")");
printf("\n");
if(x<=y) return y;
if(x>y) return x;
}
Tiberiu Leia: Software Engineering Input-output operations
158
159
*
****
*********
****
*
160