Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

304
Views
Java lee el archivo de texto y combina diferentes líneas juntas

Digamos que tenemos el siguiente archivo de texto con una identificación (no única), nombre y número

 1 Hello 3 1 Goodbye 2 1 Hello 6 1 Goodbye 5

No están en la misma línea y me gustaría poder sumarlos y poner eso en una variable. Estos no necesariamente estarían uno al lado del otro de esta manera, por lo que tendría que estar en una declaración if si la identificación y el nombre son similares, luego agregue los números.

Me gustaría poder obtener esto como mi salida.

 Hello 9 Goodbye 7

Entonces, tendría que leer todo el archivo antes de generar algo, ¿cómo se haría esto?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

 File file = new File("your/file/path"); String line = ""; try (BufferedReader reader = new BufferedReader(new FileReader(file))) { while ((line = reader.readLine()) != null) { // the algorithm that YOU should develop //or fail to develop and ask about to group things etc. } } catch (IOException ex) { ex.printStackTrace(); }
over 4 years ago · Santiago Trujillo Report

0

Aquí hay una solución rápida y sucia que usa Java 8 stream api y Java 7 NIO.2 api:

 // read all lines from the file Files.readAllLines(Paths.get("<path_to_your_file>")) // begin the stream .stream() // split every line by whitespaces // to get arrays like [1, "Hello", 3], [1, "Goodbye", 2]... .map(s -> s.split("\\s+")) // collecting to a map, grouping by the String {firstColumn}-{secondColumn} .collect(Collectors.groupingBy(split -> split[0] + "-" + split[1], // downstream collector sums the 3rd column after parsing them as long Collectors.summingLong(split -> Long.parseLong(split[2])))) // so we have Map<String, Long> with entries like {1-Hello -> 9}, {2-Goodbye -> 7} .forEach((key, value) -> // we print these entries one each line (println) // by taking the part after dash of key, // and a space between key and value, like: Hello 9 System.out.println(key.split("-")[1] + " " + value));

Tenga en cuenta que esta solución está lejos de ser completa, por ejemplo:
1- Lee todo el archivo en la memoria, por lo que si el archivo es demasiado grande puede causar problemas (gran montón asignado, OutOfMemoryError s, etc.). Sería mejor si se hiciera por streaming.

2- Si se permite que el "Nombre" tenga espacios en blanco, la división con espacios en blanco fallará; eso requeriría un trabajo adicional. La solución asume que cada línea tiene exactamente 3 "columnas", separadas por espacios en blanco.

3- Si se permite que el "Nombre" tenga guiones ( - ), la división por guiones mientras se imprime la salida daría un resultado incorrecto. En realidad, la agrupación debe hacerse usando una clase de clasificador separada, o algo que alinee una Tuple o Entry .

4- La solución asume que la 3.ª columna siempre es un long analizable y la suma no va más allá de los límites de Long .

Pero al menos puede darte qué pasos seguir. Puede hacer su implementación adecuada con pasos similares.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!