从.txt文件读取Java时出现问题

从.txt文件读取Java时出现问题,java,file-io,freeze,Java,File Io,Freeze,因此,我开发了一个系统,每当用户试图保存而数据库连接不存在时,可以将数据库插入/更新命令保存到文本文件中。文件中的每一行都是一个insert或update命令。然而,我似乎遇到了一个问题 有些文件似乎不想读取,但已通过第一行。它们都有一个共同点,因为数据库中有与第一次插入相对应的数据,我跳过它,因为一旦输入,信息就不允许更改。但是,当我尝试读取下一行时,它会启动,因为readLine()命令返回null(这会导致其余代码按预期失败) 我尝试在下一个readLine()之前添加while(!rea

因此,我开发了一个系统,每当用户试图保存而数据库连接不存在时,可以将数据库插入/更新命令保存到文本文件中。文件中的每一行都是一个insert或update命令。然而,我似乎遇到了一个问题

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

我尝试在下一个
readLine()
之前添加
while(!ready()Thread.sleep(500))
,但它只是无限期地停留在那里(在杀死JVM之前,我让它保持大约10分钟)。我还尝试向if添加一个else块来检查数据库中是否存在数据,该块会暂停2秒钟,但问题仍然存在

请注意,对于不存在的数据,任何以insert开头的文件都可以正常工作

有人对如何解决这个问题有什么想法吗

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

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;
    }
}
readLine()
到达文件末尾时将返回
null
。等着再读是没有意义的——你应该在那一点上停下来

编辑:好的,现在代码完成了-你真的需要重构它。现在几乎看不懂。将其拆分为较小的方法,并在finally块中关闭文件读取器,而不是在当前正在执行此操作的大量位置

现在还不清楚到底发生了什么,但一般来说,要循环浏览文件的内容,我会使用:

String line;
while ((line = reader.readLine()) != null)
{
    // Use the line
}
readLine
返回null时,表示不再有数据。我根本不会使用
ready()


一旦您重构了代码(仅使用finally块关闭文件将删除大约四分之一的方法,然后进一步重构),您就可以更轻松地了解到底发生了什么。

每当我需要读取文件时,我都会在谷歌上搜索“java读取文本文件”。(对于许多你不想记住怎么做的任务来说,这是一个很好的实践。)有很多页面展示了阅读文本文件的基本技巧

这里有一个

而(!ready()Thread.sleep(500))

如果我理解正确的话,您是想说您希望您的代码与正在写入文本文件的进程(或线程)同时读取文本文件?如果是这样,那可能就是你的问题所在

当程序向文件发出
write()
时,输出很可能被缓冲在某个地方。在
close()
-es的程序
flush()
-es启动其输出文件之前,缓冲数据不会写入实际文件。因此,您可能需要查看另一个程序,它写入您想要读取的数据


当一个程序与写入数据的程序同时读取数据时,这两个程序必须具有某种并发控制。在Unix(POSIX)系统上,以这种方式通信的程序通常使用管道而不是文件,处理阻塞I/O的功能提供了并发控制。当你想使用一个文件时,事情会变得更加棘手。您的阅读程序可以尝试轮询,直到它读取指示文本结尾的独特模式。您可以使用锁定方案,因此文件将被锁定,直到编写器完成对文件的写入。

在没有看到代码的情况下,我们只能猜测。您可以发布实际的文件读取代码吗?还有一个示例文件(根据需要进行清理)?如果我读对了,您只需对每个文件调用readLine()一次。您是否真的遇到了异常,或者代码没有像您预期的那样完成?第一个调用端口-了解
最后的
清除块。您当前关闭文件读取器的位置有多少?哎呀@坎平:不,您希望在顶级循环的末尾有一个finally块,这样您就可以在完成文件时关闭它,不管您是如何完成的。如果您删除了对
readLine()
的调用,那么发布其余代码就毫无意义了。我的猜测是,那些其他电话正在读取您认为被忽略的行-但这是不可能的。对不起,文件在这一点之后不是空的。当代码失败时,至少还有2行要读取(通常有4行)。假设我应该提到这一点。@user300260:那么我怀疑您在读取文件时存在错误,但您没有发布任何代码。实际上,您还没有说出要调用的
readLine
,但假设它是
BufferedReader
,返回值
null
确实表示输入数据的结束。是的,很抱歉,代码现在已经启动,示例文件中的值已被删除。在读取文件的第一行之后,它会挂起(如果我删除等待就绪,则会失败)。我没有在所有文件中使用循环的唯一原因是,我需要对第一行、第二行和下面的行执行不同的操作。但问题仍然存在:为什么readLine()在读取第二行时,在文件上返回null,而第二行在那里?@Campin:我很确定在这种情况下,它实际上并没有返回null-但您自己说您已经删除了对
readLine
的一些调用。请注意,如果您需要以不同的方式处理这些问题,您可以在阅读前几行之后使用我在回答中提供的循环。
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 ;