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());
    }
 }

我上面的代码从文本文件中读取数据,查询是一个文件,其中有两个地方“sanid”和“salabel”被字符串数组的内容替换并写入另一个文件 final 。但是当我运行代码时,最终没有查询。但是在调试时,它显示所有值都已正确替换。

4

1 回答 1

0

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

如果在调试代码时发现值被替换,但文件中缺少它们,我建议您刷新输出流。您正在关闭FileWriter而不调用flush()。该close()方法将其调用委托给StreamEncoder也不刷新流的底层。

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

尝试这个

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

那应该这样做。

于 2013-07-11T11:57:28.517 回答