获取文件所在路径
// String path = System.getProperty("user.dir")
String path ="./picturePath/"+pictureName +".bmp";
tomcat服务器
1.server.xml文件增加
<Context docBase="E:\tomcat\downlogo" path="/downlogo" />
2.web.xml文件改为true
<servlet>
<servlet-name>default</servlet-name>
<servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>0</param-value>
</init-param>
<init-param>
<param-name>listings</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class DownLogo {
public static boolean downloadPicture(String pictureSourceServer,String fileName,StringBuffer res) {
try {
fileName = fileName+".bmp";
//tomcat服务器端口和文件地址映射
// String pictureSourceServer = "http://192.168.1.1:8080/downlogo/";
String saveDir = "./picture/";
File saveFile = new File(saveDir, fileName);
File dir = new File(saveDir);
//判断文件夹是否存在
if (!dir.exists()) {
dir.mkdirs();
}
//判断文件夹内的文件是否存在
if (saveFile.exists()) {
return true;
} else {
//下载
URL url = new URL(pictureSourceServer+fileName);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = httpConn.getInputStream();
OutputStream outputStream = new FileOutputStream(saveFile);
//开辟一块缓冲区间
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
//关闭输入输出流
inputStream.close();
outputStream.close();
return true;
}else {
res.append("服务器没有找到picture源文件"+fileName);
return false;
}
}
}catch (Exception e){
e.printStackTrace();
// 将异常堆栈信息保存为字符串
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
// 获取完整的堆栈信息
String stackTrace = sw.toString();
UI.TAData.append("下载picture源文件异常:"+stackTrace+"\n");
res.append("下载picture源文件异常:"+stackTrace);
return false;
}
}
public static void main(String[] args) {
// String fileName = "xxx"; // 指定文件名
// String[] strings = new String[]{"xx1","xx2","xx3","xx4"};
String[] strings = new String[]{"xxx1"};
StringBuffer res = new StringBuffer();
for (String string : strings) {
boolean downFlag = downloadPicture(pictureSourceServer,string,res);
System.out.println(downFlag);
if (res.length()>0)
System.out.println(res);
}
}
}