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程序执行不一样?

解决方案:

猜你喜欢

转载自blog.csdn.net/qq_37591637/article/details/84137484