通过jsp动态创建文件

时间:2014-02-17 10:02:09

标签: java jsp io

我有一块像这样的jsp代码。这里的blockerdata,criticaldata,majordata和minordata是stringbuilder字符串,它们的值通过循环附加,并且值是动态分配的。现在我试着把它们写成像这样的xml文件。

<%
        System.out.println(blockerdata);
        System.out.println(criticaldata);
        System.out.println(majordata);
        System.out.println(minordata);
        try
        {

            File file1 = new File("WebContent/criticaldata.xml");
            File file2 = new File("WebContent/majordata.xml");
            File file3 = new File("WebContent/minordata.xml");
            File file4 = new File("WebContent/blockerdata.xml");

            FileOutputStream fop1 = new FileOutputStream(file1);
            FileOutputStream fop2 = new FileOutputStream(file2);
            FileOutputStream fop3 = new FileOutputStream(file3);
            FileOutputStream fop4 = new FileOutputStream(file4);


            // if file doesnt exists, then create it
            if (!file1.exists()) {
                file1.createNewFile();
            }
            if (!file2.exists()) {
                file2.createNewFile();
            }
            if (!file3.exists()) {
                file3.createNewFile();
            }
            if (!file4.exists()) {
                file4.createNewFile();
            }

            // get the content in bytes
            byte[] contentInBytes1= criticaldata.toString().getBytes();
            byte[] contentInBytes2= majordata.toString().getBytes();
            byte[] contentInBytes3= minordata.toString().getBytes();
            byte[] contentInBytes4= blockerdata.toString().getBytes();

            fop1.write(contentInBytes1);
            fop2.write(contentInBytes1);
            fop3.write(contentInBytes1);
            fop4.write(contentInBytes1);

            fop1.flush();
            fop2.flush();
            fop3.flush();
            fop4.flush();

            fop1.close();
            fop2.close();
            fop3.close();
            fop4.close();

        }
        catch ( IOException e)
        {
        }
        %>

问题是,代码似乎不起作用。我也试过用printwriter来做 文件未生成。此外,我想重写该文件,如果它已经存在。有人可以帮我解决一下这个问题吗?

0 个答案:

没有答案