Fazendo Backup de Arquivo JAVA

Ainda estou aprendendo os métodos da classe File, criei um programa que faz backup de um arquivo .txt, mas quando abro o arquivo de backup, ele escreve uma linha a mais: “null”. Queria saber por que isso está acontecendo e como uso o Debug do NetBeans, Obrigado.

package testes;
import java.io.*;
import java.util.*;

public class Testes {
    
    public static void main(String[] args) throws IOException {
        
        ArrayList<String> texto = new ArrayList<String>();
        
        File f = new File("C:\\Users\\John\\Desktop\\Original.txt");
        File f2 = new File("C:\\Users\\John\\Desktop\\Copy.txt");
        
        if(!f.exists()){
            f.createNewFile();
        }
        
        FileReader fr = new FileReader(f);
        BufferedReader bf = new BufferedReader(fr);
        
        String pega;
        
        pega = bf.readLine();
        texto.add(pega);
        
        while(pega!=null){
            pega = bf.readLine();
            texto.add(pega);
        }
        
        FileWriter fw = new FileWriter(f2);
        PrintWriter pw = new PrintWriter(fw);
        
        for(int a = 0; a<texto.size(); a++){
            pw.println(texto.get(a));
        }
        
        fr.close();
        fw.close();
    }
    
}

O erro ta no loop, tenta assim:

...

String pega;            
pega = bf.readLine();
//        texto.add(pega);
        
while(pega!=null){
texto.add(pega);
pega = bf.readLine();
}

Ou se você esta usando java 8 pode usar assim:

...

//        String pega;
//        
//        pega = bf.readLine();
////        texto.add(pega);
//        
//        while(pega!=null){
//            texto.add(pega);
//            pega = bf.readLine();
//        }
        
        bf.lines().forEach(linha -> texto.add(linha));
1 curtida

Valeu cara, funcionou!