Dividir Arquivo em Linhas

7 respostas
B

preciso fazer uma aplicacao para dividir arquivos .txt em tantas linhas! Eu consegui fazer de um jeito, mais parece que fiz uma gambiarra ! vou postar para vcs darem uma olhada! o Codigo esta funcionando perfeito! So queria alguma dica de voces!

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;

public class Split {
	private static String nomeArquivo;
	private static String email;
	private static String nomeArquivoDividido = "lista";
	
	public static void split(int numLinhas) throws IOException {
		FileReader ler = null;
		BufferedReader origem = null;
		int a = 1;
		int count = 0;
		String host;
		String[] lista = new String[numLinhas+2];
		try {
			ler = new FileReader(new File(nomeArquivo));
			origem = new BufferedReader(ler);
			lista[0] = email;
			for(host = origem.readLine(); host != null; host = origem.readLine()) {
				lista[a] = host;
				if (a == numLinhas) { // ARRAY CHEIO, SALVA A LISTA
					lista[numLinhas+1] = email; // ADICIONA NA ULTIMA LINHA
					String nome = nomeArquivoDividido+count+".txt";
					PrintWriter salva = new PrintWriter(new FileWriter(nome), true);
					for (int c = 0;c <= numLinhas+1;c++)
						salva.println(lista[c]);
					salva.close();
					count++;
					Arrays.fill(lista, null);   // LIMPA ARRAY
					a = 0;          // ZERA A CONTAGEM DO ARRAY
					lista[a] = email;  //ADICIONA NA PRIMEIRA LINHA
				}
				a++;
			}
			if (host == null) { // AQUI SALVA O RESTANTE DO ARQUIVO QUE NAO CHEGA A LOTAR O ARRAY
				String nome = nomeArquivoDividido+count+".txt";
				PrintWriter salva = new PrintWriter(new FileWriter(nome), true);
				for (int c = 0;c <= numLinhas+1 && lista[c] != null;c++)
					salva.println(lista[c]);
				salva.println(email);
				salva.close();
			}
		} finally {
			//if (origem != null)
				//origem.close();
		}
		
	}

	
	public static void main(String[] args) throws IOException {
		nomeArquivo = args[0];
		int linhas = Integer.parseInt(args[1]);
                email = args[2];
		split(linhas);	
	}

}

7 Respostas

H

Na verdade você pensa que fez uma Gambiarra, porque este método
está fazendo muita coisa.

Você pode fazer um refactor, nele somente um exemplo.

String nome = nomeArquivoDividido+count+".txt"; PrintWriter salva = new PrintWriter(new FileWriter(nome), true); for (int c = 0;c <= numLinhas+1;c++) salva.println(lista[c]); salva.close();

Você está fazendo este trecho duas vezes, extrai para um outro método assim, você ja consegue diminuir um pouco.

Espero ter contribuido um pouco

B

Hmm voce fala pra mim transformar esse trecho em um metodo, e quando for pra chamar, chama o metodo ? eh isso ?

H

Isso desta maneira, o seu código já vai ficar com outra cara isso, é só uma idéia.

B

aonde eu repiti eu criei esse metodo, passano o int count como o numero do arquivo!

public static void geraArquivo(int count, String[] lista) throws IOException {
		String nomeFragmento = nomeArquivoDividido+count+".txt";
		PrintWriter salva = new PrintWriter(new FileWriter(nomeFragmento), true);
		for (int c = 0;c <= numLinhas+1 && lista[c] != null;c++)
			salva.println(lista[c]);
		salva.println(email);
		salva.close();
	}
public static void split() throws IOException {
		Date tempoGasto = new Date();
		FileReader ler = null;
		BufferedReader origem = null;
		int a = 1;
		String host;
		String[] lista = new String[numLinhas+2];
		try {
			ler = new FileReader(new File(nomeArquivo));
			origem = new BufferedReader(ler);
			lista[0] = email;
			for(host = origem.readLine(); host != null; host = origem.readLine()) {
				lista[a] = host;
				if (a == numLinhas) {
					geraArquivo(count, lista);
					count++;
					Arrays.fill(lista, null);
					a = 0;
					lista[a] = email;
				}
				a++;
			}
			if (host == null) {
				geraArquivo(count, lista);
			}
			Date tempoGasto1 = new Date();
			long tempoTotal = tempoGasto1.getTime() - tempoGasto.getTime();
			long tempoSegundos = tempoTotal / 1000;
			System.out.println("\n\n[#] Arquivo Gerado em "+tempoSegundos+" segundos");
			//System.out.println("\n\n[#] Arquivo Gerado em "+tempoTotal+" Milisegundos");
		} finally {
			//if (origem != null)
				//origem.close();
		}
		
	}

ficou assim agora ! mais alguma dica pra melhorar ?

B

up

T

.

F

Use o System.getResource(“line.separator”);

Assim:

String line = null;
StringBuffer textFile = new StringBuffer();

while((line = br.readLine()) != null) {

textFile.append(line);

textFile.append(System.getResource(line.separator));

}

Onde br é o BufferedReader que vc tá usando pra ler o arquivo.

Sei lá se é isso que vc queria fazer huahau

Abrazzz…

Criado 30 de outubro de 2008
Ultima resposta 3 de nov. de 2008
Respostas 7
Participantes 4