簡體   English   中英

從.txt文件Java讀取的問題

[英]Problems reading from .txt file Java

因此,我開發了一個系統,只要用戶嘗試保存並且數據庫連接不存在,就會將數據庫插入/更新命令保存到文本文件中。 文件中的每一行都是一個插入或更新命令。 但是,我似乎遇到了一個問題。

有些文件似乎不想通過第一行讀取。 所有這些都有一個共同點 - 因為數據庫中有與第一個插入對應的數據,我跳過它,因為輸入后不允許更改該信息。 但是,當我嘗試讀取下一行時,它會引導,因為readLine()命令返回null(這會導致其余代碼按預期失敗)。

我嘗試在下一個readLine() while(!ready() Thread.sleep(500))之前添加一段while(!ready() Thread.sleep(500)) ,但它只是無限期地停留在那里(我讓它在殺死JVM之前大約需要10分鍾)。 我還嘗試過只添加一個else塊來檢查數據庫中是否存在數據,該數據暫停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塊中關閉文件讀取器,而不是在當前正在執行它的大量位置。

目前尚不清楚究竟發生了什么,但一般來說,循環遍歷文件的內容,我會使用:

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

readLine返回null時,表示沒有更多數據。 我根本不會使用ready()

一旦你重構了你的代碼( 只是使用finally塊關閉文件將刪除大約四分之一的方法 - 然后進一步重構),你將更容易找出真正發生的事情。

每當我需要閱讀文件時,我都會搜索“java read text file”。 (對於許多您不想記住的任務,這是一個很好的做法。)有很多頁面顯示了閱讀文本文件的基本技巧。

這是一個。 http://www.javapractices.com/topic/TopicAction.do?Id=42

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

如果我理解正確,您試圖說您希望您的代碼與寫入文件的進程(或線程) 同時讀取文本文件? 如果是這樣, 可能是你遇到的問題。

當程序向文件發出write() ,輸出很可能在某處緩沖。 緩沖數據將不會被寫入真實文件,直到程序flush() es of close() es其輸出文件。 因此,您可能需要查看另一個程序,該程序會寫入您要讀取的數據。

當一個程序要與寫入該數據的程序同時讀取數據時,這兩個程序必須具有一些並發控制 在Unix(POSIX)系統上,以這種方式通信的程序通常使用管道而不是文件,處理阻塞I / O的功能提供了並發控制。 當你想使用文件時,事情變得棘手。 您的閱讀程序可以嘗試輪詢,直到它讀取表明文本結尾的獨特模式。 您可以使用鎖定方案,因此文件將被鎖定,直到編寫器完成對文件的寫入。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM