I created a class (LerEscreverArquivo) that reads the contents of a text file, does a treatment on the read data, prints on the screen the result of the treatment done and writes in a text file the information.
The data reading and writing on the screen is working. The problem happens at the time of writing the values in the text file.
The script only writes the last record it writes to the file. The previous records it ignores. It follows the code and the images of the problem.
public class LerEscreverArquivo {
private static final String NomeArquivoEntrada = "E:\\DesafioProgramacao\\matriculasSemDV.txt";
private static final String NomeArquivoSaida = "E:\\DesafioProgramacao\\matriculasComDV.txt";
public static void main(String[] args) {
FileReader fr = null;
BufferedReader br = null;
BufferedWriter bw = null;
FileWriter fw = null;
try {
//input file
fr = new FileReader(NomeArquivoEntrada);
br = new BufferedReader(fr);
String sCurrentLine;
System.out.println("Início do arquivo.");
while ((sCurrentLine = br.readLine()) != null) {
if (!sCurrentLine.isEmpty()) {
int Total = 0;
int contador = 5;
int resto;
for (int i = 0; i < sCurrentLine.length(); i++) {
int j = Character.digit(sCurrentLine.charAt(i), 10);
Total = Total + (j * contador);
contador = contador - 1;
}
resto = Total / 16;
String decimal = Integer.toHexString(resto);
String DigitoCod=sCurrentLine + "-" + decimal;
//output file
fw = new FileWriter(NomeArquivoSaida);
bw = new BufferedWriter(fw);
bw.write(DigitoCod);
System.out.println(DigitoCod);
}
}
System.out.println("Fim do arquivo.");
} catch (IOException eReader) {
eReader.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
if (fr != null) {
fr.close();
}
if(bw != null) {
bw.close();
}
if(fw != null) {
fw.close();
}
} catch (IOException exeReader) {
exeReader.printStackTrace();
}
}
}
}
try-with-resources
. And you don't need to explicitly close yourFileReader
orFileWriter
- closing theBufferedReader
andBufferedWriter
will close them already.