我在拆分 marc21 格式文件的记录时遇到问题。我正在从一个文件中读取并尝试将记录分成单独的行,然后写入另一个文件。这是我目前拥有的:
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException{
FileReader fr = null;
BufferedReader br = null;
FileWriter fw = null;
BufferedWriter bw = null;
try{
fr = new FileReader("data.txt");
br = new BufferedReader(fr);
fw = new FileWriter("SplitRecords.txt");
bw = new BufferedWriter(fw);
String data;
String recordLength = "";
int intLength = 0;
int lengthStart = 0;
int lengthEnd = 5;
while((data = br.readLine()) != null){
while(data != null){
recordLength = data.substring(lengthStart, lengthEnd);
System.out.println(recordLength);
intLength = Integer.parseInt(recordLength);
bw.write(data, lengthStart, intLength);
bw.write("\n");
bw.flush();
lengthStart = intLength;
lengthEnd = lengthStart + 5;
br.mark(intLength);
br.reset();
}
}
}
finally{
if(fr != null){
fr.close();
}
if(br != null){
br.close();
}
if(fw != null){
fw.close();
}
if(bw != null){
bw.close();
}
}
}
}
这是我得到的输出和错误:
00934
00699
1cRT
Exception in thread "main" java.lang.NumberFormatException: For input string: "1cRT"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Main.main(Main.java:26)
它将第一条记录和第二条记录写入文件,但是第三个循环没有正确读取长度。有谁知道为什么会这样?