【发布时间】:2012-11-05 17:48:52
【问题描述】:
我有一个 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 和, 之间。但是,这些字符似乎并不重要,因为如果我将1 更改为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);
}
}
}
【问题讨论】:
标签: java file-io bufferedwriter