Está en la página 1de 5

ARCHIVOS SECUENCIALES Package Secuencial;

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader;

/** * * @author Karla Jimenez */ public class Main {

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

BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); do{ switch(Menu(in)){

case 1:{ Secuential R = new Secuential("Nuevo"); String name; System.out.println("Por favor Ingrese el nombre del archivo:"); name= in.readLine(); String uIn; System.out.println("Ingrese el Texto para el archivo"); uIn= in.readLine(); R.write(uIn); }break;

case 2:{ String name; System.out.println("Por favor Ingrese el nombre del archivo:"); name= in.readLine(); Secuential Aux = new Secuential(name); System.out.println("----"); System.out.println(Aux.read()); System.out.println("----"); }break;

case 3:{ System.exit(0); }break; } }while (true); } public static int Menu(BufferedReader read) throws IOException{ int opc; do{ System.out.println("Por favor Eliga una Opcion:"); System.out.println(""); System.out.println("1.- Escribir un nuevo Archivo"); System.out.println("2.- Leer un Archivo"); System.out.println("3.- Salir"); opc= Integer.parseInt(read.readLine()); }while (opc<1||opc>3);

return opc; } }

ARCHIVOS SECUENCIALES
package Secuencuial;

import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException;

/** * * @author TbR */ public class Secuencial { /** la clase secuential se refiere al metodo de acceso secuencial, emulando los comportamientos del acceso secuencial * a los archivos, pero por medio de objetos de java. */ FileOutputStream fos; //abrv. de File Output Stream, es el flujo que nos sirve para la variable de entrada de datos de usuario. FileInputStream fin; File Ax; static String path= "File";

public Secuencial(String nombreFichero) throws IOException{ Ax = new File(path+nombreFichero+".txt");

if (!Ax.exists()){ Ax.createNewFile(); } }

public void write (String entrada) throws FileNotFoundException, IOException{ fos = new FileOutputStream(Ax,true); //sera true por que cada vez que ingresemos archivo, se aadira if (entrada==null || entrada.length()==0){ return; } fos.write(entrada.getBytes()); //guardar texto } public String read() throws FileNotFoundException, IOException{ byte [] by = new byte[(int)Ax.length()]; fin = new FileInputStream(Ax);

if(Ax.length()==0){ System.out.println("Error 404: File Not Found"); return ""; }

if (fin!=null){ fin.read(by);

} return new String(by); }

public void close() throws IOException{ if (fin!=null&&fos!=null ){ fin.close(); fos.close(); } }

También podría gustarte