2013-07-11 99 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(); 

应该这样做。