1. 程式人生 > >java servlet生成檔案的路徑只能是絕對路徑

java servlet生成檔案的路徑只能是絕對路徑

main程式入口執行生成圖片 ,圖片路徑是相對路徑;

右擊-run as 

重新整理右側的專案欄,在webroot的根目錄下面就會有一個role.png的檔案;

以下是java程式碼

package cn.com.condition;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import cn.com.Special.Recursive;
public class Demo {	//複製圖片到
	public static void main(String[] args) {
		demo();
	}
public static void demo(){
	// 勾勒出全部的路線軌跡
				int width = 1280;
				int height = 1024;
				// 建立一個寬500高500的背景不是透明色的圖片緩衝區----目的就是儲存圖片在記憶體
				BufferedImage bi = new BufferedImage(width, height,
						BufferedImage.TYPE_INT_RGB);
				// 幾何圖形類新建物件----繪製圖片
				Graphics2D gh = bi.createGraphics(); // 建立Graphics2D物件
				// ---------- 增加下面的程式碼使得背景透明 -----------------
				bi = gh.getDeviceConfiguration().createCompatibleImage(width, height,
						Transparency.TRANSLUCENT);
				gh.dispose();
				gh = bi.createGraphics();
				// ---------- 背景透明程式碼結束 -----------------
				// 繪製路徑直線圖示意圖
				gh.setColor(Color.CYAN);
				Recursive.dwf(gh);
				gh.dispose();
				//把路徑儲存為圖片
				File f=new File("role.png");
						if(!f.exists()){
				            try {
				                f.createNewFile();
				            } catch (IOException e) {
				                // TODO Auto-generated catch block
				                e.printStackTrace();
				            }
						}
						try {
							ImageIO.write(bi, "png", f);
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					return;
}	
}

 

同樣的在servlet裡面呼叫,用tomcat啟動之後,點選跳轉到該頁面,卻生成不了圖片

package cn.com.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.com.condition.Demo;

public class Dwg extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Demo.demo();
		response.sendRedirect("/BootStrap/role_position.jsp");
	}

}

 

這是為什麼? 難道main程式與servlet程式執行不一樣?

解決方案: