Commit 7b6015f9 authored by zhangsen's avatar zhangsen

漏洞文件漏洞修改 - 流未关闭问题

parent c2a90a0a
......@@ -28,11 +28,9 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.SSLContext;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
......@@ -407,31 +405,33 @@ public class HttpContentTypeUtil {
/**
* 发送 delete请求带请求头
*/
public static String sendHttpDeleteJsonWithHeader(String httpUrl, String paramsJson, Map<String, String> headerMap) {
public static String sendHttpDeleteJsonWithHeader(String httpUrl, String paramsJson, Map<String, String> headerMap) throws IOException {
StringBuffer content = new StringBuffer();
try {
URL url = new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("DELETE");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
connection.setRequestProperty(entry.getKey(), entry.getValue());
}
PrintWriter printWriter = new PrintWriter(connection.getOutputStream());
URL url = new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("DELETE");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
connection.setRequestProperty(entry.getKey(), entry.getValue());
}
try (
PrintWriter printWriter = new PrintWriter(connection.getOutputStream());
InputStream inputStream = connection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader br = new BufferedReader(inputStreamReader);
) {
printWriter.write(paramsJson);
printWriter.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
content.append(line);
}
br.close();
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return content.toString();
}
......
......@@ -41,19 +41,13 @@ public class MyImageExtractor implements IImageExtractor {
imagePath = s1 + pre + s2;
File imageFile = new File(baseDir, imagePath);
imageFile.getParentFile().mkdirs();
InputStream in = null;
OutputStream out = null;
try {
in = new ByteArrayInputStream(imageData);
out = new FileOutputStream(imageFile);
try (
InputStream in = new ByteArrayInputStream(imageData);
OutputStream out = new FileOutputStream(imageFile);
) {
IOUtils.copy(in, out);
} finally {
if (in != null) {
IOUtils.closeQuietly(in);
}
if (out != null) {
IOUtils.closeQuietly(out);
}
} catch (IOException e) {
e.printStackTrace();
}
}
......
......@@ -67,9 +67,8 @@ public class TikaUtils {
ContentHandler handler = new ToHTMLContentHandler();
AutoDetectParser parser = new AutoDetectParser();
Metadata metadata = new Metadata();
InputStream stream = null;
try {
stream = new FileInputStream(new File(fileName));
try (InputStream stream = new FileInputStream(new File(fileName));) {
parser.parse(stream, handler, metadata);
FileHelper.writeFile(handler.toString(), outPutFile + ".html");
......@@ -78,8 +77,6 @@ public class TikaUtils {
return null;
} catch (Exception e) {
e.printStackTrace();
} finally {
}
return "";
......
......@@ -78,7 +78,10 @@ public class WordConverterUtils {
* @param readUrl html中img标签的图片存储路径
*/
private static void docToHtml(File srcFile, File targetFile, String readUrl) {
try {
try (
FileInputStream inputStream = new FileInputStream(srcFile);
HWPFDocument wordDocument = new HWPFDocument(inputStream);
) {
String imagePathStr = srcFile.getParentFile().getAbsolutePath() + imgPath;
File imagePath = new File(imagePathStr);
if (!imagePath.exists()) {
......@@ -86,13 +89,12 @@ public class WordConverterUtils {
}
String srcName = srcFile.getName();
String suffix = srcName.substring(0, srcName.lastIndexOf(".")) + "_";
HWPFDocument wordDocument = new HWPFDocument(new FileInputStream(srcFile));
org.w3c.dom.Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(document);
String uri = readUrl + imagePathStr.substring(imagePathStr.indexOf("docs"));
wordToHtmlConverter.setPicturesManager((content, pictureType, name, width, height) -> {
try {
FileOutputStream out = new FileOutputStream(imagePathStr + suffix + name);
try (FileOutputStream out = new FileOutputStream(imagePathStr + suffix + name);) {
out.write(content);
return uri + suffix + name;
} catch (Exception e) {
......@@ -124,7 +126,10 @@ public class WordConverterUtils {
* @return
*/
private static String docToHtmlString(File srcFile, String readUrl) {
try {
try (
FileInputStream inputStream = new FileInputStream(srcFile);
HWPFDocument wordDocument = new HWPFDocument(inputStream);
) {
String imagePathStr = srcFile.getParentFile().getAbsolutePath() + imgPath;
File imagePath = new File(imagePathStr);
if (!imagePath.exists()) {
......@@ -132,13 +137,12 @@ public class WordConverterUtils {
}
String srcName = srcFile.getName();
String suffix = srcName.substring(0, srcName.lastIndexOf(".")) + "_";
HWPFDocument wordDocument = new HWPFDocument(new FileInputStream(srcFile));
org.w3c.dom.Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(document);
String uri = readUrl + imagePathStr.substring(imagePathStr.indexOf("docs"));
wordToHtmlConverter.setPicturesManager((content, pictureType, name, width, height) -> {
try {
FileOutputStream out = new FileOutputStream(imagePathStr + suffix + name);
try (FileOutputStream out = new FileOutputStream(imagePathStr + suffix + name);) {
out.write(content);
return uri + suffix + name;
} catch (Exception e) {
......@@ -183,30 +187,22 @@ public class WordConverterUtils {
}
String temp = srcFile.getName();
String suffix = temp.substring(0, temp.lastIndexOf(".")) + "_";
OutputStreamWriter outputStreamWriter = null;
try {
XWPFDocument document = new XWPFDocument(new FileInputStream(srcFile));
try (
FileInputStream inputStream = new FileInputStream(srcFile);
XWPFDocument document = new XWPFDocument(inputStream);
FileOutputStream fileOutputStream = new FileOutputStream(targetFile);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "utf-8");
) {
XHTMLOptions options = XHTMLOptions.create();
options.setExtractor(new MyImageExtractor(imagePath, suffix));
String uri = readUrl + imagePathStr.substring(imagePathStr.indexOf("docs"));
System.out.println("uri :" + uri);
options.URIResolver(new MyURIResolver(uri));
outputStreamWriter = new OutputStreamWriter(new FileOutputStream(targetFile), "utf-8");
XHTMLConverter xhtmlConverter = (XHTMLConverter) XHTMLConverter.getInstance();
xhtmlConverter.convert(document, outputStreamWriter, options);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (outputStreamWriter != null) {
outputStreamWriter.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
/**
......@@ -223,9 +219,11 @@ public class WordConverterUtils {
}
String temp = srcFile.getName();
String suffix = temp.substring(0, temp.lastIndexOf(".")) + "_";
OutputStreamWriter outputStreamWriter = null;
try {
XWPFDocument document = new XWPFDocument(new FileInputStream(srcFile));
try (
FileInputStream inputStream = new FileInputStream(srcFile);
XWPFDocument document = new XWPFDocument(inputStream);
) {
XHTMLOptions options = XHTMLOptions.create();
options.setExtractor(new MyImageExtractor(imagePath, suffix));
String uri = readUrl + imagePathStr.substring(imagePathStr.indexOf("docs"));
......@@ -237,15 +235,6 @@ public class WordConverterUtils {
return stringWriter.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (outputStreamWriter != null) {
outputStreamWriter.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return null;
......
......@@ -82,8 +82,7 @@ public class WordHtml implements AbstractHtml {
private static void convertDoc2Html(InputStream is, String outPutFile)
throws TransformerException, IOException, ParserConfigurationException {
StreamResult streamResult = null;
ByteArrayOutputStream out = null;
try {
try (ByteArrayOutputStream out = new ByteArrayOutputStream();) {
String[] outPutFiles = outPutFile.split("\\\\");
outPutFiles = outPutFiles[outPutFiles.length - 1].split("/");
final String root = outPutFiles[outPutFiles.length - 1];
......@@ -106,17 +105,16 @@ public class WordHtml implements AbstractHtml {
if (pics != null) {
for (int i = 0; i < pics.size(); i++) {
Picture pic = (Picture) pics.get(i);
try {
try (FileOutputStream fileOutputStream = new FileOutputStream(outPutFile + "/" + pic.suggestFullFileName());) {
// 指定doc文档中转换后图片保存的路径
pic.writeImageContent(
new FileOutputStream(outPutFile + "/" + pic.suggestFullFileName()));
pic.writeImageContent(fileOutputStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
// #end save pictures
out = new ByteArrayOutputStream();
streamResult = new StreamResult(out);
TransformerFactory tf = TransformerFactory.newInstance();
......@@ -134,10 +132,8 @@ public class WordHtml implements AbstractHtml {
FileHelper.writeFile(content, outPutFile + ".html");
// FileHelper.parseCharset(outPutFile + ".html");
// System.out.println(new String(out.toByteArray()));
} finally {
if (null != out) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
......@@ -195,45 +191,29 @@ public class WordHtml implements AbstractHtml {
}
public static void xml2Ttml(String docPath, String xsltPath, String hrmlPath){
FileInputStream fis= null;
FileInputStream fis1= null;
try {
//创建XML的文件输入流
fis = new FileInputStream(docPath);
Source source=new StreamSource(fis);
//创建XSL文件的输入流
fis1 = new FileInputStream(xsltPath);
Source template=new StreamSource(fis1);
PrintStream stm=new PrintStream(new File(hrmlPath));
//讲转换后的结果输出到 stm 中即 F:\123.html
Result result=new StreamResult(stm);
//根据XSL文件创建准个转换对象
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
Transformer transformer=transformerFactory.newTransformer(template);
//处理xml进行交换
transformer.transform(source, result);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
} finally {
//关闭文件流
try {
if(null != fis1){
fis1.close();
}
if(null != fis){
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void xml2Ttml(String docPath, String xsltPath, String hrmlPath) {
try (
//创建XML的文件输入流
FileInputStream fis = new FileInputStream(docPath);
//创建XSL文件的输入流
FileInputStream fis1 = new FileInputStream(xsltPath);
PrintStream stm = new PrintStream(new File(hrmlPath));
) {
Source source = new StreamSource(fis);
Source template = new StreamSource(fis1);
//讲转换后的结果输出到 stm 中即 F:\123.html
Result result = new StreamResult(stm);
//根据XSL文件创建准个转换对象
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
Transformer transformer = transformerFactory.newTransformer(template);
//处理xml进行交换
transformer.transform(source, result);
} catch (IOException | TransformerException e) {
e.printStackTrace();
}
}
}
......
......@@ -89,27 +89,16 @@ public class WordTemplateUtils {
public File getWordFileItem(Map map, String title, String ftlFile) throws IOException {
configuration.setClassForTemplateLoading(this.getClass(), "/ftl");
Template freemarkerTemplate = configuration.getTemplate(ftlFile, "UTF-8");
File file = null;
// 调用工具类的createDoc方法生成Word文档
File file = createDoc(map, freemarkerTemplate);
File filepdf = new File("sellPlan.pdf");
InputStream fin = null;
OutputStream os = null;
try {
// 调用工具类的createDoc方法生成Word文档
file = createDoc(map, freemarkerTemplate);
fin = new FileInputStream(file);
os = new FileOutputStream(filepdf);
try (
InputStream fin =new FileInputStream(file) ;
OutputStream os = new FileOutputStream(filepdf);
)
{
wordTopdfByAspose(fin, os);
return filepdf;
} finally {
if (fin != null) {
fin.close();
}
if (os != null) {
os.close();
}
if (file != null) {
file.delete();
}// 删除临时文件
}
}
......
......@@ -51,17 +51,25 @@ public class IOConfig {
tmp2.put("lower-greek", 1L);
ILV1_MAP = Collections.unmodifiableMap(tmp2);
NumberingDefinitionsPart numberingDefinitionsPart = null;
try {
numberingDefinitionsPart = new NumberingDefinitionsPart();
InputStream is = IOConfig.class.getClassLoader().getResourceAsStream("office/listStyle.xml");
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuilder builder = new StringBuilder();
String str;
while ((str = reader.readLine()) != null) {
builder.append(str);
try (
InputStream is = IOConfig.class.getClassLoader().getResourceAsStream("office/listStyle.xml");
) {
assert is != null;
try (InputStreamReader inputStreamReader = new InputStreamReader(is, "UTF-8");
BufferedReader reader = new BufferedReader(inputStreamReader);
) {
numberingDefinitionsPart = new NumberingDefinitionsPart();
StringBuilder builder = new StringBuilder();
String str;
while ((str = reader.readLine()) != null) {
builder.append(str);
}
Numbering numbering = (Numbering) XmlUtils.unmarshalString(builder.toString());
numberingDefinitionsPart.setJaxbElement(numbering);
} catch (Exception e) {
e.printStackTrace();
}
Numbering numbering = (Numbering) XmlUtils.unmarshalString(builder.toString());
numberingDefinitionsPart.setJaxbElement(numbering);
} catch (Exception e) {
e.printStackTrace();
}
......
......@@ -495,6 +495,7 @@ public class DocxBuilder {
*/
private static byte[] getRemotePic2Bytes(String picUrl) {
byte[] picBytes = {};
InputStream is = null;
try {
if (picUrl.startsWith(IOConfig.PIC_ROUTER)) {
picUrl = picUrl.replaceFirst(IOConfig.PIC_ROUTER, IOConfig.PIC_URI);
......@@ -504,7 +505,7 @@ public class DocxBuilder {
// 设置请求超时为5s
con.setConnectTimeout(5 * 1000);
// 输入流
InputStream is = con.getInputStream();
is = con.getInputStream();
// 1K的数据缓冲
byte[] current = new byte[1024];
// 读取到的数据长度
......@@ -513,9 +514,16 @@ public class DocxBuilder {
picBytes = Arrays.copyOf(picBytes, picBytes.length + len);
System.arraycopy(current, 0, picBytes, picBytes.length - len, len);
}
is.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != is) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return picBytes;
}
......
......@@ -272,17 +272,14 @@ public class EquipmentManageServiceImpl extends ServiceImpl<EquipmentManageMappe
@Override
public void downLoad(FileUploadVo vo, HttpServletResponse response) {
String fileName = vo.getName() ;
ServletOutputStream out;
response.setHeader("Content-Disposition", "attachment;fileName="+fileName);
response.setHeader("Access-Control-Expose-Headers", "access_token");
response.setHeader("Access-Control-Allow-Origin", "*");
response.setContentType("multipart/form-data");
try {
InputStream inputStream = getInputStreamFromURL(vo.getUrl());
//3.通过response获取ServletOutputStream对象(out)
out = response.getOutputStream();
try (InputStream inputStream = getInputStreamFromURL(vo.getUrl());
//3.通过response获取ServletOutputStream对象(out)
ServletOutputStream out = response.getOutputStream();
) {
int b = 0;
byte[] buffer = new byte[512];
while (b != -1){
......@@ -290,10 +287,7 @@ public class EquipmentManageServiceImpl extends ServiceImpl<EquipmentManageMappe
//4.写到输出流(out)中
out.write(buffer,0,b);
}
inputStream.close();
out.close();
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
......
......@@ -41,7 +41,9 @@ public class ExcelUtil {
Class<?> model, String token, String appKey, String product, boolean flag) {
HorizontalCellStyleStrategy horizontalCellStyleStrategy = setMyCellStyle();
try {
try (
OutputStream outputStream = getOutputStream(fileName, response, ExcelTypeEnum.XLSX);
) {
//下拉列表集合
Map<Integer, String[]> explicitListConstraintMap = new HashMap<>();
if (flag) {
......@@ -54,7 +56,7 @@ public class ExcelUtil {
resolveExplicitConstraint(explicitListConstraintMap, explicitConstraint,token,appKey,product);
}
}
EasyExcel.write(getOutputStream(fileName, response, ExcelTypeEnum.XLSX), model)
EasyExcel.write(outputStream, model)
.excelType(ExcelTypeEnum.XLSX).sheet(sheetName)
.registerWriteHandler(new TemplateCellWriteHandlerDate(explicitListConstraintMap))
.registerWriteHandler(new TemplateCellWriteHandler())
......
......@@ -434,62 +434,50 @@ public class FileHelper {
}
public static void nioTransferCopy(File source, File target) {
FileChannel in = null;
FileChannel out = null;
FileInputStream inStream = null;
FileOutputStream outStream = null;
try {
inStream = new FileInputStream(source);
outStream = new FileOutputStream(target);
in = inStream.getChannel();
out = outStream.getChannel();
try (
FileInputStream inStream = new FileInputStream(source);
FileOutputStream outStream = new FileOutputStream(target);
FileChannel in = inStream.getChannel();
FileChannel out = outStream.getChannel();
) {
in.transferTo(0, in.size(), out);
} catch (IOException e) {
e.printStackTrace();
} finally {
close(inStream);
close(in);
close(outStream);
close(out);
}
}
private static boolean nioBufferCopy(File source, File target) {
FileChannel in = null;
FileChannel out = null;
FileInputStream inStream = null;
FileOutputStream outStream = null;
try {
inStream = new FileInputStream(source);
outStream = new FileOutputStream(target);
in = inStream.getChannel();
out = outStream.getChannel();
try (
FileInputStream inStream = new FileInputStream(source);
FileOutputStream outStream = new FileOutputStream(target);
FileChannel in = inStream.getChannel();
FileChannel out = outStream.getChannel();
) {
ByteBuffer buffer = ByteBuffer.allocate(4096);
while (in.read(buffer) != -1) {
buffer.flip();
out.write(buffer);
buffer.clear();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
close(inStream);
close(in);
close(outStream);
close(out);
}
return true;
}
public static void customBufferStreamCopy(File source, File target) {
InputStream fis = null;
OutputStream fos = null;
try {
fis = new FileInputStream(source);
fos = new FileOutputStream(target);
try (
InputStream fis = new FileInputStream(source);
OutputStream fos = new FileOutputStream(target);
) {
byte[] buf = new byte[4096];
int i;
while ((i = fis.read(buf)) != -1) {
......@@ -497,9 +485,6 @@ public class FileHelper {
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close(fis);
close(fos);
}
}
......
......@@ -851,35 +851,33 @@ public class CheckController extends AbstractBaseController {
}
InputStream inputStream = new ByteArrayInputStream(xml.getBytes());
Source source = new StreamSource(inputStream);
try {
String filePath = Objects.requireNonNull(this.getClass().getResource("/")).getPath() + "temp" + File.separator + "checkTemplate.xsl";
if (Files.notExists(Paths.get(filePath))) {
throw new RuntimeException("模板文件不存在");
}
FileInputStream fis1 = new FileInputStream(FilenameUtils.normalize(filePath));
String filePath = Objects.requireNonNull(this.getClass().getResource("/")).getPath() + "temp" + File.separator + "checkTemplate.xsl";
if (Files.notExists(Paths.get(filePath))) {
throw new RuntimeException("模板文件不存在");
}
Date date = new Date();
String path = request.getSession().getServletContext().getRealPath("/");
String subPath = path.substring(0, path.indexOf(File.separator) + 1);
String dir = subPath + "check";
String html = subPath + "check" + File.separator + "task_"
+ date.getTime() + ".html";
File htmlFile = new File(html);
try (
FileInputStream fis1 = new FileInputStream(FilenameUtils.normalize(filePath));
FileInputStream fis = new FileInputStream(htmlFile);
) {
Source template = new StreamSource(fis1);
Date date = new Date();
String path = request.getSession().getServletContext().getRealPath("/");
String subPath = path.substring(0, path.indexOf(File.separator) + 1);
String dir = subPath + "check";
String html = subPath + "check" + File.separator + "task_"
+ date.getTime() + ".html";
File dirFile = new File(dir);
if (!dirFile.exists()) {
dirFile.mkdirs();
}
Result result = new StreamResult(html);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
Transformer transformer = transformerFactory.newTransformer(template);
transformer.transform(source, result);
File htmlFile = new File(html);
FileInputStream fis = new FileInputStream(htmlFile);
String data = IOUtils.toString(fis, StandardCharsets.UTF_8);
fis.close();
if (htmlFile.exists()) {
htmlFile.delete();
}
......
......@@ -2108,12 +2108,13 @@ public class PlanTaskServiceImpl implements IPlanTaskService {
}
public static byte[] file2byte(File file) {
try {
FileInputStream in = new FileInputStream(file);
try (
FileInputStream in = new FileInputStream(file);
) {
//当文件没有结束时,每次读取一个字节显示
byte[] data = new byte[in.available()];
in.read(data);
in.close();
return data;
} catch (Exception e) {
e.printStackTrace();
......
......@@ -475,37 +475,26 @@ public class FileHelper {
}
public static void nioTransferCopy(File source, File target) {
FileChannel in = null;
FileChannel out = null;
FileInputStream inStream = null;
FileOutputStream outStream = null;
try {
inStream = new FileInputStream(source);
outStream = new FileOutputStream(target);
in = inStream.getChannel();
out = outStream.getChannel();
try (
FileInputStream inStream = new FileInputStream(source);
FileOutputStream outStream = new FileOutputStream(target);
FileChannel in = inStream.getChannel();
FileChannel out = outStream.getChannel();
) {
in.transferTo(0, in.size(), out);
} catch (IOException e) {
e.printStackTrace();
} finally {
close(inStream);
close(in);
close(outStream);
close(out);
}
}
private static boolean nioBufferCopy(File source, File target) {
FileChannel in = null;
FileChannel out = null;
FileInputStream inStream = null;
FileOutputStream outStream = null;
try {
inStream = new FileInputStream(source);
outStream = new FileOutputStream(target);
in = inStream.getChannel();
out = outStream.getChannel();
try (
FileInputStream inStream = new FileInputStream(source);
FileOutputStream outStream = new FileOutputStream(target);
FileChannel in = inStream.getChannel();
FileChannel out = outStream.getChannel();
) {
ByteBuffer buffer = ByteBuffer.allocate(4096);
while (in.read(buffer) != -1) {
buffer.flip();
......@@ -515,22 +504,16 @@ public class FileHelper {
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
close(inStream);
close(in);
close(outStream);
close(out);
}
return true;
}
public static void customBufferStreamCopy(File source, File target) {
InputStream fis = null;
OutputStream fos = null;
try {
fis = new FileInputStream(source);
fos = new FileOutputStream(target);
try (
InputStream fis = new FileInputStream(source);
OutputStream fos = new FileOutputStream(target);
) {
byte[] buf = new byte[4096];
int i;
while ((i = fis.read(buf)) != -1) {
......@@ -538,9 +521,6 @@ public class FileHelper {
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close(fis);
close(fos);
}
}
......
......@@ -18,11 +18,9 @@ import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
......@@ -395,31 +393,32 @@ public class HttpUtil {
/**
* 发送 delete请求带请求头
*/
public static String sendHttpDeleteJsonWithHeader(String httpUrl, String paramsJson, Map<String, String> headerMap) {
public static String sendHttpDeleteJsonWithHeader(String httpUrl, String paramsJson, Map<String, String> headerMap) throws IOException {
StringBuffer content = new StringBuffer();
try {
URL url = new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("DELETE");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
connection.setRequestProperty(entry.getKey(), entry.getValue());
}
PrintWriter printWriter = new PrintWriter(connection.getOutputStream());
URL url = new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("DELETE");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
connection.setRequestProperty(entry.getKey(), entry.getValue());
}
try (
OutputStream outputStream = connection.getOutputStream();
InputStreamReader inputStreamReader = new InputStreamReader(connection.getInputStream());
BufferedReader br = new BufferedReader(inputStreamReader);
PrintWriter printWriter = new PrintWriter(outputStream);
) {
printWriter.write(paramsJson);
printWriter.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
content.append(line);
}
br.close();
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return content.toString();
}
......
......@@ -82,8 +82,7 @@ public class WordHtml implements AbstractHtml {
private static void convertDoc2Html(InputStream is, String outPutFile)
throws TransformerException, IOException, ParserConfigurationException {
StreamResult streamResult = null;
ByteArrayOutputStream out = null;
try {
try (ByteArrayOutputStream out = new ByteArrayOutputStream();) {
String[] outPutFiles = outPutFile.split("\\\\");
outPutFiles = outPutFiles[outPutFiles.length - 1].split("/");
final String root = outPutFiles[outPutFiles.length - 1];
......@@ -105,19 +104,18 @@ public class WordHtml implements AbstractHtml {
if (pics != null) {
for (int i = 0; i < pics.size(); i++) {
Picture pic = (Picture) pics.get(i);
try {
try (
FileOutputStream fileOutputStream = new FileOutputStream(outPutFile + "/" + pic.suggestFullFileName());
) {
// 指定doc文档中转换后图片保存的路径
pic.writeImageContent(
new FileOutputStream(outPutFile + "/" + pic.suggestFullFileName()));
pic.writeImageContent(fileOutputStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
// #end save pictures
out = new ByteArrayOutputStream();
streamResult = new StreamResult(out);
TransformerFactory tf = TransformerFactory.newInstance();
tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
// 创建执行从 Source 到 Result 的复制的新 Transformer。
......@@ -133,10 +131,8 @@ public class WordHtml implements AbstractHtml {
FileHelper.writeFile(content, outPutFile + ".html");
// FileHelper.parseCharset(outPutFile + ".html");
// System.out.println(new String(out.toByteArray()));
} finally {
if (null != out) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
......@@ -195,44 +191,26 @@ public class WordHtml implements AbstractHtml {
public static void xml2Ttml(String docPath, String xsltPath, String hrmlPath){
FileInputStream fis= null;
FileInputStream fis1= null;
try {
//创建XML的文件输入流
fis = new FileInputStream(docPath);
Source source=new StreamSource(fis);
//创建XSL文件的输入流
fis1 = new FileInputStream(xsltPath);
Source template=new StreamSource(fis1);
PrintStream stm=new PrintStream(hrmlPath);
//讲转换后的结果输出到 stm 中即 F:\123.html
Result result=new StreamResult(stm);
//根据XSL文件创建准个转换对象
try (
//创建XML的文件输入流
FileInputStream fis = new FileInputStream(docPath);
//创建XSL文件的输入流
FileInputStream fis1 = new FileInputStream(xsltPath);
PrintStream stm = new PrintStream(hrmlPath);
) {
Source source = new StreamSource(fis);
Source template = new StreamSource(fis1);
//讲转换后的结果输出到 stm 中即 F:\123.html
Result result = new StreamResult(stm);
//根据XSL文件创建准个转换对象
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
Transformer transformer= transformerFactory.newTransformer(template);
//处理xml进行交换
transformer.transform(source, result);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (TransformerException e) {
} catch (TransformerException | IOException e) {
e.printStackTrace();
} finally {
//关闭文件流
try {
if(null != fis1){
fis1.close();
}
if(null != fis){
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
......
......@@ -109,27 +109,15 @@ public class WordTemplateUtils {
public File getWordFileItem(Map map, String title, String ftlFile,String type) throws IOException {
configuration.setClassForTemplateLoading(this.getClass(), "/ftl");
Template freemarkerTemplate = configuration.getTemplate(ftlFile, "UTF-8");
File file = null;
File file = createDoc(map, freemarkerTemplate);
File filepdf = new File("sellPlan.pdf");
InputStream fin = null;
OutputStream os = null;
try {
try (
InputStream fin = new FileInputStream(file);
OutputStream os = new FileOutputStream(filepdf);
) {
// 调用工具类的createDoc方法生成Word文档
file = createDoc(map, freemarkerTemplate);
fin = new FileInputStream(file);
os = new FileOutputStream(filepdf);
wordTopdfByAspose(fin, os,type);
return filepdf;
} finally {
if (fin != null) {
fin.close();
}
if (os != null) {
os.close();
}
if (file != null) {
file.delete();
}// 删除临时文件
}
}
......@@ -214,24 +202,17 @@ public class WordTemplateUtils {
if (!file.exists()) {
return "";
}
InputStream in = null;
byte[] data = null;
try {
in = new FileInputStream(file);
} catch (FileNotFoundException e1) {
try (InputStream in = new FileInputStream(file);) {
data = new byte[in.available()];
in.read(data);
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
} catch (IOException e1) {
e1.printStackTrace();
}
try {
if (null != in) {
data = new byte[in.available()];
in.read(data);
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
return null;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment