gpt4 book ai didi

java - 从 .txt 文件 Java 读取的问题

转载 作者:行者123 更新时间:2023-12-02 05:21:44 25 4
gpt4 key购买 nike

所以我开发了一个系统,每当用户尝试保存但数据库连接不存在时,它会将数据库插入/更新命令保存到文本文件中。文件中的每一行都是一个插入或更新命令。但是,我似乎遇到了问题。

有些文件似乎不想读过第一行。它们都有一个共同点——因为数据库中有与第一个插入对应的数据,所以我跳过它,因为该信息一旦输入就不允许更改。但是,当我尝试读取下一行时,它会启动,因为 readLine() 命令返回 null(这会导致其余代码按预期失败)。

我尝试在下一个 readLine() 之前添加一个 while(!ready() Thread.sleep(500)),但它只是无限期地坐在那里(我在终止 JVM 之前让它运行大约 10 分钟)。我也试过只在 if 中添加一个 else block 来检查数据库中是否存在数据,这会暂停 2 秒,但问题仍然存在。

请注意,任何以不存在的数据插入开头的文件都可以正常工作。

有没有人对如何解决这个问题有任何想法?

编辑:这是从顶部到等待就绪的代码

private static boolean loadExistingData()
{
File dir = new File(Configuration.DBOutputDataLocation);
// Attempt to create the directory in case it doesn't exist.
if(!dir.exists())
{
if(!dir.mkdir())
{
return false;
}
}
String[] existingFiles = dir.list();
System.out.println(existingFiles.length);
if(existingFiles == null || existingFiles.length == 0)
{
return false;
}
else
{
BufferedReader fileReader = null;
DatabaseAccessor dba = DatabaseAccessor.getInstance();
// Pull out the files, submit each one.
for(int i = 0; i < existingFiles.length; i++)
{
try
{
fileReader = new BufferedReader(new FileReader(new File(Configuration.DBOutputDataLocation + existingFiles[i])));
}
catch(FileNotFoundException e)
{
System.err.println("ERROR Reading From File: " + existingFiles[i]);
e.printStackTrace();
}
// Recreate much of Util.saveToDB();
if(dba.isConnected())
dba.disconnect();
if(!dba.connect(Configuration.dbUser, Configuration.dbPass, Configuration.dbURL))
return false;
String sqlUpdate;
String serialNum = "";
int testNum;
/**
* Sensor Information {serial number, type, capacity, etc.} Data
*/
try
{
// Read Line for the Sensor data.
sqlUpdate = fileReader.readLine();
}
catch(IOException e)
{
System.err.println("ERROR Reading From File: " + existingFiles[i]);
e.printStackTrace();
try
{
fileReader.close();
}
catch(IOException e1)
{
e1.printStackTrace();
}
return false;
}
try
{
int serialNumBegin = sqlUpdate.indexOf("'") + 1;
int serialNumEnd = sqlUpdate.indexOf("'", serialNumBegin);
serialNum = sqlUpdate.substring(serialNumBegin, serialNumEnd);
System.out.println("Sensor sqlUpdate: " + sqlUpdate);
if(!dba.contains("sensor", "serial_number = '" + serialNum + "'"))
{
try
{
// please work, please work, please work...
dba.executeUpdate(sqlUpdate);
}
catch(SQLException e)
{
// gaa! ok, give user moderately descriptive error. What could
// they do about it anyway? Reconfigure the SQL server?
e.printStackTrace();
System.out.println("failed sensor entry @ update");
try
{
fileReader.close();
}
catch(IOException e1)
{
e1.printStackTrace();
}
return false;
}
}
else
{
System.out.println("Sensor Exists, skipping.");
}
}
catch(SQLException e1)
{
e1.printStackTrace();
System.out.println("failed sensor entry");
try
{
fileReader.close();
}
catch(IOException e2)
{
e1.printStackTrace();
}
return false;
}
/**
* Sensor Test xref
*/
try
{
int k = 0;
while(!fileReader.ready())
{
Thread.sleep(500);
System.out.println("Slept : " + k++);
}
}
catch(IOException e3)
{
e3.printStackTrace();
}
catch(InterruptedException e)
{
// TODO Auto-generated catch block::: Problem with file not being
// ready!!111oneoneoneeleventyeleven
e.printStackTrace();
}
try
{
// Read Line for the Sensor test data.
sqlUpdate = fileReader.readLine();
}
catch(IOException e)
{
System.err.println("ERROR Reading From File: " + existingFiles[i]);
e.printStackTrace();
try
{
fileReader.close();
}
catch(IOException e1)
{
e1.printStackTrace();
}
}
System.out.println("Sensor Test Xref: " + sqlUpdate);
// Locate the test number
int serialNumBegin = sqlUpdate.indexOf("'") + 1;
int serialNumEnd = sqlUpdate.indexOf("'", serialNumBegin);
int testNumBegin = serialNumEnd + 2;
int testNumEnd = sqlUpdate.indexOf(",", testNumBegin);
testNum = Integer.parseInt(sqlUpdate.substring(testNumBegin, testNumEnd));
if(testNum == -1)
{
// increments until it finds an unused test #
try
{

while(dba.contains("sensor_test_xref", "serial_number = '" + serialNum + "' and test_no = " + (++testNum)));
}
catch(SQLException e1)
{
e1.printStackTrace();
JOptionPane.showMessageDialog(new JFrame(), "Error saving test information (date, test number, station...) to database",
"DB Error", JOptionPane.ERROR_MESSAGE);
System.out.println("failed sensor_test_xref");
try
{
fileReader.close();
}
catch(IOException e2)
{
e1.printStackTrace();
}
return false;
}

System.out.println("settled on test# " + testNum);

// Splice test number back in
// Gets me the beginning up to the comma before the test number
String firstPartOfUpdate = sqlUpdate.substring(0, testNumBegin);
// Gets me the last part of it, from the comma to the end.
String lastPartOfUpdate = sqlUpdate.substring(testNumEnd);
// Piece everything back together...
sqlUpdate = firstPartOfUpdate + testNum + lastPartOfUpdate;
try
{
dba.executeUpdate(sqlUpdate);
}
catch(SQLException e)
{
e.printStackTrace();
// obviously a good entry was not made
testNum = -1;
System.out.println("failed sensor_test_xref");
try
{
fileReader.close();
}
catch(IOException e1)
{
e1.printStackTrace();
}
return false;
}
System.out.println("sensor_test_xref success");
}
/**
* Temperature Point Data.
*/
try
{
// Need a loop because there should be one line for each temp. point.
while(fileReader.ready())
{
try
{
sqlUpdate = fileReader.readLine();
}
catch(IOException e)
{
System.err.println("ERROR Reading From File: " + existingFiles[i]);
e.printStackTrace();
try
{
fileReader.close();
}
catch(IOException e1)
{
e1.printStackTrace();
}
return false;
}

// Locate the temp point
int serialNumBegin1 = sqlUpdate.indexOf("'") + 1;
int serialNumEnd1 = sqlUpdate.indexOf("'", serialNumBegin1);
int testNumBegin1 = serialNumEnd1 + 2;
int testNumEnd1 = sqlUpdate.indexOf(",", testNumBegin1);
int tempPointBegin = testNumEnd1 + 2;
int tempPointEnd = sqlUpdate.indexOf("'", tempPointBegin);
String tempPoint = sqlUpdate.substring(tempPointBegin, tempPointEnd);
// the unique key for a temperature point entry
String condition =
"serial_number = '" + serialNum + "' and test_no = " + testNum + " and temp_point = '" + tempPoint + "'";
// if an entry already exists delete it
try
{
if(dba.contains("sensor_temp_point", condition))
{
try
{
dba.executeUpdate("delete from sensor_temp_point where " + condition);
}
catch(SQLException e)
{
e.printStackTrace();
try
{
fileReader.close();
}
catch(IOException e1)
{
e1.printStackTrace();
}
return false;
}
}
}
catch(HeadlessException e1)
{
e1.printStackTrace();
try
{
fileReader.close();
}
catch(IOException e2)
{
e1.printStackTrace();
}
return false;

}
catch(SQLException e1)
{
e1.printStackTrace();
try
{
fileReader.close();
}
catch(IOException e2)
{
e1.printStackTrace();
}
return false;

}

// Splice test number and temperature point back in
// Gets me the beginning up to the comma before the test number
String firstPartOfUpdate = sqlUpdate.substring(0, testNumBegin1);
// Gets me the last part of it, from the comma to the end.
String lastPartOfUpdate = sqlUpdate.substring(tempPointEnd);
// Piece everything back together...
sqlUpdate = firstPartOfUpdate + testNum + ",'" + tempPoint + lastPartOfUpdate;

System.out.println("Temp Point sqlUpdate: " + sqlUpdate);
try
{
dba.executeUpdate(sqlUpdate);
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("failed to save temp. point data : " + i);
try
{
fileReader.close();
}
catch(IOException e1)
{
e1.printStackTrace();
}
return false;
}

}
}
catch(IOException e)
{
System.err.println("ERROR Reading From File: " + existingFiles[i]);
e.printStackTrace();
try
{
fileReader.close();
}
catch(IOException e1)
{
e1.printStackTrace();
}
return false;
}
System.out.println("all successful");
// Close the file before deletion!
try
{
fileReader.close();
}
catch(IOException e1)
{
e1.printStackTrace();
}
try
{
new File(Configuration.DBOutputDataLocation + existingFiles[i]).delete();
}
catch(SecurityException e)
{
e.printStackTrace();
}

}
System.out.println("All Files Saved Successfully.");
dba.disconnect();

return true;
}
}

这是对示例文件的另一个编辑。我删除了数据部分以节省空间,只包含一个“sensor_temp_point”行(文件中有 4 个)。

insert into sensor (serial_number, sensor_type, amplification_id, sensor_max_capacity,  unit_cd) values ;
insert into sensor_test_xref (serial_number, test_no, test_station, test_date, tester_initials, test_load) values ;
insert into sensor_temp_point (serial_number, test_no, temp_point, temp_val, excitation_val, linearity, temp_zero_shift_abs, temp_span_shift_abs, load_0_actual_val, load_0_raw_val, load_0_norm_val, load_50_actual_val, load_50_raw_val, load_50_norm_val, load_100_actual_val, load_100_raw_val, load_100_norm_val, load_0r_actual_val, load_0r_raw_val, load_0r_norm_val, last_reading_time) values ;

最佳答案

readLine() 到达文件末尾时将返回 null。等待再次阅读是没有意义的 - 你应该在那一刻停下来。

编辑:好的,现在代码已经准备就绪 - 您真的需要重构它。目前几乎不可读。将其拆分为更小的方法,并在 finally block 中关闭文件读取器,而不是在您当前正在执行此操作的大量地方。

目前还不清楚到底发生了什么,但通常要遍历文件的内容,我会使用:

String line;
while ((line = reader.readLine()) != null)
{
// Use the line
}

readLine 返回 null 时,这意味着没有更多数据。我根本不会使用 ready()

一旦您重构了您的代码(只是使用 finally block 关闭文件将删除大约四分之一的方法 - 然后进一步重构它)对您来说会容易得多弄清楚到底发生了什么。

关于java - 从 .txt 文件 Java 读取的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5394488/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com