3.java 关于文件
1.java 读取文件
public class ReadFromFile {
/**
* 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。
*/
public static void readFileByBytes(String fileName) {
File file = new File(fileName);
InputStream in = null;
try {
System.out.println("以字节为单位读取文件内容,一次读一个字节:");
// 一次读一个字节
in = new FileInputStream(file);
int tempbyte;
while ((tempbyte = in.read()) != -1) {
System.out.write(tempbyte);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
return;
}
try {
System.out.println("以字节为单位读取文件内容,一次读多个字节:");
// 一次读多个字节
byte[] tempbytes = new byte[100];
int byteread = 0;
in = new FileInputStream(fileName);
ReadFromFile.showAvailableBytes(in);
// 读入多个字节到字节数组中,byteread为一次读入的字节数
while ((byteread = in.read(tempbytes)) != -1) {
System.out.write(tempbytes, 0, byteread);
}
} catch (Exception e1) {
e1.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e1) {
}
}
}
}
/**
* 以字符为单位读取文件,常用于读文本,数字等类型的文件
*/
public static void readFileByChars(String fileName) {
File file = new File(fileName);
Reader reader = null;
try {
System.out.println("以字符为单位读取文件内容,一次读一个字节:");
// 一次读一个字符
reader = new InputStreamReader(new FileInputStream(file));
int tempchar;
while ((tempchar = reader.read()) != -1) {
// 对于windows下,\r\n这两个字符在一起时,表示一个换行。
// 但如果这两个字符分开显示时,会换两次行。
// 因此,屏蔽掉\r,或者屏蔽\n。否则,将会多出很多空行。
if (((char) tempchar) != '\r') {
System.out.print((char) tempchar);
}
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
System.out.println("以字符为单位读取文件内容,一次读多个字节:");
// 一次读多个字符
char[] tempchars = new char[30];
int charread = 0;
reader = new InputStreamReader(new FileInputStream(fileName));
// 读入多个字符到字符数组中,charread为一次读取字符数
while ((charread = reader.read(tempchars)) != -1) {
// 同样屏蔽掉\r不显示
if ((charread == tempchars.length)
&& (tempchars[tempchars.length - 1] != '\r')) {
System.out.print(tempchars);
} else {
for (int i = 0; i < charread; i++) {
if (tempchars[i] == '\r') {
continue;
} else {
System.out.print(tempchars[i]);
}
}
}
}
} catch (Exception e1) {
e1.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}
/**
* 以行为单位读取文件,常用于读面向行的格式化文件
*/
public static void readFileByLines(String fileName) {
File file = new File(fileName);
BufferedReader reader = null;
try {
System.out.println("以行为单位读取文件内容,一次读一整行:");
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
// 一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
// 显示行号
System.out.println("line " + line + ": " + tempString);
line++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}
/**
* 随机读取文件内容
*/
public static void readFileByRandomAccess(String fileName) {
RandomAccessFile randomFile = null;
try {
System.out.println("随机读取一段文件内容:");
// 打开一个随机访问文件流,按只读方式
randomFile = new RandomAccessFile(fileName, "r");
// 文件长度,字节数
long fileLength = randomFile.length();
// 读文件的起始位置
int beginIndex = (fileLength > 4) ? 4 : 0;
// 将读文件的开始位置移到beginIndex位置。
randomFile.seek(beginIndex);
byte[] bytes = new byte[10];
int byteread = 0;
// 一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。
// 将一次读取的字节数赋给byteread
while ((byteread = randomFile.read(bytes)) != -1) {
System.out.write(bytes, 0, byteread);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (randomFile != null) {
try {
randomFile.close();
} catch (IOException e1) {
}
}
}
}
/**
* 显示输入流中还剩的字节数
*/
private static void showAvailableBytes(InputStream in) {
try {
System.out.println("当前字节输入流中的字节数为:" + in.available());
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String fileName = "C:/temp/newTemp.txt";
ReadFromFile.readFileByBytes(fileName);
ReadFromFile.readFileByChars(fileName);
ReadFromFile.readFileByLines(fileName);
ReadFromFile.readFileByRandomAccess(fileName);
}
}
2.通过URL获取文件
package test1;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class FileDown {
/**
* 说明:根据指定URL将文件下载到指定目标位置
*
* @param urlPath
* 下载路径
* @param downloadDir
* 文件存放目录
* @return 返回下载文件
*/
@SuppressWarnings("finally")
public static File downloadFile(String urlPath, String downloadDir) {
File file = null;
try {
// 统一资源
URL url = new URL(urlPath);
// 连接类的父类,抽象类
URLConnection urlConnection = url.openConnection();
// http的连接类
HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
//设置超时
httpURLConnection.setConnectTimeout(1000*5);
//设置请求方式,默认是GET
httpURLConnection.setRequestMethod("POST");
// 设置字符编码
httpURLConnection.setRequestProperty("Charset", "UTF-8");
// 打开到此 URL引用的资源的通信链接(如果尚未建立这样的连接)。
httpURLConnection.connect();
// 文件大小
int fileLength = httpURLConnection.getContentLength();
// 控制台打印文件大小
System.out.println("您要下载的文件大小为:" + fileLength / (1024 * 1024) + "MB");
// 建立链接从请求中获取数据
URLConnection con = url.openConnection();
BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());
// 指定文件名称(有需求可以自定义)
String fileFullName = "aaa.apk";
// 指定存放位置(有需求可以自定义)
String path = downloadDir + File.separatorChar + fileFullName;
file = new File(path);
// 校验文件夹目录是否存在,不存在就创建一个目录
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
OutputStream out = new FileOutputStream(file);
int size = 0;
int len = 0;
byte[] buf = new byte[2048];
while ((size = bin.read(buf)) != -1) {
len += size;
out.write(buf, 0, size);
// 控制台打印文件下载的百分比情况
System.out.println("下载了-------> " + len * 100 / fileLength + "%\n");
}
// 关闭资源
bin.close();
out.close();
System.out.println("文件下载成功!");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("文件下载失败!");
} finally {
return file;
}
}
/**
* 测试
*
* @param args
*/
public static void main(String[] args) {
// 指定资源地址,下载文件测试
downloadFile("http://count.liqucn.com/d.php?id=22709&urlos=android&from_type=web", "B:/myFiles/");
}
}
3.java new File(网络路径)
import java.net.URL;
public static void main(String[] args) {
try {
URL url = new URL("http://10.xxx/xxx/abc.xlsx");
URLConnection connection = url.openConnection();
InputStream is = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is,"gb2312"));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
4.java通过httppost请求传文件
public class MainUI {
private static final String REQUEST_PATH = "http://localhost/server_url.php";
private static final String BOUNDARY = "20140501";
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
URL url = new URL(REQUEST_PATH);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setConnectTimeout(3000); // 设置发起连接的等待时间,3s
httpConn.setReadTimeout(30000); // 设置数据读取超时的时间,30s
httpConn.setUseCaches(false); // 设置不使用缓存
httpConn.setDoOutput(true);
httpConn.setRequestMethod("POST");
httpConn.setRequestProperty("Connection", "Keep-Alive");
httpConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
OutputStream os = httpConn.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(os);
String content = "--" + BOUNDARY + "\r\n";
content += "Content-Disposition: form-data; name=\"title\"" + "\r\n\r\n";
content += "我是post数据的值";
content += "\r\n--" + BOUNDARY + "\r\n";
content += "Content-Disposition: form-data; name=\"cover_img\"; filename=\"avatar.jpg\"\r\n";
content += "Content-Type: image/jpeg\r\n\r\n";
bos.write(content.getBytes());
// 开始写出文件的二进制数据
FileInputStream fin = new FileInputStream(new File("avatar.jpg"));
BufferedInputStream bfi = new BufferedInputStream(fin);
byte[] buffer = new byte[4096];
int bytes = bfi.read(buffer, 0, buffer.length);
while (bytes != -1) {
bos.write(buffer, 0, bytes);
bytes = bfi.read(buffer, 0, buffer.length);
}
bfi.close();
fin.close();
bos.write(("\r\n--" + BOUNDARY).getBytes());
bos.flush();
bos.close();
os.close();
// 读取返回数据
StringBuffer strBuf = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpConn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
strBuf.append(line).append("\n");
}
String res = strBuf.toString();
System.out.println(res);
reader.close();
httpConn.disconnect();
}
}
5.ssp发送文件案例
package com.esint.plug.util;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Stream;
import javax.activation.MimetypesFileTypeMap;
import javax.net.ssl.SSLContext;
import javax.servlet.http.HttpServletRequest;
import javax.sound.sampled.AudioFormat;
import org.apache.commons.lang.StringUtils;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustAllStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.aspectj.weaver.ast.Var;
import org.omg.IOP.Encoding;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.esint.plug.consts.GlobalConsts;
import com.esint.plug.enums.ResultEnums;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
* @program: pahx
* @description: http 请求 相关工具
* @author: ZhengWei
* @updater: wangyuanhao
* @updatTime: 2019-07-16
* @create: 2018-03-20 09:42
**/
public final class HttpUtils {
private static final Logger logger = LoggerFactory.getLogger("esint");
// 文件保存的路径
private static final String PATH_KEY = "path";
public HttpUtils() {}
private static HttpUtils httpUtils;
public HttpUtils getInstance(){
if(httpUtils == null){
httpUtils = new HttpUtils();
}
return httpUtils;
}
/**
* 下载进度
* @auth wangyuanhao
* @date 2019-07-15
*/
public interface HttpClientDownLoadProgress {
public void onProgress(int progress);
}
/**
* 功能描述:后台模拟 get 请求
*
* @param url 请求路径
* @param param 参数(多个参数需要使用&分隔)
*
* @return java.lang.String
*
* @throw
* @Author 郑伟
* @version V1.0.0
* @Date 2018/3/20 上午9:45
*/
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
// for (String key : map.keySet()) {
// System.out.println(key + "--->" + map.get(key));
// }
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/**
* 功能描述:后台模拟 post 请求
*
* @param url 请求路径
* @param param 参数(多个参数需要使用&分隔)
*
* @return java.lang.String
*
* @throw
* @Author 郑伟
* @version V1.0.0
* @Date 2018/3/20 上午9:45
*/
public static String sendPost(String url, String param) {
OutputStream out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = conn.getOutputStream();
// 发送请求参数
out.write(param.getBytes("UTF-8"));
// System.out.println("###################" + param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
/**
* post提交form表单
* @date 2019-06-23 19:00
* @auth wangyuanhao
* @param url
* @param paramMap
*/
public static String sendPostForm(String url, Map<String,String> paramMap) {
HttpPost post = new HttpPost(url);
List<BasicNameValuePair> pairList = new ArrayList<>();
// 迭代map --> 取出key,val放到BasicNameValuePair对象中 --> 添加到list
for(String key : paramMap.keySet()){
pairList.add(new BasicNameValuePair(key,paramMap.get(key)));
}
String resultData = null;
try {
UrlEncodedFormEntity uefe = new UrlEncodedFormEntity(pairList,"utf-8");
post.setEntity(uefe);
post.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
// 创建一个http客户端
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 发送post请求
CloseableHttpResponse response = httpClient.execute(post);
// 状态码为200
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
// 返回数据
resultData = EntityUtils.toString(response.getEntity(),"utf-8");
}
} catch (Exception e) {
e.printStackTrace();
}
return resultData;
}
/**
*
* @param urlStr 请求路径
* @param textMap 封装的文本参数
* @param fileMap 文件参数
* @param contentType 没有传入文件类型默认采用application/octet-stream
* contentType非空采用filename匹配默认的图片类型
*
* @return 返回response数据
*/
@SuppressWarnings("rawtypes")
public static String formUploadCenter(String urlStr, Map<String, String> textMap,
Map<String, String> fileMap, List<String> filesList,String contentType) {
String res = "";
HttpURLConnection conn = null;
// boundary就是request头和上传文件内容的分隔符
String boundary = "---------------------------123821742118716";
//Encoding encoding = Encoding.UTF8;
try {
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(30000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Accept","application/json, text/javascript, */*");
conn.setRequestProperty("User-Agent",
"Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
conn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
conn.setRequestProperty("charsert", "utf-8");
// OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
OutputStream out = new DataOutputStream(conn.getOutputStream());
// text
if (textMap != null) {
StringBuffer strBuf = new StringBuffer();
Iterator iter = textMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
String inputName = (String) entry.getKey();
String inputValue = (String) entry.getValue();
System.out.println("inputName------- "+inputName);
System.out.println("inputValue------- "+inputValue);
if (inputValue == null) {
continue;
}
strBuf.append("\r\n").append("--").append(boundary).append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n");
strBuf.append(inputValue);
}
out.write(strBuf.toString().getBytes());
System.out.println("strBuf======"+strBuf);
}
// file
if(!filesList.isEmpty()){
for (String strFilePath : filesList) {
//http://file.zfw.weijingyuan.com.cn:9000/front/downfile?guid=1add5e39-d6b1-451f-9091-8a5c20448cb6
String strPathPer = "http://file.zfw.weijingyuan.com.cn:9000/front/downfile?guid=";
String strPathLas = strFilePath.split("&")[2];
//String strZFWPath = strFilePath.replace("192.156.193.201:8888","file.zfw.weijingyuan.com.cn:9000");
String strZFWPath = strPathPer+strPathLas;
System.out.println("strPathPer ````````````````````````````````````` "+strPathPer);
System.out.println("strPathLas ````````````````````````````````````` "+strPathLas);
System.out.println("strZFWPath ````````````````````````````````````` "+strZFWPath);
File file = new File(strZFWPath);
System.out.println("filename ===============================文件开始的方法 ------------------------------------------------------------------------------=====================");
System.out.println("filename ===================================================="+ file.getName());
// Stream mys = (Stream) getHttpServletRequest().getInputStream();
System.out.println("****** file --------****//*//********"+file);
//http:/192.156.193.201:8888/group1/M00/65/9D/wJzByWIcUmiAUHNWAAbRshfYdiI78.jpeg file
String filename = strFilePath.split("&")[1];;
/* if (file.exists()) {
System.out.println("文件不存在");
filename = file.getName();
}*/
System.out.println("filename------------- ******************// "+filename);
contentType = "application/octet-stream";
StringBuffer strBuf = new StringBuffer();
strBuf.append("\r\n").append("--").append(boundary).append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\"" + "file" + "\"; filename=\"" + filename + "\"\r\n");
strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
System.out.println("strBuf file======"+strBuf);
out.write(strBuf.toString().getBytes());
/* if (file.exists()) {
System.out.println(" /// ----------文件不存在");
DataInputStream in = new DataInputStream(
new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
in.close();
}*/
URL urlAttach = null;
try {
System.out.println("```````````````````````````````````````````````````````````````开始下载文件并调用上传方法```````````````````````````````````````````````````````");
// 统一资源
urlAttach = new URL(strZFWPath);
// 连接类的父类,抽象类
URLConnection connection = urlAttach.openConnection();
// http的连接类
HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
//设置超时
httpURLConnection.setConnectTimeout(1000 * 5);
//设置请求方式,默认是GET
httpURLConnection.setRequestMethod("POST");
// 设置字符编码
httpURLConnection.setRequestProperty("Charset", "UTF-8");
// 打开到此 URL引用的资源的通信链接(如果尚未建立这样的连接)。
httpURLConnection.connect();
// 建立链接从请求中获取数据
URLConnection con = url.openConnection();
BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());
// 指定文件名称(有需求可以自定义)
String fileFullName = strFilePath.split("&")[1];
// 指定存放位置(有需求可以自定义)
//String path = downloadDir + File.separatorChar + fileFullName;
String strSys = System.getProperty("user.dir");
String path =strSys+File.separatorChar +"tempFileByCenter" +File.separator+ fileFullName;
System.out.println("新路径------------------------------------------ " +path);
file = new File(path);
// 校验文件夹目录是否存在,不存在就创建一个目录
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
OutputStream out1 = new FileOutputStream(file);
String strFileName = file.getName();
System.out.println("strname === " + strFileName);
int size = 0;
int len = 0;
byte[] buf = new byte[2048];
while ((size = bin.read(buf)) != -1) {
len += size;
out1.write(buf, 0, size);
out.write(buf, 0, size);
}
// 关闭资源
bin.close();
out1.close();
System.out.println("```````````````````````````````````````````````````````````````开始下载文件并调用上传方法11111```````````````````````````````````````````````````````");
if (file.exists()) {
System.out.println("```````````````````````````````````````````````````````````````开始下载文件并调用上传方法222```````````````````````````````````````````````````````"+file +"ssss"+file.getName());
DataInputStream in = new DataInputStream(
new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
in.close();
}
/* System.out.println("文件下载成功!");
InputStream is = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is,"utf-8"));
String line = "";
while ((line = br.readLine()) != null) {
strBuf.append(line);
out.write(Integer.parseInt(line));
}
br.close();
out1.close();*/
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
/*
FileInputStream fin = new FileInputStream(new File(strZFWPath));
BufferedInputStream bfi = new BufferedInputStream(fin);
byte[] buffer = new byte[4096];
int bytesFile = bfi.read(buffer, 0, buffer.length);
while (bytesFile != -1) {
out.write(buffer, 0, bytesFile);
bytesFile = bfi.read(buffer, 0, buffer.length);
}
bfi.close();
fin.close();
out.write(("\r\n--" + boundary).getBytes());
out.flush();
out.close();
*/
}
}
byte[] endData = ("\r\n--" + boundary + "--\r\n").getBytes();
System.out.println("endData------------- "+endData);
out.write(endData);
out.flush();
out.close();
// 读取返回数据
StringBuffer strBuf = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
strBuf.append(line).append("\n");
}
res = strBuf.toString();
reader.close();
reader = null;
} catch (Exception e) {
System.out.println("发送POST请求出错。" + urlStr);
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
conn = null;
}
}
return res;
}
/**
* post提交form表单
* @date 2022-02-15 11:00
* @auth 祁玉良
* @param url
* @param paramMap
*/
public static String sendPostFormUrl(String url, Map<String,String> paramMap) {
HttpPost post = new HttpPost(url);
List<BasicNameValuePair> pairList = new ArrayList<>();
// 迭代map --> 取出key,val放到BasicNameValuePair对象中 --> 添加到list
for(String key : paramMap.keySet()){
pairList.add(new BasicNameValuePair(key,paramMap.get(key)));
}
String resultData = null;
try {
UrlEncodedFormEntity uefe = new UrlEncodedFormEntity(pairList,"utf-8");
post.setEntity(uefe);
post.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
// 创建一个http客户端
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 发送post请求
CloseableHttpResponse response = httpClient.execute(post);
// 状态码为200
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
// 返回数据
resultData = EntityUtils.toString(response.getEntity(),"utf-8");
}
} catch (Exception e) {
e.printStackTrace();
}
return resultData;
}
public static String sendPostJson(String url, String param) {
OutputStream out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = conn.getOutputStream();
// 发送请求参数
out.write(param.getBytes("UTF-8"));
// System.out.println("###################" + param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
/**
* 后台模拟上传图片
*
* @param urlStr 请求路径
* @param textMap 封装的文本参数
* @param fileMap 文件参数
* @param contentType 没有传入文件类型默认采用application/octet-stream
* contentType非空采用filename匹配默认的图片类型
*
* @return 返回response数据
*/
@SuppressWarnings("rawtypes")
public static String formUpload(String urlStr, Map<String, String> textMap,
Map<String, String> fileMap, String contentType) {
String res = "";
HttpURLConnection conn = null;
// boundary就是request头和上传文件内容的分隔符
String boundary = "---------------------------123821742118716";
try {
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(30000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("User-Agent",
"Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
conn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
OutputStream out = new DataOutputStream(conn.getOutputStream());
// text
if (textMap != null) {
StringBuffer strBuf = new StringBuffer();
Iterator iter = textMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
String inputName = (String) entry.getKey();
String inputValue = (String) entry.getValue();
if (inputValue == null) {
continue;
}
strBuf.append("\r\n").append("--").append(boundary)
.append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\""
+ inputName + "\"\r\n\r\n");
strBuf.append(inputValue);
}
out.write(strBuf.toString().getBytes());
}
// file
if (fileMap != null) {
Iterator iter = fileMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
String inputName = (String) entry.getKey();
String inputValue = (String) entry.getValue();
if (inputValue == null) {
continue;
}
String[] valueSplit = inputValue.split(",");
for (String fileStr : valueSplit) {
File file = new File(fileStr);
String filename = "";
if (file.exists()) {
filename = file.getName();
}
//没有传入文件类型,同时根据文件获取不到类型,默认采用application/octet-stream
contentType = new MimetypesFileTypeMap().getContentType(file);
//contentType非空采用filename匹配默认的图片类型
if (!"".equals(contentType)) {
if (filename.endsWith(".png")) {
contentType = "image/png";
} else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".jpe")) {
contentType = "image/jpeg";
} else if (filename.endsWith(".gif")) {
contentType = "image/gif";
} else if (filename.endsWith(".ico")) {
contentType = "image/image/x-icon";
}
}
if (contentType == null || "".equals(contentType)) {
contentType = "application/octet-stream";
}
StringBuffer strBuf = new StringBuffer();
strBuf.append("\r\n").append("--").append(boundary)
.append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\""
+ inputName + "\"; filename=\"" + filename
+ "\"\r\n");
strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
out.write(strBuf.toString().getBytes());
if (file.exists()) {
DataInputStream in = new DataInputStream(
new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
in.close();
}
}
}
}
byte[] endData = ("\r\n--" + boundary + "--\r\n").getBytes();
out.write(endData);
out.flush();
out.close();
// 读取返回数据
StringBuffer strBuf = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
strBuf.append(line).append("\n");
}
res = strBuf.toString();
reader.close();
reader = null;
} catch (Exception e) {
System.out.println("发送POST请求出错。" + urlStr);
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
conn = null;
}
}
return res;
}
/**
* 功能描述:下载远程文件到本地
* @param remoteFilePath 远程图片地址 http://**
* @param localFilePath 本地保存路径
* @return void
* @throw
* @Author 郑伟
* @version V1.0.0
* @Date 2018/4/9 下午6:33
*/
public static void downloadFile(String remoteFilePath, String localFilePath) {
URL urlfile = null;
HttpURLConnection httpUrl = null;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
//创建本地文件
/**
* 增加路径判断,如果没有路径创建路径
*/
File file = new File(localFilePath);
try {
/**
* 增加判断是否是 http 路径 详见 : /usr/local/apache-maven/apache-maven-3.3.9/repository/cn/hutool/hutool-all/4.0.9/hutool-all-4.0.9.jar!/cn/hutool/http/HttpUtil.class
*/
urlfile = new URL(remoteFilePath);
httpUrl = (HttpURLConnection) urlfile.openConnection();
httpUrl.connect();
//将文件读入流中
bis = new BufferedInputStream(httpUrl.getInputStream());
//创建写入流
bos = new BufferedOutputStream(new FileOutputStream(file));
int len = 2048;
byte[] bytes = new byte[len];
//循环读入流
while ((len = bis.read(bytes)) != -1) {
bos.write(bytes, 0, len);
}
//刷新并关闭
bos.flush();
bis.close();
//断开连接,其他请求不可用
httpUrl.disconnect();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
bis.close();
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 功能描述:获取 request
*
* @param
*
* @return javax.servlet.http.HttpServletRequest
*
* @throw
* @Author 郑伟
* @version V1.0.0
* @Date 2018/4/11 下午4:55
*/
public static HttpServletRequest getHttpServletRequest() {
RequestAttributes ra = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes sra = (ServletRequestAttributes) ra;
HttpServletRequest request = sra.getRequest();
return request;
}
/**
* 功能描述:从Request对象中获得客户端IP,处理了HTTP代理服务器和Nginx的反向代理截取了ip
* @param request
* @return java.lang.String
* @throw
* @Author 郑伟
* @version V1.0.0
* @Date 2018/4/11 下午5:00
*/
public static String getLocalIp(HttpServletRequest request) {
String remoteAddr = request.getRemoteAddr();
String forwarded = request.getHeader("X-Forwarded-For");
String realIp = request.getHeader("X-Real-IP");
String ip = null;
if (realIp == null) {
if (forwarded == null) {
ip = remoteAddr;
} else {
ip = remoteAddr + "/" + forwarded.split(",")[0];
}
} else {
if (realIp.equals(forwarded)) {
ip = realIp;
} else {
if(forwarded != null){
forwarded = forwarded.split(",")[0];
}
ip = realIp + "/" + forwarded;
}
}
return ip;
}
/**
* 下载附件地址
* @auth wangyuanhao
* @param utilsElement
*/
public static void httpDownloadFile(HttpUtilsElement utilsElement) {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
/********************************忽略 https 的安全验证 start *****************************/
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(new TrustAllStrategy()).build();
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
sslContext,
new String[]{"TLSv1"},
null,
SSLConnectionSocketFactory.getDefaultHostnameVerifier()
);
CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
/********************************忽略 https 的安全验证 end *****************************/
HttpGet httpGet = new HttpGet(utilsElement.getUrl());
setGetHead(httpGet, utilsElement.getHeadMap());
CloseableHttpResponse response = client.execute(httpGet);
// 获取文件名
Header[] headers = response.getHeaders("Content-Disposition");
for(Header head : headers){
HeaderElement[] elements = head.getElements();
for(HeaderElement element : elements){
NameValuePair pair = element.getParameterByName("filename");
if(pair != null && StringUtils.isBlank(utilsElement.getFileName())){
utilsElement.setFileName(pair.getValue());
break;
}
}
}
/*
* 获取content-type 和 fileType
* content-type: 不为空,则不做改变
* fileType: 不为空,则不做改变
*/
if(StringUtils.isBlank(utilsElement.getRespContentType())){
Header[] contentTypes = response.getHeaders("Content-type");
for(Header head : contentTypes){
utilsElement.setRespContentType(head.getValue());
if(StringUtils.isNotBlank(utilsElement.getRespContentType()) && StringUtils.isBlank(utilsElement.getFileType())){
utilsElement.setFileType(getFileTypeByContentType(utilsElement.getRespContentType()));
break;
}
}
}else {
if(StringUtils.isBlank(utilsElement.getFileType())){
utilsElement.setFileType(getFileTypeByContentType(utilsElement.getRespContentType()));
}
}
try {
// System.out.println(response1.getStatusLine());
HttpEntity httpEntity = response.getEntity();
long contentLength = httpEntity.getContentLength();
InputStream inputStream = httpEntity.getContent();
HttpClientDownLoadProgress progress = new HttpClientDownLoadProgress() {
@Override
public void onProgress(int progress) {
logger.info("download progress ==> [{}]",progress);
System.out.println(progress);
}
};
/*************** 生成目录(wx_web_file_temp_path + catalog + fileType) start ***************/
PropertiesUtils utils = new PropertiesUtils("global/params.properties");
// 本地根目录
String wx_web_file_temp_path = utils.getProperty("wx_web_file_temp_path");
if(StringUtils.isBlank(wx_web_file_temp_path)){
wx_web_file_temp_path = "/tmp/fileTemp/";
}
// 目录
String catalog = new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + File.separator + utilsElement.getFileType();
// 保存到本地
String localPath = saveFileToLocal(inputStream, wx_web_file_temp_path + catalog, utilsElement.getFileName(), progress, contentLength);
/*************** 生成目录(wx_web_file_temp_path + catalog + fileType) end ***************/
utilsElement.setLocalPath(localPath);
logger.info("下载文件保存的路径为 ==> {}",localPath);
// 关闭网络连接
EntityUtils.consume(httpEntity);
} finally {
response.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// return utilsElement;
}
/**
* 根据centent-type获取附件类型(自定义的类型,对应info_attachment附件表的fileType)
* @auth wangyuuanhao
* @date 2019-07-16
* @param contentType
* @return
*/
private static String getFileTypeByContentType(String contentType){
if (contentType.contains("image")) {
return "image";
}else if(contentType.contains("video")){
return "video";
}else if(contentType.contains("audio")){
return "voice";
}else {
return "file";
}
}
/**
* 将文件流保存到服务器本地
* @param is-
* @param fileCatalog: 文件所在的目录
* @param progress: 回调的目标方法所在的接口
* @param contentLength: 总长度
* @return 本地存储的路径
* @throws IOException
*/
private static String saveFileToLocal(InputStream is,String fileCatalog, String fileName, HttpClientDownLoadProgress progress,Long contentLength) throws IOException {
File file = new File(fileCatalog);
if(!file.exists()){
file.mkdirs();
}
byte[] buffer = new byte[1024];
int r = 0;
long totalRead = 0;
// 根据InputStream 下载文件
ByteArrayOutputStream output = new ByteArrayOutputStream();
while ((r = is.read(buffer)) > 0) {
output.write(buffer, 0, r);
totalRead += r;
// 回调进度
if (progress != null) {
progress.onProgress((int) (totalRead * 100 / contentLength));
}
}
String filePath = fileCatalog + File.separator + fileName;
FileOutputStream fos = new FileOutputStream(filePath);
output.writeTo(fos);
output.flush();
output.close();
fos.close();
return filePath;
}
/**
* 文件服务器上传当个文件(有时间可以看看怎么上传多个)
* @author wangyuanhao
* @date 2018年7月26日 下午5:12:18
* @editer wangyuanhao
* @editdate 2018年7月26日 下午5:12:18
* @remark
*/
public static Map<String,String> saveFileToFdfs(InputStream in,String fileName){
Map<String,String> map = null;
try{
PropertiesUtils utils = new PropertiesUtils("global/param_hexi.properties");
String dfs_url = utils.getProperty("file.lan.path");
String url = "";
String result = "";
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(dfs_url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addBinaryBody("inputfile",in, ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
StringBody type1 = new StringBody("0",ContentType.TEXT_PLAIN);
builder.addPart("type", type1);
HttpEntity entity1 = builder.build();
httpPost.setEntity(entity1);
HttpResponse response1 = httpClient.execute(httpPost);// 执行提交
HttpEntity responseEntity = response1.getEntity();
if (responseEntity != null) {
// 将响应内容转换为字符串
result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
JSONObject obj = JSONObject.fromObject(result);//把String转换为json
if(obj.containsKey(GlobalConsts.BASE_RETURN_PARAM_KEY_RESULT_CODE) && ("" + ResultEnums.TRUE_200.getCode()).equals(obj.getString(GlobalConsts.BASE_RETURN_PARAM_KEY_RESULT_CODE))){
String resultData = obj.getString(GlobalConsts.BASE_RETURN_PARAM_KEY_RESULT_DATA);
JSONArray arr = JSONArray.fromObject(resultData);
List<Map<String,String>> list = (List<Map<String, String>>) JSONArray.toCollection(arr, Map.class);
if(list.size() > 0){
return list.get(0);
}
}
}
}catch(Exception e){
e.printStackTrace();
try {
in.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
return map;
}
/**
* 设置http的HEAD
* @auth wangyuanhao
* @param httpGet
* @param headMap
*/
private static void setGetHead(HttpGet httpGet, Map<String, String> headMap) {
if (headMap != null && headMap.size() > 0) {
Set<String> keySet = headMap.keySet();
for (String key : keySet) {
httpGet.addHeader(key, headMap.get(key));
}
}
}
public static void main(String[] args) {
HttpUtilsElement elem = new HttpUtilsElement();
String url = "https://zwapp.tj.gov.cn:7020/group1/M00/00/0B/Cl4Tq10XIniEG2ZgAAAAADbv9k0699.jpg?filename=magazine-unlock-01-2.3.1390-_00eb9e6723d24953a90b09d8829e57de.jpg";
// String url = "http://60.28.163.71:5020/group1/M00/00/38/Cl4TsF0oKfqEdJrYAAAAAJqqrKI530.aac?filename=58bfafaf7c5e246796f791c95c1b30b5.aac";
elem.setUrl(url);
elem.setFileType("voice");
// httpDownloadFile(elem);
File file = new File("D:\\tmp\\fileTemp\\2019-07-16\\image\\1.jpg");
try {
InputStream in = new FileInputStream(file);
Map<String, String> map = saveFileToFdfs(in, "2.png");
System.out.println(map);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// Map<String, String> stringStringMap = saveFileToFdfs(elem.getInputStream(), elem.getFileName());
System.out.println(elem.getFileName());
System.out.println(elem.getFileType());
System.out.println(elem.getRespContentType());
a();
//
// String resJson ="[{\"path\":\"http://mfiles.weijingyuan.com.cn:80/group1/M00/00/2E/CmMxAlrNsruAP8jQAAhQ4Kh96mY631.jpg\",\"name\":\"14825153586.jpg\",\"guid\":\"6ce8e58d-8efe-416c-8813-bbb28869ac63\",\"time\":35}]";
//
// FileType fileType = new FileType();
//
// String s = fileType.fileType("14825153586.jpg");
// System.out.println(s);
}
private static void a() {
HashMap<String, String> map = new HashMap<String, String>();
map.put("inputfile","/Users/hancock/Downloads/14825153586.jpg");
String s = formUpload("http://mfiles.weijingyuan.com.cn/front/upload", null, map, "");
System.out.println(s);
}
public String postSSL(String url, String param){
try {
HttpClient client= ConsumerHttpClientConnectionManager.getHttpsCilentInstance();
HttpPost post=new HttpPost(url);
post.setHeader("Content-Type", "application/Json; charset=UTF-8");
// post.setHeader("Authorization", authorization );
StringEntity entity=new StringEntity(param, "UTF-8");
post.setEntity(entity);
HttpResponse response=client.execute(post);
if(HttpStatus.SC_OK==response.getStatusLine().getStatusCode())
{
HttpEntity res=response.getEntity();
String result= EntityUtils.toString(res);
return result;
}else{
logger.error("resultCode is {}", response.getStatusLine().getStatusCode());
}
} catch (Exception e) {
logger.error("push error {}",e);
}
return null;
}
}