无法通过BufferedReader

时间:2016-07-28 23:18:34

标签: java spring spring-boot

我无法通过BufferedReader对象读取文本文件。但是,我可以通过BufferedWriter对象成功写入同一文本文件。

我的程序的目的是读取一个名为queryCountFile.txt的文本文件,然后该文件将能够确定先前创建了多少Query个对象(我的自定义对象)。从那里,我将能够创建尽可能多的Query个对象,同时能够跟踪所述查询的数量。

尝试(和失败)从文本文件中读取的函数称为findNumberOfQueries()。它位于我的名为 Query.java

的文件中

任何人都可以理解为什么我无法从文本文件中读取文件吗?

QuickControllerApplication.java

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
public class QuickControllerApplication {

    public static void main(String[] args) {
        SpringApplication.run(QuickControllerApplication.class, args);
        //everthing below this line is for testing purposes
        Query littleQuery = new Query(101L);
        //littleQuery.testPrint();
        littleQuery.generateQueryID();
        System.out.println(littleQuery.findNumberOfQueries());
    }
}

Query.java

/**************************************************************
 * queryIDNumber - a long that holds the individual data of an
 * individual query. Each query will have a unique number
 * associated with it.
 **************************************************************/
public class Query {
    final Long MIN_ID_NUMBER = 1L;  //minimum ID Number that can be ever generated by the program
    final String QUERY_COUNT_FILE = "queryCountFile.txt";       //this file will simply hold a number that states how many queries have been created
    final int SKIP_NUM_LINES_IN_FILE = 2;   //the first X number of lines that will skipped in QUERY_COUNT_FILE

    //final Long MAX_ID_NUMBER = 9223372036854775807L; //maximum ID Number that can be ever generated by the program

    private Long queryID;           //each query must have a unique ID Number which will go in the URL when the user is viewing the result of the query search.
    private static Long totalQueryIDs = 0L;      //holds the value of how many queries have been created over the life of the program

    public Query(Long previouslyGeneratedIDNumber)
    {
        generateQueryID();
        //totalQueryIDs++;
        //OTHER FUNCTION CALLS
        //WILL PROBABLY GO
        //HERE LATER...
    }

/**************************************************************
 * generateQueryID - Generate a ID Number for a query. ID
 * Number must be unique, and then is assigned to queryID
 **************************************************************/
public void generateQueryID(){
    Long generatedNumber;

    //Finds the totalQueryIDs stored in QUERY_COUNT_FILE
    generatedNumber = findNumberOfQueries();

    if (generatedNumber <= MIN_ID_NUMBER){
        totalQueryIDs = MIN_ID_NUMBER;
    }
    else {
        totalQueryIDs = generatedNumber + 1L;
    }

    queryID = totalQueryIDs;
}
/**************************************************************
     * findNumberOfQueries - This function finds out how many
     * queries have been generated so far. This function will check
     * a text file that will contain the past number of queries
     * that have been generated.
     **************************************************************/
    public Long findNumberOfQueries(){
        //Check a file. If queryCountFile.txt is not found then numberOfQueries is considered 0 and becomes 1?
        try {
            Date date = new Date();
            //Assume default encoding.
            FileWriter fileWriter = new FileWriter(QUERY_COUNT_FILE);
            FileReader fileReader = new FileReader(QUERY_COUNT_FILE);

            //Always wrap FileWriter in BufferedWriter.
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
            //Always wrap FileReader in BufferedReader.
            BufferedReader bufferedReader = new BufferedReader(fileReader);

            bufferedWriter.write("FILE LAST WRITTEN TO ON: " + date + "\n");
            bufferedWriter.write("totalQueryIDs:\n");
            bufferedWriter.write("5");

            //reading from QUERY_COUNT_FILE
            try{
                System.out.println("got here\n");   //debug statement
                String line;    //temp var

                //skip first SKIP_NUM_LINES_IN_FILE lines in QUERY_COUNT_FILE
                for (int count = 0; count < SKIP_NUM_LINES_IN_FILE; count++) {
                    bufferedReader.readLine();
                }

                line = bufferedReader.readLine();
                while (line != null) {
                    System.out.println("stuff bufferedReader got: " + line);
                }
            }
            catch(IOException ex) {
                System.out.println("Error reading to file '" + QUERY_COUNT_FILE + "'");
            }

            //Close the file.
            bufferedWriter.close();
            bufferedReader.close();
        }
        catch(IOException ex) {
            System.out.println("Error writing to file '" + QUERY_COUNT_FILE + "'");
        }
return totalQueryIDs;
}

}

1 个答案:

答案 0 :(得分:2)

让我建议您使用最新的API方法读取您的行,这样可以更容易阅读和维护(至少在我看来):

try(final Stream<String> fileStream = Files.lines(Paths.get("queryCountFile.txt")){
    fileStream.skip(SKIP_NUM_LINES_IN_FILE)
              .forEach(line -> processMyLine(line));
}

为了完整起见,您的示例中的问题是您永远不会在循环中重新分配line变量:

while(line != null)

应该是:

while((line = bufferedReader.readLine()) != null)