Unir dois Arquivos TXT

3 respostas Resolvido
java
C

Galera. Boa tarde , eu estou tentando unir dois arquivos txt , mas ta dando erro

“java.lang.NullPointerException”.

public void juntar() throws FileNotFoundException, IOException {

    File arquivo;
    File[] arquivos = null;
    FileReader fr = null;
    BufferedReader br = null;
    FileOutputStream fos = null;
    arquivos[0] = new File("d_c_srv.txt");
    arquivos[1] = new File("d_c_srv2.txt");
    String linha = "";
    
    for (int i = 0; i < arquivos.length; i++) {
        arquivo = arquivos[i];
        fr = new FileReader(arquivo);
        br = new BufferedReader(fr);
        fos = new FileOutputStream("numerosf.txt");
        while ((linha = br.readLine()) != null) {
            fos.write(linha.getBytes());
        }
    }
    fos.flush();
    fos.close();
}

3 Respostas

P
Solucao aceita

vc deve inicializar o seu array da maneira certa

File [] arquivos = new File[] {

new File("…"), new File("…")

};

muito provavelmente vc tentou acessar arquivos[0] ou arquivos.length e deu erro pq… vc inicializou este objeto como nulo.

arrays são objetos. pense como tal.

C

Obrigado. Deu certo aqui.

E

Boa Noite pessoal, sou novo com o Java…
Estou tentando juntar dois arquivos e peguei o seu exemplo…
Porem não funcionou… vou postar o código abaixo:Não sei o que esta errado…

package org.eclipse.acceleo.module.example.uml2java;

import java.io.BufferedReader;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.FileReader;

import java.io.IOException;

public class Juntar {

public void juntar() throws FileNotFoundException, IOException {

	File arquivo;

	File[] arquivos = new File[] {
			new File("C:\\Experimento_Work\\TransfM2tUML_Java\\codGenerated\\MIN\\Venda.java"),
			new File("C:\\Experimento_Work\\TransfM2tUML_Java\\codGenerated\\PROJETO\\Venda.java") };
	FileReader fr = null;
	BufferedReader br = null;
	FileOutputStream fos = null;
	/*
	 * arquivos[0] = new File("C:\\Experimento_Work\\TransfM2tUML_Java\\codGenerated\\MIN\\Venda.java");
	 * arquivos[1] = new
	 * File("C:\\Experimento_Work\\TransfM2tUML_Java\\codGenerated\\PROJETO\\Venda.java");
	 */
	String linha = "";

	for (int i = 0; i < arquivos.length; i++) {
		arquivo = arquivos[i];
		fr = new FileReader(arquivo);
		br = new BufferedReader(fr);
		fos = new FileOutputStream("numerosf.txt");
		while ((linha = br.readLine()) != null) {
			fos.write(linha.getBytes());
		}
	}
	fos.flush();
	fos.close();
}

}

Criado 7 de novembro de 2016
Ultima resposta 18 de jun. de 2018
Respostas 3
Participantes 3