文本文件如下:
.I 1
some text
.I 2
some text
.I 3
some text
........
以下代码使用stringbuilder追加行。以下代码拆分上述文本文件,并在找到.I
时创建多个文件但问题是当我运行代码时,它不会为最后一个.I创建文件 它有1400.I在文件中。所以应该有1400个文本文件。但它产生了1399个文本文件。 有什么问题 ?我找不到问题。
public class Test {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String inputFile="C:\\logs\\test.txt";
BufferedReader br = new BufferedReader(new FileReader(new File(inputFile)));
String line=null;
StringBuilder sb = new StringBuilder();
int count=1;
try {
while((line = br.readLine()) != null){
if(line.startsWith(".I")){
if(sb.length()!=0){
File file = new File("C:\\logs\\DOC_ID_"+count+".txt");
PrintWriter writer = new PrintWriter(file, "UTF-8");
writer.println(sb.toString());
writer.close();
sb.delete(0, sb.length());
count++;
}
continue;
}
sb.append(line);
}
} catch (Exception ex) {
ex.printStackTrace();
}
finally {
br.close();
}
}
}
答案 0 :(得分:0)
在您使用FileWriter编写之后,您将在循环底部附加到StringBuilder,这意味着附加到StringBuilder的最后一行不会写入文件:< / p>
try {
while((line = br.readLine()) != null){
if(line.startsWith(".I")){
if(sb.length()!=0){
File file = new File("C:\\logs\\DOC_ID_"+count+".txt");
PrintWriter writer = new PrintWriter(file, "UTF-8");
writer.println(sb.toString());
writer.close();
sb.delete(0, sb.length());
count++;
}
continue;
}
sb.append(line); // here ****
}
}
我建议您简化逻辑和代码:
答案 1 :(得分:0)
当您遇到以&#34; .I&#34;开头的行时您想要关闭现有文件(如果有)并启动一个新文件。其他所有内容都会附加到当前打开的文件中。确保最后检查您是否有一个打开的文件并关闭它。
public static void main(String[] args) throws IOException {
String inputFile="C:\\logs\\test.txt";
BufferedReader br = new BufferedReader(new FileReader(new File(inputFile)));
String line=null;
int count=1;
try {
PrintWriter writer = null;
while((line = br.readLine()) != null){
if(line.startsWith(".I")){
if(writer != null) writer.close();
writer = new PrintWriter(file, "UTF-8");
}
if(writer != null){
writer.println(line);
}
}
if(writer != null){
writer.close;
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
br.close();
}
}