我有一个 Java 程序,它从文件中逐行读取一些文本,并将新文本写入输出文件。但并不是我写给我的所有文字BufferedWriter
程序完成后出现在输出文件中。这是为什么?
详细信息:该程序获取 CSV 文本文档并将其转换为 SQL 命令以将数据插入表中。该文本文件有超过 10000 行,类似于以下内容:
2007,10,9,1,1,1006134,19423882
该程序似乎工作正常,只是它在创建新的 SQL 语句并将其打印到 SQL 文件中时随机停止在文件中。它看起来像:
insert into nyccrash values (2007, 1, 2, 1, 4, 1033092, 259916);
insert into nyccrash values (2007, 1, 1, 1, 1, 1020246, 197687);
insert into nyccrash values (2007, 10, 9, 1
这种情况发生在大约 10000 行之后,但距离文件末尾还有几百行。中断发生的地方是在1
and a ,
。然而,角色似乎并不重要,因为如果我改变1
to a 42
写入新文件的最后内容是4
,即从该整数中减去 2。所以看起来读者或作者在写/读一定数量后一定会死。
我的Java代码如下:
import java.io.*;
public class InsertCrashData
{
public static void main (String args[])
{
try
{
//Open the input file.
FileReader istream = new FileReader("nyccrash.txt");
BufferedReader in = new BufferedReader(istream);
//Open the output file.
FileWriter ostream = new FileWriter("nyccrash.sql");
BufferedWriter out = new BufferedWriter(ostream);
String line, sqlstr;
sqlstr = "CREATE TABLE nyccrash (crash_year integer, accident_type integer, collision_type integer, weather_condition integer, light_condition integer, x_coordinate integer, y_coordinate integer);\n\n";
out.write(sqlstr);
while((line = in.readLine())!= null)
{
String[] esa = line.split(",");
sqlstr = "insert into nyccrash values ("+esa[0]+", "+esa[1]+", "+esa[2]+", "+esa[3]+", "+esa[4]+", "+esa[5]+", "+esa[6]+");\n";
out.write(sqlstr);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}