从测试文件中写入多个查询

时间:2013-07-11 11:05:03

标签: java bufferedreader filewriter

    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。但是当我运行代码时,最终没有查询。但调试时显示所有值都已正确替换。

1 个答案:

答案 0 :(得分:0)

  

但在调试时显示所有值都已正确替换

如果在调试代码时发现值被替换,但文件中缺少这些值,我建议您刷新输出流。您正在关闭FileWriter而不致电flush()close()方法将其调用委托给不会刷新流的基础StreamEncoder

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

试试这个

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

应该这样做。