修改JFreeChart 圖片的存放路徑

/**

**QQ:252574345

**MSN:[email protected]

*/

 

跟蹤發現,JFreeChart會把生成的圖片,默認放在應用服務器的temp目錄下,有的時候我們是不能放在該目錄下的,需要改變這個存放路徑

發現jfreechart的ServletUtilities類裏有

    protected static void createTempDir() {
        String tempDirName = System.getProperty("java.io.tmpdir");
        if (tempDirName == null) {
            throw new RuntimeException("應用服務器目錄下不存在temp目錄或該目錄無法創建");
        }

        // create the temporary directory if it doesn't exist
        File tempDir = new File(tempDirName);
        if (!tempDir.exists()) {
            tempDir.mkdirs();
        }
    }

該方法創建了默認的圖片存放路徑

在該類的saveChartAsPNG() 和saveChartAsJPEG () 裏被調用,產生圖形,因此我們的思路就是將ServletUtilities的saveChartAsPNG() 和saveChartAsJPEG () 這2個方法改造成自己定義的方法

修改前源文件如下:

    public static String saveChartAsJPEG(JFreeChart chart, int width,
            int height, ChartRenderingInfo info, HttpSession session)
            throws IOException {

        if (chart == null) {
            throw new IllegalArgumentException("Null 'chart' argument.");  
        }
        //注意,源文件使用了默認路徑
        ServletUtilities.createTempDir();
        String prefix = ServletUtilities.tempFilePrefix;
        if (session == null) {
            prefix = ServletUtilities.tempOneTimeFilePrefix;  
        }
        File tempFile = File.createTempFile(prefix, ".jpeg",
                new File(System.getProperty("java.io.tmpdir")));
        ChartUtilities.saveChartAsJPEG(tempFile, chart, width, height, info);
        if (session != null) {
            ServletUtilities.registerChartForDeletion(tempFile, session);
        }
        return tempFile.getName();

    }

 

修改後如下:

    public static String saveChartAsJPEG(JFreeChart chart, int width,
            int height, ChartRenderingInfo info, HttpSession session)
            throws IOException {

//從application中讀取出臨時文件目錄,我事先已經在系統啓動時,創建了目錄
     
       File tempDr=(File)session.getServletContext().getAttribute("tempDirectory");

      
      
        if (chart == null) {
            throw new IllegalArgumentException("chart 對象爲空");  
        }
       
        UIServletUtilities.createTempDir();
        String prefix = UIServletUtilities.tempFilePrefix;
        if (session == null) {
            prefix = UIServletUtilities.tempOneTimeFilePrefix;  
        }
        File tempFile = File.createTempFile(prefix, ".jpeg", tempDr);
        ChartUtilities.saveChartAsJPEG(tempFile, chart, width, height, info);
        if (session != null) {
         UIServletUtilities.registerChartForDeletion(tempFile, session);
        }
        return tempFile.getName();

    }

 

接下來就可以使用

String filename = ServletUtilities.saveChartAsJPEG(chart, 800, 600, info, session);
String graphURL = request.getContextPath() + "/DisplayChart?filename=" + filename;

來生成圖形了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章