2013-07-11 42 views
0
public static void main(String[] args) { 
    ArrayList<String> studentTokens = new ArrayList<String>(); 
    ArrayList<String> studentIds = new ArrayList<String>(); 
    try { 
     // Open the file that is the first 
     // command line parameter 
     FileInputStream fstream = new FileInputStream(new File("file1.txt")); 
     BufferedReader br = new BufferedReader(new InputStreamReader(fstream, "UTF8")); 

     String strLine; 
     // Read File Line By Line 
     while ((strLine = br.readLine()) != null) { 
      strLine = strLine.trim(); 

      if ((strLine.length()!=0) && (!strLine.contains("#"))) { 
       String[] students = strLine.split("\\s+"); 
       studentTokens.add(students[TOKEN_COLUMN]); 
       studentIds.add(students[STUDENT_ID_COLUMN]); 
      } 

     } 





     for (int i=0; i<studentIds.size();i++) { 
      File file = new File("query.txt");              // The path of the textfile that will be converted to csv for upload 
      BufferedReader reader = new BufferedReader(new FileReader(file)); 
      String line = "", oldtext = ""; 
      while ((line = reader.readLine()) != null) {                 
       oldtext += line + "\r\n"; 
      } 
      reader.close(); 
      String newtext = oldtext.replace("sanid", studentIds.get(i)).replace("salabel",studentTokens.get(i));           // Here the name "sanket" will be replaced by the current time stamp 
      FileWriter writer = new FileWriter("final.txt",true); 
      writer.write(newtext); 
      writer.close(); 
     } 


     fstream.close(); 
     br.close(); 
     System.out.println("Done!!"); 
    } catch (Exception e) { 
     e.printStackTrace(); 
     System.err.println("Error: " + e.getMessage()); 
    } 
} 

礦的上面的代碼從文本文件和查詢讀數據寫入多個查詢是具有其中2個地方「sanid」和「salabel」通過的內容替換的查詢的文件字符串數組並寫入另一個文件final。但是當我運行代碼時,最終沒有查詢。但在調試時顯示所有值都被正確替換。從一個測試文件

+0

因此'System.out.println(newtext)'輸出正確的數據,但'final.txt'不包含相同的東西? – assylias

+0

使用stringbuffer append方法 –

回答

0

但同時調試它表明,所有的值都正確更換

如果找到值,當你調試的代碼進行替換,但它們在文件中丟失,我建議你刷新輸出流。您正在關閉FileWriter而無需致電flush()close()方法將其調用委託給底層的StreamEncoder,它不會刷新流。

public void close() throws IOException { 
se.close(); 
} 

試試這個

writer.flush(); 
writer.close(); 

應該這樣做。