简体   繁体   English

无法通过BufferedReader读取文本文件

[英]Unable to Read a Text File via BufferedReader

I am unable to read a text file via a BufferedReader Object. 我无法通过BufferedReader对象读取文本文件。 However I can successfully write to the same text file via a BufferedWriter Object. 但是,我可以通过BufferedWriter对象成功写入同一文本文件。

The intent of my program is to read a text file called queryCountFile.txt which will then able to figure out how many Query Objects (my custom object) have been previously created. 我的程序的目的是读取一个名为queryCountFile.txt的文本文件,该文件queryCountFile.txt将能够确定先前已创建了多少个Query对象(我的自定义对象)。 From there, I will then be able to create as many Query Objects as a want while being able to keep track of the number of said Queries. 从那里,我将能够根据需要创建任意数量的Query对象,同时能够跟踪所述查询的数量。

The function that tries (and fails) to read from the text file is called findNumberOfQueries() . 尝试(失败)从文本文件读取的函数称为findNumberOfQueries() It is located in my file called Query.java 它位于我的名为Query.java的文件中

Can anyone understand why I am unable to read from the text file? 谁能理解我为什么无法从文本文件中读取内容?

QuickControllerApplication.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 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;
}

} }

Let me suggest you another way of reading your lines using most recent APIs method which make it easier to read and maintain (at least in my opinion) : 让我为您建议另一种使用最新API方法读取行的方法,该方法使读取和维护更加容易(至少在我看来):

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

For completeness, the problem in your example is that you never re-assign line variable in your loop : 为了完整起见,示例中的问题是您永远不会在循环中重新分配line变量:

while(line != null)

should be : 应该 :

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM