2016-07-28 55 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 )'。 –