【发布时间】:2018-04-20 14:12:04
【问题描述】:
我创建了一个类 (LerEsceverArquivo),它读取文本文件的内容,对读取的数据进行处理,在屏幕上打印完成的处理结果并将信息写入文本文件。
屏幕数据读写正常。问题发生在文本文件中写入值的时候。
脚本仅将其写入文件的最后一条记录写入。它忽略以前的记录。它遵循问题的代码和图像。
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。而且您不需要显式关闭您的FileReader或FileWriter- 关闭BufferedReader和BufferedWriter将已经关闭它们。
标签: java file filewriter bufferedwriter