2016-07-28 54 views
0

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

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

尝试(并失败)从文本文件读取的功能称为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; 
} 

}

+4

1.您应该刷新和在尝试读取前关闭'Writer' 2. while(line!= null){''line'永远不会被重新赋值 - 如果在这一点不是null,将会有一个无限循环。 – copeg

+0

是的,是正确的。谢谢一堆! – lordmichael95

+1

这是旧式阅读方式nio提供了读取所有文件或流线等的方法。 –

回答

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) 
+0

根据您的代码,'processMyLine()'是一个自定义函数。但是它究竟做了什么?这是一个函数,你是否打电话'System.out.println()'和其他相关的功能,如果有这样的愿望? – lordmichael95

+0

@ lordmichael95它做你想做的任何事 - 它是你创造它的角色。基本上,这是一个你将创建的函数,它将接收一行(作为'String')作为参数。你可以放任何你想要的东西。尽管如果你只想打印这一行,你可以用'System.out :: println'替换'line - > processMyLine(line)'。另外,如果'processMyLine'在同一个类中,如果你希望它更简洁(我个人这样做),你也可以改变'line - > processMyLine(line)'为'this :: processMyLine'。如果你想打印一个自定义的消息,就像你的实际代码 –

+0

[...]一样,你可以使用lambda语法:'line - > System.out.println(“stuff bufferedReader got:”+ line )'。 –