Send data from a txt to Java

0

Well, my problem is as follows.

My program has to read the data from a .txt and get the average and classify them.

I managed to do it but entering the numbers directly from the code. int age [] = {3,12,1,20,52,10,3,20,99,12,52,4,43,20,99};

And until I got it to print my txt data, the problem is that I want the data to enter the txt to be read by the program to get the average and classify them, so that as my program reads Int and what I wrote, so I want you to read from my txt.

package edades01;
// Ramirez Nava Diego Isair 2S1
import java.io.*;
public class Edades01 {
    public static void main(String[] args) {

        int edad[]={3,12,1,20,52,10,3,20,99,12,52,4,43,20,99};
        Edades01.Mostrar(edad); 
        Edades01 a=new Edades01();//crear un objeto de la clase edad01
        a.promedioedad();

        //lee el archivo edadestxt

        System.out.println(a.edadestxt("C:\Archivos P\JavaApplication\edades.txt"));

    }
    static int niños=0;
    static int adolescentes=0;
    static int adultos=0;
    static int adultosmayores=0;
    static double promedioNiños=0;
    static double promedioAdolescentes;
    static double promedioAdultos;
    static double promedioMayores;

    public static void Mostrar(int edad[]){

        for(int a=0;a<edad.length;a++){
            System.out.print("\n"+edad[a]+"\n");
            if(edad[a]<11){
                niños++;
                promedioNiños+=edad[a];
            }
            if(edad[a]>=12 && edad[a]<=17){
                adolescentes++;
                promedioAdolescentes+=edad[a];
            }
            if(edad[a]>=18 && edad[a]<=59){
                adultos++;
                promedioAdultos+=edad[a];
            }
            if(edad[a]>60 && edad[a]<105){
                adultosmayores++;
                promedioMayores+=edad[a];
            }
       }

       System.out.print("Poblacion: "+edad.length);
       System.out.print("niños: "+niños+"\n");
       System.out.print("adolescentes: "+adolescentes+"\n");
       System.out.print("adultos: "+adultos+"\n");
       System.out.print("adultos mayores: "+adultosmayores+"\n");
   }

   public void promedioedad(){
       System.out.println("promedio niños es: "+(promedioNiños / niños ));
       System.out.println("promedio niños es: "+(promedioAdolescentes / 
adolescentes ));
       System.out.println("promedio niños es: "+(promedioAdultos / adultos ));
       System.out.println("promedio niños es: "+(promedioMayores / adultosmayores 
)); 
    }

                //LECTURA DE TEXTO PLANO CON METODO TRY Y CATCH
    public String edadestxt(String direccion){ //mandar a llamar la direccion 
del archivo

        String texto="";

        try{
            BufferedReader bf=new BufferedReader(new FileReader(direccion)); // se crea 
el objeto y mandar a llamar la direcion con filereader
            String temp="";
            String bfRead;

            System.out.println("*****//LECTURA DE TEXTO EDADES.TXT//*****");

            while((bfRead = bf.readLine())!=null){ //realiza ciclo mientras bfRead tiene datos
                temp = temp +bfRead+"\n"; //guarda el texto del archivo

            }
            texto=temp;
        }catch(Exception e){
            System.err.println("El archivo no existe");
            e.printStackTrace();
        }
        return texto; 
     }
 }
    
asked by Diego Isair Ramirez 06.06.2018 в 06:00
source

1 answer

1

I will assume that the file has a single line and the format is value, value, value ... (Example: 3,12,1,20,52,10,3,20,99,12, 52,4,43,20,99)

public int[] leerFichero(String pathFichero) {
        //Inicializamos el array que devolveremos
        int[] array;

        //Leemos la linea del fichero
        BufferedReader br = null;
        String text = null;
        try {
            br = new BufferedReader(new FileReader(new File(pathFichero)));
            text = br.readLine();
        } catch (IOException e) {
            System.out.println("La lectura del fichero ha fallado.");
        }finally {
            try{
                br.close();
            } catch (Exception e){
                e.printStackTrace();
            }
        }

        //Convertimos ese texto en el array de int que manejaremos
        String[] elementos = text.split(",");
        array = new int[elementos.length];
        for (int i = 0; i < elementos.length; i++) {
            array[i] = Integer.parseInt(elementos[i]);
        }

        return array;
    }

I have not put any type of error control in case the file does not exist, has other formats, or is a character other than numbers, so I invite you to investigate and that you add depending on your needs and helping you to understand the code better, as you could also try to tinker with other file formats and to inform you a bit more about data persistence, since it is something basic in programming.

    
answered by 06.06.2018 в 11:10