This discussion is archived
3 Replies Latest reply: Feb 26, 2013 9:46 AM by 939520 RSS

How to modify a record in a file.txt

993309 Newbie
Currently Being Moderated
I got this problem:

I had to create a file in java which can register the name, the last name ,and the id number of a student. Until now I could made it and also I could make the program to register the number of students that I want to insert into the file, but the thing is that I had a struggle at the time of modifying certain record in the file. This is what I have done:

package universitario;
import java.io.*;
import universitario.Estudiantes.Estudiante;
import java.util.Scanner;
import java.io.PrintStream;
import java.io.FileReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.lang.String;

import java.io.File;

public class Central {
static Scanner miscaner = new Scanner (System.in);

static int NumerodeControl;
static String Nombre ;
static String Apellido;
static String Carrera;




public static Estudiante open() throws Exception {
String nombreFichero = "Archivo.txt";
String strFilename = "Archivo.txt";
Estudiante majoring = new Estudiante();
//Declarar una variable FileReader

FileReader fr = null;

try {

//Abrir el fichero indicado en la variable nombreFichero

fr = new FileReader(nombreFichero);

//Leer el primer carácter

//Se debe almacenar en una variable de tipo int

int caract = fr.read();

//Se recorre el fichero hasta encontrar el carácter -1

// que marca el final del fichero

while(caract != -1) {

//Mostrar en pantalla el carácter leído convertido a char

System.out.print((char)caract);

//Leer el siguiente carácter

caract = fr.read();

}

}

catch (FileNotFoundException e) {

//Operaciones en caso de no encontrar el fichero

System.out.println("Error: Fichero no encontrado");

//Mostrar el error producido por la excepción

System.out.println(e.getMessage());

}

catch (Exception e) {

//Operaciones en caso de error general

System.out.println("Error de lectura del fichero");

System.out.println(e.getMessage());

}

finally {

//Operaciones que se harán en cualquier caso. Si hay error o no.

try {

//Cerrar el fichero si se ha abierto

if(fr != null)
fr.close();

}

catch (Exception e) {

System.out.println("Error al cerrar el fichero");

System.out.println(e.getMessage());

}
return majoring;
}
}


public static void main(String[] args) throws Exception {
String mainAnswer = "Q", answer = "N";
Scanner scnr = new Scanner(System.in);

System.out.println("Instituto Tecnologico de Cd Victoria");

System.out.println("Que desea hacer?");
System.out.println("R - Registrar a un alumno");
System.out.println("V - Ver la informacion del archivo");
System.out.println("S - Salir");
System.out.println("M - Modificar registro");

System.out.print("Escribe la opcion? ");
mainAnswer = scnr.next();



if( (mainAnswer.equals("r")) || (mainAnswer.equals("R")) ) {

PrintStream DDescritor = new PrintStream("Archivo.txt");
System.out.println("Cuantos alumnos quieres registrar");
Scanner c= new Scanner(System.in);

int alumnos= c.nextInt();
int x[];
x= new int[alumnos];


System.out.println("--Ingresa la informacion del alumno--");
for ( int i=1;i<=x.length;i++){

System.out.print("Numero de Control del alumno " i ":");
NumerodeControl = miscaner.nextInt();
DDescritor.println(NumerodeControl);

System.out.print("Nombre: " );
Nombre = miscaner.next();
DDescritor.println(Nombre);

System.out.print("Apeido: ");
Apellido = miscaner.next();
DDescritor.println(Apellido);

System.out.print("Carrera: ");
Carrera = miscaner.next();
DDescritor.println(Carrera);

}


}



else
if( (mainAnswer.equals("v")) || (mainAnswer.equals("V")) ) {

Estudiante str= open();


}

if( (mainAnswer.equals("m")) || (mainAnswer.equals("M")) ) {



PrintStream Descritor = new PrintStream("Archivo1.txt");
Scanner d= new Scanner(System.in);

System.out.println("Que registro quieres modificar");
int alumnoss= d.nextInt();
int y[];
y= new int[alumnoss];
for ( int j=1;j<=y.length;j++){






System.out.print("Numero de Control: ");
NumerodeControl = miscaner.nextInt();
Descritor.println(NumerodeControl);

System.out.print("Nombre: " );
Nombre = miscaner.next();
Descritor.println(Nombre);

System.out.print("Apellido: ");
Apellido = miscaner.next();
Descritor.println(Apellido);

System.out.print("Carrera: ");
Carrera = miscaner.next();
Descritor.println(Carrera);


}

System.out.println("Archivo creado");
}

System.out.println ("Adios");


}

}





I hope you can help me I really aprecciate it
  • 1. Re: How to modify a record in a file.txt
    Kayaman Guru
    Currently Being Moderated
    First, format the code so it's readable. You do that by putting it between
     tags.
    Secondly, state your problem clearly.                                                                                                                                                                                                                                                            
  • 2. Re: How to modify a record in a file.txt
    gimbal2 Guru
    Currently Being Moderated
    990306 wrote:
    I had to create a file in java which can register the name, the last name ,and the id number of a student. Until now I could made it and also I could make the program to register the number of students that I want to insert into the file, but the thing is that I had a struggle at the time of modifying certain record in the file. This is what I have done:
    They are not records, they are lines. If you search using the proper simplified terminology you will probably get more search results in your research.

    Generally you don't "modify a line" - you load the file, modify the data and then create a new file, possibly overwriting the original one. With the RandomAccessFile class you have some control over writing to a particular position in a file, but I wouldn't really recommend using it. Creating a new file is way simpler.
  • 3. Re: How to modify a record in a file.txt
    939520 Explorer
    Currently Being Moderated
    On an unrelated note, you may want to specify the path to where the file is located and not just its name.

    Example:

    From:
    String strFilename = "Archivo.txt";
    To:
    String strFilename = "C:/myProgram/Archivo.txt";

    You may also consider researching the difference between absolute paths (the above is an example) verses relative paths.

    *******
    You might also consider creating two functions to read and write to a file as follows:
    public List<String> getLines(String filePathAndName)

    public void writeLines(String filePathAndName, List<String> lines)

    *****
    Lastly, you may want to search Google to see if there are better examples of how to read and write to a file.

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points