Categorías
Real Methods

Ordenar contenido en un archivo txt

Si tiene un archivo con palabras o términos en cada línea, es posible que desee ordenarlo. Java Arrays.sort es una función agradable común para hacer esto. Collections.sort () es otro buen comentario. Aquí hay un ejemplo y un código.
EG en un archivo, tiene el siguiente txt.

dog 
cat
--windows
--kankan
pps
game
--annot be guaranteed 
as it is, generally speaking, 
--impossible to make any hard gu
arantees in the p
--resence of unsynchr

Aquí está el código para ordenar las líneas, excluyendo las líneas que comienzan con «-«.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
 
 
public class SortFileContent {
	public static void sortObserve() throws IOException {
		File fin = new File("c:input.txt");
		File fout = new File("c:sorted.txt");
 
 
		FileInputStream fis = new FileInputStream(fin);
		FileOutputStream fos = new FileOutputStream(fout);
 
		BufferedReader in = new BufferedReader(new InputStreamReader(fis));
		BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fos));
 
		String aLine;
		ArrayList<String> al = new ArrayList<String> ();
 
 
		int i = 0;
		while ((aLine = in.readLine()) != null) {
			//get the lines you want, here I don't want something starting with - or empty
			if (!aLine.trim().startsWith("-") && aLine.trim().length() > 0) {
				al.add(aLine);
				i++;
			}
		}
 
		Collections.sort(al);
		//output sorted content to a file
		for (String s : al) {
		    System.out.println(s);
		    out.write(s);
			out.newLine();
			out.write("-----------------------------------------");
			out.newLine();
		}
 
		in.close();
		out.close();
	}
}
  Código Java: convierte un archivo en una cadena

Finalmente, obtiene lo siguiente en el archivo sorted.txt.

arantees in the p
-----------------------------------------
as it is, generally speaking, 
-----------------------------------------
cat
-----------------------------------------
dog 
-----------------------------------------
game
-----------------------------------------
pps
-----------------------------------------

Por Programación.Click

Más de 20 años programando en diferentes lenguajes de programación. Apasionado del code clean y el terminar lo que se empieza. ¿Programamos de verdad?

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *