0

Estou tentando dividir um arquivo em outros arquivos menores, estou recebendo via serversocket um arquivo e quero que este arquivo seja dividido de acordo com o identificador que vem no começo de cada linha, estou com esse código até o momento, consigo escrever alguns dos arquivos, mas o conteúdo não está vindo corretamente, segue um exemplo do arquivo .txt.

01#Joao Pedro Gonçalves#10000#1205325103

01#cvnbhgdfgs#10000#1205325103

01#gfdhgdfhdfh#10000#1205325103

01#Jffgjhfgvbs#10000#1205325103

01#jfjgfvcnvbves#10000#1205325103

04#LUAL DO LOBO#5351235#123635526356

03#LUAL DO LOBO#5351235#123635526356

05#LUAL DO LOBO#5351235#123635526356

06#LUAL DO LOBO#5351235#123635526356

03#LUAL DO LOBO#5351235#123635526356

07#LUAL DO LOBO#5351235#123635526356

e o código que estou fazendo é:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package split;

/**
 *
 * @author PURE
 */
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;

public class Split {

    public static void main(String args[]) {
        try {
            // lendo o arquivo e vendo quantas linhas ele tem
            String inputfile = "caminho.txt"; //  Source File Name.
            double nol = 2000.0; //  No. of lines to be split and saved in each output file.
            File file = new File(inputfile);
            Scanner scanner = new Scanner(file);
            int count = 0;
            while (scanner.hasNextLine()) {
                scanner.nextLine();
                count++;
            }
            System.out.println("Lines in the file: " + count);     // Displays no. of lines in the input file.

            //---------------------------------------------------------------------------------------------------------
            // Actual splitting of file into smaller files
            FileInputStream fstream = new FileInputStream(inputfile);
            DataInputStream in = new DataInputStream(fstream);

            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine = br.readLine();


            while (strLine.startsWith("1")) {
                FileWriter fstream1 = new FileWriter("C:\\teste java\\" + 1 + ".txt", true);     // Destination File Location
                BufferedWriter out = new BufferedWriter(fstream1);
                if (strLine != null) {
                    String vetor[] = strLine.split("#");
                    out.write(Arrays.toString(vetor) + System.getProperty("line.separator"));

                }

                out.close();

            }
            while (strLine.startsWith("2")) {

                FileWriter fstream1 = new FileWriter("C:\\teste java\\" + 2 + ".txt", true);     // Destination File Location
                BufferedWriter out = new BufferedWriter(fstream1);

                if (strLine != null) {
                    out.write(strLine + System.getProperty("line.separator"));
                } else {
                    out.newLine();
                }
                out.close();
            }
            while (strLine.startsWith("3")) {

                FileWriter fstream1 = new FileWriter("C:\\teste java\\" + 3 + ".txt", true);     // Destination File Location
                BufferedWriter out = new BufferedWriter(fstream1);

                if (strLine != null) {
                    out.write(strLine + System.getProperty("line.separator"));
                } else {
                    out.newLine();
                }
                out.close();
            }
            while (strLine.startsWith("4")) {

                FileWriter fstream1 = new FileWriter("C:\\teste java\\" + 4 + ".txt", true);     // Destination File Location
                BufferedWriter out = new BufferedWriter(fstream1);

                if (strLine != null) {
                    out.write(strLine + System.getProperty("line.separator"));
                } else {
                    out.newLine();
                }
                out.close();
            }
            while (strLine.startsWith("5")) {

                FileWriter fstream1 = new FileWriter("C:\\teste java\\" + 5 + ".txt", true);     // Destination File Location
                BufferedWriter out = new BufferedWriter(fstream1);

                if (strLine != null) {
                    out.write(strLine + System.getProperty("line.separator"));
                } else {
                    out.newLine();
                }
                out.close();
            }
            while (strLine.startsWith("6")) {
                FileWriter fstream1 = new FileWriter("C:\\teste java\\" + 6 + ".txt", true);     // Destination File Location
                BufferedWriter out = new BufferedWriter(fstream1);

                if (strLine != null) {
                    out.write(strLine + System.getProperty("line.separator"));
                } else {
                    out.newLine();
                }
                out.close();
            }
            while (strLine.startsWith("7")) {

                FileWriter fstream1 = new FileWriter("C:\\teste java\\" + 7 + ".txt", true);     // Destination File Location
                BufferedWriter out = new BufferedWriter(fstream1);

                if (strLine != null) {
                    out.write(strLine + System.getProperty("line.separator"));
                } else {
                    out.newLine();
                }
                out.close();
            }
            while (strLine.startsWith("8")) {

                FileWriter fstream1 = new FileWriter("C:\\teste java\\" + 8 + ".txt", true);     // Destination File Location
                BufferedWriter out = new BufferedWriter(fstream1);

                if (strLine != null) {
                    out.write(strLine + System.getProperty("line.separator"));
                } else {
                    out.newLine();
                }
                out.close();
            }
            while (strLine.startsWith("9")) {

                FileWriter fstream1 = new FileWriter("C:\\teste java\\" + 9 + ".txt", true);     // Destination File Location
                BufferedWriter out = new BufferedWriter(fstream1);

                if (strLine != null) {
                    out.write(strLine + System.getProperty("line.separator"));
                } else {
                    out.newLine();
                }
                out.close();
            }

            in.close();
        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
        }

    }

}

Obrigado!

@edit o serversocket está em outro pacote no mesmo projeto.

2
  • Os dois dígitos iniciais são conhecidos, ou seja, virão números de 01 à 10 e nada diferente disso ou pode vir qualquer coisa? 2/05/2016 às 16:21
  • os digitos são conhecidos e e predefinidos, cada um representa uma operação realizada pela pessoa que vem logo depois, no segundo elemento apos o sustenido
    – xhenrique
    2/05/2016 às 16:25

1 Resposta 1

0

Uma sugestão seria essa:

boolean arquivo1_aberto, arquivo2_aberto, arquivo3_aberto ... = false;

abre_o_arquivo_principal
while ( tem linhas )
  linha = linha_lida;
  if ( linha comeca com 01 ) {
    if ( !arquivo_aberto )  {
      abre_arquivo1;
      arquivo1_aberto = true;
   }
    escreve_linha_no_arquivo_1;
  } else if ( linha comeca com 02 ) {
    if ( !arquivo_aberto )  {
      abre_arquivo2;
      arquivo2_aberto = true;
   }
   escreve_linha_no_arquivo_2;
 } else if ( linha comeca com 03 ) {
   if ( !arquivo_aberto )  {
      abre_arquivo3;
      arquivo3_aberto = true;
  }
   escreve_linha_no_arquivo_3
} 
...
}
fecha_o_arquivo_principal;
if ( arquivo1_aberto )
   fecha_arquivo1;
if ( arquivo2_aberto )
   fecha_arquivo2;    
...   
1
  • Obrigado Reginaldo Rigo, fiz como descrevestes e deu certo, estou conseguindo separar perfeitamente os arquivos agora, um forte abraço, ajudou demais!
    – xhenrique
    2/05/2016 às 21:32

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .