Documentos de Académico
Documentos de Profesional
Documentos de Cultura
CESTUNT
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Indice
UNIDAD 1: JAVA JSP ELEMENTOS BASICOS
1. INTRODUCCION
2. MODELO DE SOLUCION
3. VARIABLES
4. TIPOS DE DATOS
5. CLASES NUMERICAS
6. OPERADORES ARITMETICOS
7. OPERADOR CAST Y CONVERSIONES
8. JERARQUIA DE OPERACIONES
9. APLICACIONES
10. CONCEPTOS BASICOS DE OOP
11. JAVA SERVER PAGE (1)
APENDICE: OBJETOS HTML
APENDICE: PALABRAS RESERVADAS JAVA
INTRODUCCION
INSTRUCCIONES DE CONTROL DE PROGRAMA
INSTRUCCIONES CONDICIONALES
CONDICIONES SIMPLES
OPERADORES RELACIONALES
INSTRUCCION IF
CONDICIONES COMPUESTAS
Docente: Arturo Diaz Pulido
Lenguaje de Programacion IV
8. INSTRUCCION SWITCH
9. CONTROL SELECT
10. CONTROL CHECKBOX Y MANEJO DE EXEPCIONES
11. CONTROL RADIOBUTTON
12. CICLO FOR
13. CICLO WHILE
14. CICLO DO...WHILE
15. CONCLUSIONES ACERCA DE CICLOS
INTRODUCCION
ARREGLOS TRADICIONALES
ARREGLOS TIPO LISTA
ARREGLOS TIPO TABLA
PROCEDIMIENTOS Y FUNCIONES
PARAMETROS
VARIABLES LOCALES Y GLOBALES
FUNCIONES
ARREGLOS COMO PARAMETROS
Lenguaje de Programacion IV
3. ARCHIVOS (1)
4. ARCHIVOS (2)
5. CREACION ARCHIVOS
6. GRABACION Y LECTURA DISCO
7. BUSQUEDA EN ARCHIVO DIRECTO
8. FILTROS o CONDICIONES
9. BAJA o ELIMINACION
10. OPERACIONES CON CAMPOS
11. EDICION o MODIFICACION REGISTROS
12. GRAFICOS
Lenguaje de Programacion IV
4. TABLAS (CONTINUACION)
5. MICROSOFT ACCESS
6. JDBC SQL RESULTSET CONNECTION
7. SELECCION O DESPLIEGUE
8. INSERCCION O ADICION DE REGISTROS
9. BUSQUEDAS
10. FILTROS
11. OPERACIONES CON CAMPOS
12. BAJAS
13. EDICION DE REGISTROS
14. GRAFICOS O IMAGENES
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Class Integer
public
{
final
//
public
public
//
public
public
//
public
public
public
public
public
public
val);
public
public
public
public
public
public
public
public
class
java.lang.Integer extends
Fields
final static int **MAX_VALUE**;
final static int **MIN_VALUE**;
Constructors
**Integer**(int value);
**Integer**(String s);
Methods
double **doubleValue**();
boolean **equals**(Object obj);
float **floatValue**();
static Integer **getInteger**(String
static Integer **getInteger**(String
static Integer **getInteger**(String
java.lang.Number
nm);
nm, int val);
nm, Integer
int **hashCode**();
int **intValue**();
long **longValue**();
static int **parseInt**(String s);
static int **parseInt**(String s, int radix);
static String **toBinaryString**(int i);
static String **toHexString**(int i);
static String **toOctalString**(int i);
Lenguaje de Programacion IV
public
public
public
public
public
String
static
static
static
static
**toString**();
String **toString**(int i);
String **toString**(int i, int radix);
Integer **valueOf**(String s);
Integer **valueOf**(String s, int radix);
}
Esta clase convierte un dato de tipo int a un objeto.
Este objeto contiene un solo campo de tipo int.
Pero tambien el objeto contiene una serie de metodos para
convertir un valor int a una String y tambien para convertir una
String a int.
Ademas de otros metodos de igual utilidad.
Class Double
public final class java.lang.Double extends java.lang.Number
{
//
public
public
public
public
public
//
public
public
//
public
public
public
public
public
public
public
public
public
public
public
public
public
public
public
Fields
final static double **MAX_VALUE**;
final static double **MIN_VALUE**;
final static double **NaN**;
final static double **NEGATIVE_INFINITY**;
final static double **POSITIVE_INFINITY**;
Constructors
**Double**(double value);
**Double**(String s);
Methods
static long **doubleToLongBits**(double value);
double **doubleValue**();
boolean **equals**(Object obj);
float **floatValue**();
int **hashCode**();
int **intValue**();
boolean **isInfinite**();
static boolean **isInfinite**(double v);
boolean **isNaN**();
static boolean **isNaN**(double v);
static double **longBitsToDouble**(long bits);
long **longValue**();
String **toString**();
static String **toString**(double d);
static Double **valueOf**(String s);
Lenguaje de Programacion IV
* La misma fuente y las mismas notas de la clase anterior
Class Float
public
{
final
class
java.lang.Float extends
java.lang.Number
// Fields
public final static float **MAX_VALUE**;
public final static float **MIN_VALUE**;
public final static float **NaN**;
public final static float **NEGATIVE_INFINITY**;
public final static float **POSITIVE_INFINITY**;
// Constructors
public **Float**(double value);
public **Float**(float value);
public **Float**(String s);
// Methods
public double **doubleValue**();
public boolean **equals**(Object obj);
public static int **floatToIntBits**(float value);
public float **floatValue**();
public int **hashCode**();
public static float **intBitsToFloat**(int bits);
public int **intValue**();
public boolean **isInfinite**();
public static boolean **isInfinite**(float v);
public boolean **isNaN**();
public static boolean **isNaN**(float v);
public long **longValue**();
public String **toString**();
public static String **toString**(float f);
public static Float **valueOf**(String s);
}
Class Long
public final class java.lang.Long extends java.lang.Number
{
// Fields
public final static long MAX_VALUE;
public final static long MIN_VALUE;
// Constructors
public Long(long value);
public Long(String s);
// Methods
public double doubleValue();
Lenguaje de Programacion IV
public
public
public
public
public
public
public
public
public
public
public
public
public
public
public
public
public
Lenguaje de Programacion IV
Suma
Resta
Multiplicacion
Division
Residuo o Modulo
Lenguaje de Programacion IV
Esta funcin ocupa dos valores o datos ( base y exp) ambos de tipo
double, y regresa un resultado tambin de tipo double, ejemplo;
* resolver el problema de calcular 53
import java.io.*;
import java.lang.Math;
public class ejemplo1
{
public static void main(String args[])
{
double base =5;
double exponente=3;
double potencia =0;
potencia = Math.pow(base, exponente);
System.out.println("potencia =" +potencia);
} // cerrar main
} //cerrar clase
Lenguaje de Programacion IV
Lenguaje de Programacion IV
public final static double E;
public final static double PI;
Methods
public static double abs(double a);
public static float abs(float a);
public static int abs(int a);
public static long abs(long a);
public static double acos(double a);
public static double asin(double a);
public static double atan(double a);
public static double atan2(double a, double b);
public static double ceil(double a);
public static double cos(double a);
public static double exp(double a);
public static double floor(double a);
public static double IEEEremainder(double f1, double f2);
public static double log(double a);
public static double max(double a, double b);
public static float max(float a, float b);
public static int max(int a, int b);
public static long max(long a, long b);
public static double min(double a, double b);
public static float min(float a, float b);
public static int min(int a, int b);
public static long min(long a, long b);
public static double pow(double a, double b);
public static double random();
public static double rint(double a);
public static long round(double a);
public static int round(float a);
public static double sin(double a);
public static double sqrt(double a);
public static double tan(double a);
}
Lenguaje de Programacion IV
Ejemplo:
(int) 3.1416;
Lenguaje de Programacion IV
En toda divisin recordar agregar a uno de los dos valores el (.0), solo
que los dos elementos sean variables entonces usar el operador cast
con una de ellas.
b)// Declaracin
double potencia;
// Operacin
potencia = Math.pow ( (double)5, (double)3);
Lenguaje de Programacion IV
desplegar x, y
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Parntesis
Potencias y races
Multiplicaciones y divisiones
Sumas y restas
Dos o ms de la misma jerarqua u orden, entonces resolver
de izquierda a derecha
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Por supuesto que el browser del cliente debe estar preparado para
ejecutar applets, esto se hace teniendo constantemente actualizado
el browser (internet explorer o netscape) y estando sobre todo
seguro que en la actualizacin del browser se incluya la maquina
virtual de java.
4. Aplicacion de tipo SERVLETS, que son programas en java que
se ejecutan direcatemente en el servidor de paginas o web
server, que al ser invocado o llamado por una pc remota, el
web server compila y ejecuta el servlet, ya ejecutado se
mandan generalmente los resultados a la maquina remota,
estos resultados se mandan en forma de una pagina html,
para que la maquina remota los vea en su propio browser.
Una vez que el web server o servidor de paginas ejecuta un
servlet, lo mantiene vivo o despierto, para responder de
manera mas rapida a las peticiones siguientes que se hagan
del servlet.
5. Aplicaciones JSP (Java Server Pages), tecnologia que
combina codigo html y codigo java en un solo programa o
aplicacin, cuando al web server le piden un jsp, lo compila,
lo convierte a servlet con todas las implicaciones que se
mencionarn en el inciso anterior y manda los resultados a
la pc remota que lo solicit.
6. Beans y Java Beans, tecnologias de tipo servlet pero que
estan especializadas principalmente en mantener enlaces
constantes a bases de datos de cualquier marca (access,
oracle, mysql, etc), esto permite que una serie de varios
programas o aplicaciones a la vez esten interactuando con el
mismo java bean y por consiguiente con la base de datos.
7. Existen otra serie de aplicaciones diferentes que se pueden
construir con java, tales como aplicaciones rmi, aplicaciones
en tiempo real, ejb , pero de momento estan fuera del
Docente: Arturo Diaz Pulido
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Pero en general tanto las formas como los controles no dejan de ser
objetos en programacin y por tanto tienen sus propiedades,
mtodos y estn sujetos a eventos.
Lenguaje de Programacion IV
Lenguaje de Programacion IV
out.println("DAME LA ALTURA:<INPUT TYPE=TEXT NAME=ALTURA
value="+altura+"><BR>");
out.println("AREA:<INPUT TYPE=TEXT NAME=AREA value="+area+"><BR>");
out.println("<INPUT TYPE=SUBMIT NAME=OK VALUE=evento1 ><BR>");
out.println("</FORM>");
%>
corrida:
Lenguaje de Programacion IV
Lenguaje de Programacion IV
3.
4.
5.
6.
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
value
enabled
checked
Control Password.
Propiedades Eventos Metodos
form
OnBlur blur
name
OnFocus focus
value
enabled
Controles Text y Textareas.
Propiedades Eventos Metodos
form
OnBlur blur
name
OnFocus focus
value
enabled
Control Select.
Propiedades
Eventos
Metodos
length
OnBlur
blur
options
OnFocus focus
selectedIndex OnChange
Control Hidden.
Docente: Arturo Diaz Pulido
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Significado
==
Igual que
>
Mayor que
<
Menor que
>=
!=
Lenguaje de Programacion IV
Lenguaje de Programacion IV
out.println("DAME SUELDO:<INPUT TYPE=TEXT NAME=SUELDO
value="+sueldo+"><BR>");
out.println("EVALUACION:<INPUT TYPE=TEXT NAME=RES
value="+res+"><BR>");
out.println("<INPUT TYPE=SUBMIT NAME=OK VALUE=evento1 ><BR>");
out.println("</FORM>");
%>
Recordar que es valido usar mas de una instruccin dentro del grupo
cierto o falso del if.
Recorar ademas que para el caso de strings usar:
if ( carrera.compareTo(informatica) == 0 )
Lenguaje de Programacion IV
Lenguaje de Programacion IV
NO NEGACION
Ejemplo:
if ( (sueldo >100) && ( sexo=='m') ) etc, etc, etc.
Y recordar que para comparar strings usar;
if ( carrera.compareTo(informatica) == 0 )
Notas:
Docente: Arturo Diaz Pulido
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
break;
default: instruccin(es);
};
prog3 jsp
<%
// declarando
char letra=' ';
if(request.getParameter("OK") != null)
{
//recordar que TEXTBOX contiene una string
letra=request.getParameter("LETRA").charAt(0);
switch(letra)
{case 'a':
out.println("aguila ");
break;
case 'b': case 'B':
out.println("baca ");
break;
case 'c':
out.println("caballo ");
break;
default:
out.println("no hay ");
};
// observar que se puede escribir direcatmente a la pagina dinamica
// esto es para los flojos
};
// construyendo forma dinamica
out.println("<FORM ACTION=prog3.jsp METHOD=post>");
out.println("DAME UNA LETRA:<INPUT TYPE=TEXT NAME=LETRA
value="+letra+"><BR>");
out.println("<INPUT TYPE=SUBMIT NAME=OK VALUE=evento1 ><BR>");
out.println("</FORM>");
%>
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Prog4.jsp
<%
// declarando
String municipio="";
if(request.getParameter("OK") != null)
{
municipio =request.getParameter("MUNICIPIO");
out.println(municipio+" =");
if (municipio.compareTo("ENSENADA")==0) out.println("TIBIO");
if (municipio.compareTo("TIJUANA")==0) out.println("HELADO");
if (municipio.compareTo("MEXICALI")==0) out.println("CALIENTE");
};
// construyendo forma dinamica
out.println("<FORM ACTION=prog4.jsp METHOD=post>");
out.println("<B>MUNICIPIOS</B>");
out.println("<SELECT NAME=MUNICIPIO>");
out.println("<OPTION>ENSENADA<OPTION>TECATE<OPTION>TIJUANA<OPTION>ME
XICALI");
out.println("</SELECT>");
out.println("<INPUT TYPE=SUBMIT NAME=OK VALUE=evento1 ><BR>");
out.println("</FORM>");
%>
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Notas:
1. grabarlo y subirlo como prog5. jsp a tu sitio en
programacionfacil.com
2. La propiedad name debera ser diferente en cada checkbox
usado, la propiedad checked se usa para que aparezca ya
palomeado o seleccionado el control.
3. Cuando se activa prog5 jsp, esta forma manda el par NAME =
on solo de los checkbox que fuern seleccionados.
Docente: Arturo Diaz Pulido
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Try{
Instrucciones normales de java;
} catch(tipo de error o excepcion var de error){ inst de aviso o correc
de error puede incluir la var de error ;
};
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
for (int x=1; x<=10; x++)
{ out.println("x= "+x+"<br>"); };
%>
QUE
DESPLIEGUE
LOS
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
notas:
Recordar tambin que la primera posicin o rengln en una lista es
la posicin o rengln 0 (cero).
Prog10 jsp
<%! int edad[]=new int[5], ren=0; %>
<%
String temp1=request.getParameter("INSERTAR");
if(temp1==null)temp1=" ";
if(temp1.compareTo("insertar")==0){
if(ren < 5){
edad[ren]=Integer.parseInt(request.getParameter("EDAD"));
ren=ren+1;};
if(ren==5){out.print("ARREGLO LLENO");};
};
if(request.getParameter("SUMAR") != null )
{
// operaciones
for(ren=0; ren<=4; ren++) edad[ren]=edad[ren]* 12;
// DESPLEGANDO EN OBJETO LISTA DE HMTL CON BULLETS FOR NORMAL
out.println("EDADES EN MESES");
out.println("<UL>");
for(ren=0;ren<=4;ren++)
{out.println("<LI>"+edad[ren]); };
out.println("</UL>");
// DESPLEGANDO EN OBJETO LISTA DE HMTL FOR NORMAL
out.println("<OL>");
for(ren=0; ren<=4; ren++)
{ out.println("<LI>"+edad[ren]); };
out.println("</OL>");
// DESPLEGANDO USANDO OBJETO TABLE DE HMTL FOR NORMAL
out.println("<table border=2><tr><th>EDADES EN MESES</th></tr>");
for(ren=0; ren<=4; ren++)
{ out.println("<tr><td>"+edad[ren]+"</td></tr>"); };
};
// construyendo forma dinamica
out.println("<FORM ACTION=prog10.jsp METHOD=post>");
out.println("DAME EDAD:"+ren+"<INPUT TYPE=TEXT NAME=EDAD>");
out.println("<INPUT TYPE=SUBMIT NAME=INSERTAR VALUE=insertar
><BR>");
out.println("<INPUT TYPE=SUBMIT NAME=SUMAR VALUE=sumar><BR>");
out.println("</FORM>");
%>
Notas:
Lenguaje de Programacion IV
Lenguaje de Programacion IV
String *ciudad[]={tecate,
ensenada};
tijuana,
mexicali,
rosarito,
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Notas:
Observar el formato de declaracin y como se controlan los
indices de captura reng, col.
Notas:
El for reng tiene su propio grupo de instrucciones encerrados
entre {}. Mientras que el for col solo tiene una instruccin que
ejecutar el print(celda ), el ultimo print(</termina renglon) es del
ciclo for reng).
El renglon de encabezado solo tiene una celda, por eso los otros
dos renglones con mas celdas se ajustarn por su cuenta, para
corregir esta situacin revisar su tutorial de html(TABLE).
Para inicializar tablas, se debera usar el siguiente formato:
tipodato nomtabla[2][3]={1,2,3,4,5,6 };
TAREAS PROGRAMACION JAVA JSP
1. CONSTRUIR UN CUADRO QUE CONTENGA LOS COSTOS
FIJOS DE CUATRO PRODUCTOS CUALESQUIERA, QUE SE
PRODUCEN EN TRES PLANTAS DIFERENTES DE UNA
EMPRESA MAQUILADORA.
2. CONSTRUIR UN CUADRO QUE CONTENGA LOS INGRESOS
MENSUALES POR VENTAS DURANTE LOS TRES PRIMEROS
MESES DEL AO DE CUATRO SUCURSALES DE UNA
CADENA DE AUTO REFACCIONES, AGREGAR AL FINAL
UNA LISTA QUE MUESTRE LOS INGRESOS MENSUALES
TOTALES POR MESES Y UNA SEGUNDA LISTA QUE
MUESTRE LOS INGRESOS MENSUALES TOTALES POR
SUCURSAL(2 programas uno capturado y otro
inicializado).
Docente: Arturo Diaz Pulido
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Prog12.jsp
<%!
int base=0,altura=0; double area=0;
void proc1(){
area= base * altura / 2.0 ;};
%>
<%
// no usar objetos request y out fuera de scriptlet
// porque no estan creados por java todavia
if(request.getParameter("OK") != null)
{
base = Integer.parseInt(request.getParameter("BASE"));
altura = Integer.parseInt(request.getParameter("ALTURA"));
// llamando o invocando procedimiento uno
proc1();
};
// construyendo forma dinamica
out.println("<FORM ACTION=prog12.jsp METHOD=post>");
out.println("DAME
LA
BASE:<INPUT
TYPE=TEXT
NAME=BASE
value="+base+"><BR>");
out.println("DAME
LA
ALTURA:<INPUT
TYPE=TEXT
NAME=ALTURA
value="+altura+"><BR>");
out.println("AREA:<INPUT TYPE=TEXT NAME=AREA value="+area+"><BR>");
out.println("<INPUT TYPE=SUBMIT NAME=OK VALUE=evento1 ><BR>");
out.println("</FORM>");
%>
Lenguaje de Programacion IV
d) Fin de menu.
Lenguaje de Programacion IV
Lenguaje de Programacion IV
out.println("DAME
LA
BASE:<INPUT
TYPE=TEXT
NAME=BASE
value="+base+"><BR>");
out.println("DAME
LA
ALTURA:<INPUT
TYPE=TEXT
NAME=ALTURA
value="+altura+"><BR>");
out.println("AREA:<INPUT TYPE=TEXT NAME=AREA value="+area+"><BR>");
out.println("<INPUT TYPE=SUBMIT NAME=OK VALUE=evento1 ><BR>");
out.println("</FORM>");
%>
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
<%
// no usar objetos request y out fuera de scriptlet
// porque no estan creados por java todavia
if(request.getParameter("OK") != null)
{
int eta[]={3,4,5};
decl1(eta);
for(r=0;r<=2;r++)
out.println("eta="+eta[r]+"<br>");
};
// construyendo forma dinamica
out.println("<FORM ACTION=prog15.jsp METHOD=post>");
out.println("<INPUT TYPE=SUBMIT NAME=OK VALUE=evento1 ><BR>");
out.println("</FORM>");
%>
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
void desplegar(){
System.out.println(alumno.nombre);
System.out.println(alumno.edad);
};
} // termina la clase
Programa 16.jsp;
<%!
static class alumno{
static String nombre=" ";
static int edad=0;
void alumno(){};
static void inicializar(){
alumno.nombre="pepe el toro";
alumno.edad=18; };
};
%>
<%
if(request.getParameter("OK") != null)
{
alumno.inicializar();
out.println(alumno.nombre);
out.println(alumno.edad);
};
// construyendo forma dinamica
out.println("<FORM ACTION=prog16.jsp METHOD=post>");
out.println("<INPUT TYPE=SUBMIT NAME=OK VALUE=evento1 ><BR>");
out.println("</FORM>");
%>
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
out.println("ESTATURA :<INPUT TYPE=TEXT NAME=ESTATURA><BR>");
out.println("<INPUT TYPE=SUBMIT NAME=INSERTAR VALUE=GRABAR ><BR>");
out.println("</FORM>");
%>
size() Returns the current value of the counter written, the number of
bytes written to this data output stream so far.
write(byte[]
b,
int
off,
int
len)
void Writes len bytes from the specified byte array starting at offset off to
the underlying output stream.
void
write(int b) Writes the specified byte (the low eight bits of the argument
b) to the underlying output stream.
Lenguaje de Programacion IV
void
void
writeByte(int
v)
Writes out a byte to the underlying output stream as a 1-byte value.
void
WriteBytes (String s) Writes out the string to the underlying output stream
as a sequence of bytes.
void
writeChar(int v) Writes a char to the underlying output stream as a 2byte value, high byte first.
void
writeDouble(double
v)
Converts the double argument to a long using the doubleToLongBits
void
method in class Double, and then writes that long value to the
underlying output stream as an 8-byte quantity, high byte first.
writeFloat(float v) Converts the float argument to an int using the
void floatToIntBits method in class Float, and then writes that int value
to the underlying output stream as a 4-byte quantity, high byte first.
writeInt(int
v)
void Writes an int to the underlying output stream as four bytes, high byte
first.
writeLong(long
v)
void Writes a long to the underlying output stream as eight bytes, high byte
first.
writeShort(int
v)
void Writes a short to the underlying output stream as two bytes, high byte
first.
void
writeUTF (String str) writes a string to the underlying output stream using
UTF-8 encoding in a machine-independent manner.
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
out.println("<FORM ACTION=prog18.jsp METHOD=post>");
out.println("<INPUT TYPE=SUBMIT NAME=LECTURA VALUE=leer ><BR>");
out.println("</FORM>");
%>
Notas:
Observar en codigo que ahora se usan FILEINPUTSTREAM Y
DATAINPUTSTREAM como clases.
En fileinputstream solo se uso el parametro de abrir archivo(no el
true de append) como ya se menciono estas clases se especializan
en archivos secuenciales.
El ciclo de lectura se realiza con un while(true) los metodos de
DATAINPUTSTREAM SON:
Method Summary
int
read(byte[]
See the general contract of the read method of DataInput.
b)
int
read(byte[]
b,
int
off,
int
len)
See the general contract of the read method of DataInput.
readBoolean()
boolean See the general contract of the readBoolean method of
DataInput.
byte
readByte()
See the general contract of the readByte method of DataInput.
char
readChar()
See the general contract of the readChar method of DataInput.
double
readDouble()
See the general contract of the readDouble method of DataInput.
float
readFloat()
See the general contract of the readFloat method of DataInput.
void
readFully(byte[]
b)
See the general contract of the readFully method of DataInput.
Lenguaje de Programacion IV
void
readFully(byte[]
b,
int
off,
int
len)
See the general contract of the readFully method of DataInput.
int
readInt()
See the general contract of the readInt method of DataInput.
String
with: BufferedReader d
= new BufferedReader(new InputStreamReader(in)); |
| long | readLong()
See the general contract of the readLong method of DataInput.
|
readShort()
short See the general contract of the readShort method of
DataInput.
readUnsignedByte()
int
See the general contract of the readUnsignedByte
method of DataInput.
readUnsignedShort()
int
See the general contract of the readUnsignedShort
method of DataInput.
readUTF()
String
See the general contract of the readUTF method of
DataInput.
readUTF(DataInput
in)
static Reads from the stream in a representation of a Unicode
String
character string encoded in Java modified UTF-8 format;
this string of characters is then returned as a String.
skipBytes(int
n)
int
See the general contract of the skipBytes method of
DataInput.
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Codigo prog19.Java:
<%@ page import="java.io.*" %>
<%
// declarando
int clave=0;int claveb=0;String nombre=""; float estatura=0;
// creando un objeto de tipo archivo
DataInputStream archivo = null;
if(request.getParameter("BUSCAR") != null)
{
// construyendo tabla html
out.println("<HTML><TABLE Border=10 CellPadding=5><TR>");
out.println("<th
bgcolor=Green>CLAVE</th><th
bgcolor=White>NOMBRE</th><th bgcolor=Red>ESTATURA</th></TR>");
// capturando clave a buscar
claveb=Integer.parseInt(request.getParameter("CLAVEB"));
try {
// abriendo archivo
archivo
=
new
DataInputStream(new
FileInputStream("c:\\archivo1.dat"));
while(true){
clave=archivo.readInt();
nombre=archivo.readUTF();
estatura=archivo.readFloat();
if (claveb==clave){
out.println("<TR>");
out.println("<TD>"+clave+"</TD>");
out.println("<TD>"+nombre+"</TD>");
out.println("<TD>"+estatura+"</TD>");
out.println("</TR>");
} } }
catch(FileNotFoundException fnfe) {}
catch (IOException ioe) {};
archivo.close();
};
// construyendo forma dinamica
out.println("<FORM ACTION=prog19.jsp METHOD=post>");
out.println("CLAVE BUSCAR:<INPUT TYPE=TEXT NAME=CLAVEB><BR>");
out.println("<INPUT TYPE=SUBMIT NAME=BUSCAR VALUE=buscar><BR>");
out.println("</FORM>");
%>
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
out.println("<TD>"+estatura+"</TD>");
out.println("</TR>");
} } }
catch(FileNotFoundException fnfe) {}
catch (IOException ioe) {};
archivo.close();
};
// construyendo forma dinamica
out.println("<FORM ACTION=prog20.jsp METHOD=post>");
out.println("ESTATURA >=:<INPUT TYPE=TEXT NAME=ESTATURA><BR>");
out.println("<INPUT TYPE=SUBMIT NAME=FILTRAR VALUE=Filtrar><BR>");
out.println("</FORM>");
%>
Lenguaje de Programacion IV
Lenguaje de Programacion IV
Lenguaje de Programacion IV
archivot.close();
// eliminando original renombrando temporal
File file1 = new File("c:\\archivo1.dat");
File file2 = new File("c:\\temp.dat");
if (file1.exists()) {file1.delete();};
file2.renameTo(file1);
// avisando
out.println("REGISTRO ELIMINADO");
};
// construyendo forma dinamica
out.println("<FORM ACTION=prog21.jsp METHOD=post>");
out.println("CLAVE ELIMINAR:<INPUT TYPE=TEXT NAME=CLAVEB><BR>");
out.println("<INPUT TYPE=SUBMIT NAME=ELIMINAR VALUE=Eliminar><BR>");
out.println("</FORM>");
%>
Lenguaje de Programacion IV
Lenguaje de Programacion IV
catch (IOException ioe) {};
// cerrando archivos
archivo.close();
archivot.close();
// eliminando original renombrando temporal
File file1 = new File("c:\\archivo1.dat");
File file2 = new File("c:\\temp.dat");
if (file1.exists()) {file1.delete();};
file2.renameTo(file1);
// avisando
out.println("ESTATURAS SUMADAS ");
};
// construyendo forma dinamica
out.println("<FORM ACTION=prog22.jsp METHOD=post>");
out.println("<INPUT TYPE=SUBMIT NAME=SUMAR VALUE=EST+5><BR>");
out.println("</FORM>");
%>
Lenguaje de Programacion IV
Lenguaje de Programacion IV
clave=archivo.readInt();
nombre=archivo.readUTF();
estatura=archivo.readFloat();
if (claveb==clave){
out.println("<FORM ACTION=prog23.jsp METHOD=post>");
out.println("CLAVE
:<INPUT
TYPE=TEXT
NAME=CLAVE
value="+clave+"><BR>");
out.println("<INPUT TYPE=HIDDEN NAME=CLAVEB value="+claveb+"><BR>");
out.println("NOMBRE
:<INPUT
TYPE=TEXT
NAME=NOMBRE
value=\""+nombre+"\"><BR>");
out.println("ESTATURA
:<INPUT
TYPE=TEXT
NAME=ESTATURA
value="+estatura+"><BR>");
out.println("<INPUT TYPE=SUBMIT NAME=EDITAR VALUE=editar><BR>");
out.println("</FORM>");
}
} }
catch(FileNotFoundException fnfe) {}
catch (IOException ioe) {};
archivo.close();
};
// codigo de edicion
String temp2=request.getParameter("EDITAR");
if(temp2==null)temp2=" ";
if(temp2.compareTo("editar")==0){
try {
// abriendo archivos
archivo
=
new
DataInputStream(new
FileInputStream("c:\\archivo1.dat"));
archivot
=
new
DataOutputStream(new
FileOutputStream("c:\\temp.dat",true));
// cargando clave de edicion
claveb=Integer.parseInt(request.getParameter("CLAVEB"));
while(true){
clave=archivo.readInt();
nombre=archivo.readUTF();
estatura=archivo.readFloat();
if (claveb != clave){
archivot.writeInt(clave);
archivot.writeUTF(nombre);
archivot.writeFloat(estatura);
}
else{
// capturando y grabando nuevos datos
clave=Integer.parseInt(request.getParameter("CLAVE"));
nombre=request.getParameter("NOMBRE");
estatura=Float.parseFloat(request.getParameter("ESTATURA"));
archivot.writeInt(clave);
archivot.writeUTF(nombre);
archivot.writeFloat(estatura);
};
}}
Lenguaje de Programacion IV
catch(FileNotFoundException fnfe) {}
catch (IOException ioe) {};
// cerrando archivos
archivo.close();
archivot.close();
// eliminando original renombrando temporal
File file1 = new File("c:\\archivo1.dat");
File file2 = new File("c:\\temp.dat");
if (file1.exists()) {file1.delete();};
file2.renameTo(file1);
// avisando
out.println("REGISTRO EDITADO");
};
// construyendo forma dinamica
out.println("<FORM ACTION=prog23.jsp METHOD=post>");
out.println("CLAVE ELIMINAR:<INPUT TYPE=TEXT NAME=CLAVEB><BR>");
out.println("<INPUT TYPE=SUBMIT NAME=BUSCAR VALUE=buscar><BR>");
out.println("</FORM>");
%>
Lenguaje de Programacion IV
Lenguaje de Programacion IV
claveb=Integer.parseInt(request.getParameter("CLAVEB"));
try {
// abriendo archivo
archivo
=
new
DataInputStream(new
FileInputStream("c:\\archivo1.dat"));
while(true){
clave=archivo.readInt();
nombre=archivo.readUTF();
estatura=archivo.readFloat();
foto=archivo.readUTF();
if (claveb==clave){
out.println("<TR>");
out.println("<TD>"+clave+"</TD>");
out.println("<TD>"+nombre+"</TD>");
out.println("<TD>"+estatura+"</TD>");
out.println("<TD><img
src=http:\\\\localhost\\progs\\"+foto+"></TD>");
out.println("</TR>");
} } }
catch(FileNotFoundException fnfe) {}
catch (IOException ioe) {};
archivo.close();
};
// construyendo forma dinamica
out.println("<FORM ACTION=prog24.jsp METHOD=post>");
out.println("CLAVE BUSCAR:<INPUT TYPE=TEXT NAME=CLAVEB><BR>");
out.println("<INPUT TYPE=SUBMIT NAME=BUSCAR VALUE=buscar><BR>");
out.println("</FORM>");
%>
nota:
Observar que en img src debe ir la direccin internet del servidor por
ejemplo http:\\misitio.com\pato.jpg, sin embargo en el programa
se esta usando http:\\\\localhost\\pato.jpg, en cuanto a localhost
se puede sustituir por el dominio ejemplo laurosoto.com, y en
cuanto
porque
se
usaron
cuatro
\\
recordar que en java dentro de una string las secuencias de escape (
\a, \r etc) van precedidas del simbolo \, por esa causa para mandar
un \ a la pagina se tiene que usar la secuencia de escape
y
como
la
direccin
incluia
Lenguaje de Programacion IV