Commit a6c9b89f authored by zhangsen's avatar zhangsen

根据代码检查工具处理阻断漏洞

parent b1af2f42
...@@ -54,14 +54,11 @@ public class WordConverterUtils { ...@@ -54,14 +54,11 @@ public class WordConverterUtils {
FileItem item = factory.createItem("textField", "text/plain", true, file.getName()); FileItem item = factory.createItem("textField", "text/plain", true, file.getName());
int bytesRead = 0; int bytesRead = 0;
byte[] buffer = new byte[8192]; byte[] buffer = new byte[8192];
try { try (FileInputStream fis = new FileInputStream(file);
FileInputStream fis = new FileInputStream(file); OutputStream os = item.getOutputStream();) {
OutputStream os = item.getOutputStream();
while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) { while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead); os.write(buffer, 0, bytesRead);
} }
os.close();
fis.close();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
......
...@@ -10,33 +10,14 @@ public class ImageText implements AbstractText { ...@@ -10,33 +10,14 @@ public class ImageText implements AbstractText {
public void createTxt(String inputFile, String outputFile) throws Exception { public void createTxt(String inputFile, String outputFile) throws Exception {
File file = new File(inputFile); File file = new File(inputFile);
String baseName = FilenameUtils.getBaseName(inputFile); String baseName = FilenameUtils.getBaseName(inputFile);
InputStream is = null; try (InputStream is = new FileInputStream(file);
OutputStream os = null; OutputStream os = new FileOutputStream(outputFile.substring(0, outputFile.length() - baseName.length() - 1) + ".txt")) {
try {
is = new FileInputStream(file);
os = new FileOutputStream(
outputFile.substring(0, outputFile.length() - baseName.length() - 1) + ".txt");
byte[] buffer = new byte[1024]; byte[] buffer = new byte[1024];
int result = -1; int result = -1;
while (-1 != (result = is.read(buffer))) { while (-1 != (result = is.read(buffer))) {
os.write(buffer, 0, result); os.write(buffer, 0, result);
} }
} finally {
try {
if (null != is) {
is.close();
}
if (null != os) {
os.close();
}
} catch (Exception exce) {
System.err.println(exce.getMessage());
}
} }
} }
} }
...@@ -18,6 +18,7 @@ import java.io.*; ...@@ -18,6 +18,7 @@ import java.io.*;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.channels.Channel; import java.nio.channels.Channel;
import java.nio.channels.FileChannel; import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator; import java.util.Iterator;
import java.util.TreeSet; import java.util.TreeSet;
...@@ -39,11 +40,8 @@ public class FileHelper { ...@@ -39,11 +40,8 @@ public class FileHelper {
* @return * @return
*/ */
public static boolean isExcel2003(File file) { public static boolean isExcel2003(File file) {
InputStream is = null; try (InputStream is = new FileInputStream(file);
Workbook wb = null; Workbook wb = WorkbookFactory.create(is);) {
try {
is = new FileInputStream(file);
wb = WorkbookFactory.create(is);
if (wb instanceof XSSFWorkbook) { if (wb instanceof XSSFWorkbook) {
return false; return false;
} else if (wb instanceof HSSFWorkbook) { } else if (wb instanceof HSSFWorkbook) {
...@@ -51,17 +49,6 @@ public class FileHelper { ...@@ -51,17 +49,6 @@ public class FileHelper {
} }
} catch (Exception e) { } catch (Exception e) {
return false; return false;
} finally {
try {
if (null != is) {
is.close();
}
if (null != wb) {
wb.close();
}
} catch (IOException e) {
e.printStackTrace();
}
} }
return true; return true;
} }
...@@ -71,39 +58,19 @@ public class FileHelper { ...@@ -71,39 +58,19 @@ public class FileHelper {
* @return * @return
*/ */
public static boolean isWord2003(File file) { public static boolean isWord2003(File file) {
InputStream is = null; try (InputStream is = new FileInputStream(file);
try { HWPFDocument hwpfDocument = new HWPFDocument(is);) {
is = new FileInputStream(file);
new HWPFDocument(is);
} catch (Exception e) { } catch (Exception e) {
return false; return false;
} finally {
try {
if (null != is) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
} }
return true; return true;
} }
public static boolean isWord2007(File file) { public static boolean isWord2007(File file) {
InputStream is = null; try (InputStream is = new FileInputStream(file);
try { XWPFDocument xwpfDocument = new XWPFDocument(is)) {
is = new FileInputStream(file);
new XWPFDocument(is).close();
} catch (Exception e) { } catch (Exception e) {
return false; return false;
} finally {
try {
if (null != is) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
} }
return true; return true;
} }
...@@ -113,24 +80,10 @@ public class FileHelper { ...@@ -113,24 +80,10 @@ public class FileHelper {
* @return * @return
*/ */
public static boolean isPpt2003(File file) { public static boolean isPpt2003(File file) {
InputStream is = null; try (InputStream is = new FileInputStream(file);
HSLFSlideShow ppt = null; HSLFSlideShow ppt = new HSLFSlideShow(is)) {
try {
is = new FileInputStream(file);
ppt = new HSLFSlideShow(is);
} catch (Exception e) { } catch (Exception e) {
return false; return false;
} finally {
try {
if (null != is) {
is.close();
}
if (null != ppt) {
ppt.close();
}
} catch (IOException e) {
e.printStackTrace();
}
} }
return true; return true;
} }
...@@ -141,13 +94,10 @@ public class FileHelper { ...@@ -141,13 +94,10 @@ public class FileHelper {
*/ */
public static StringBuffer readFile(String path) { public static StringBuffer readFile(String path) {
StringBuffer buffer = new StringBuffer(); StringBuffer buffer = new StringBuffer();
InputStream is = null; File file = new File(path);
BufferedReader br = null; try (InputStream is = new FileInputStream(file);
try { BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
File file = new File(path);
if (file.exists()) { if (file.exists()) {
is = new FileInputStream(file);
br = new BufferedReader(new InputStreamReader(is));
String content = br.readLine(); String content = br.readLine();
while (null != content) { while (null != content) {
buffer.append(content); buffer.append(content);
...@@ -156,19 +106,7 @@ public class FileHelper { ...@@ -156,19 +106,7 @@ public class FileHelper {
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally {
try {
if (null != is) {
is.close();
}
if (null != br) {
br.close();
}
} catch (Exception e) {
e.printStackTrace();
}
} }
return buffer; return buffer;
} }
...@@ -181,13 +119,10 @@ public class FileHelper { ...@@ -181,13 +119,10 @@ public class FileHelper {
*/ */
public static StringBuffer readFile(String path, String split) { public static StringBuffer readFile(String path, String split) {
StringBuffer buffer = new StringBuffer(); StringBuffer buffer = new StringBuffer();
InputStream is = null; File file = new File(path);
BufferedReader br = null; try (InputStream is = new FileInputStream(file);
try { BufferedReader br = new BufferedReader(new InputStreamReader(is));) {
File file = new File(path);
if (file.exists()) { if (file.exists()) {
is = new FileInputStream(file);
br = new BufferedReader(new InputStreamReader(is));
String content = br.readLine(); String content = br.readLine();
while (null != content) { while (null != content) {
buffer.append(content).append(split); buffer.append(content).append(split);
...@@ -196,19 +131,7 @@ public class FileHelper { ...@@ -196,19 +131,7 @@ public class FileHelper {
} }
} catch (Exception exception) { } catch (Exception exception) {
exception.printStackTrace(); exception.printStackTrace();
} finally {
try {
if (null != is) {
is.close();
}
if (null != br) {
br.close();
}
} catch (Exception exception2) {
exception2.printStackTrace();
}
} }
return buffer; return buffer;
} }
...@@ -219,28 +142,15 @@ public class FileHelper { ...@@ -219,28 +142,15 @@ public class FileHelper {
* @param path 写入内容的文件路径 * @param path 写入内容的文件路径
*/ */
public static void writeFile(String content, String path) { public static void writeFile(String content, String path) {
OutputStream fos = null; File file = new File(path);
BufferedWriter bw = null; try (OutputStream fos = new FileOutputStream(file);
try { BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos, StandardCharsets.UTF_8));) {
File file = new File(path);
if (!file.getParentFile().exists()) { if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs(); file.getParentFile().mkdirs();
} }
fos = new FileOutputStream(file);
bw = new BufferedWriter(new OutputStreamWriter(fos, "UTF-8"));
bw.write(content); bw.write(content);
} catch (FileNotFoundException fnfe) { } catch (IOException fnfe) {
fnfe.printStackTrace(); fnfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (bw != null) {
bw.close();
}
} catch (IOException ioException) {
System.err.println(ioException.getMessage());
}
} }
} }
...@@ -330,11 +240,8 @@ public class FileHelper { ...@@ -330,11 +240,8 @@ public class FileHelper {
public static void rmrBlankLines(String inputFile, String outPutFile) throws IOException { public static void rmrBlankLines(String inputFile, String outPutFile) throws IOException {
File htmFile = new File(inputFile); File htmFile = new File(inputFile);
// 以GB2312读取文件 // 以GB2312读取文件
BufferedReader br = null; try (BufferedReader br = new BufferedReader(new FileReader(htmFile));
BufferedWriter bw = null; BufferedWriter bw = new BufferedWriter(new FileWriter(new File(outPutFile)));) {
try {
br = new BufferedReader(new FileReader(htmFile));
bw = new BufferedWriter(new FileWriter(new File(outPutFile)));
String result = null; String result = null;
while (null != (result = br.readLine())) { while (null != (result = br.readLine())) {
if (!"".equals(result.trim())) { if (!"".equals(result.trim())) {
...@@ -343,20 +250,7 @@ public class FileHelper { ...@@ -343,20 +250,7 @@ public class FileHelper {
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally {
try {
if (null != br) {
br.close();
}
if (null != bw) {
bw.close();
}
} catch (Exception e) {
}
} }
} }
/** /**
......
...@@ -34,18 +34,12 @@ public class TikaUtils { ...@@ -34,18 +34,12 @@ public class TikaUtils {
public static String fileToTxt(File file) { public static String fileToTxt(File file) {
Parser parser = new AutoDetectParser(); Parser parser = new AutoDetectParser();
try { try (InputStream inputStream = new FileInputStream(file);) {
InputStream inputStream = new FileInputStream(file);
DefaultHandler handler = new BodyContentHandler(); DefaultHandler handler = new BodyContentHandler();
Metadata metadata = new Metadata(); Metadata metadata = new Metadata();
ParseContext parseContext = new ParseContext(); ParseContext parseContext = new ParseContext();
parseContext.set(Parser.class, parser); parseContext.set(Parser.class, parser);
parser.parse(inputStream, handler, metadata, parseContext); parser.parse(inputStream, handler, metadata, parseContext);
/*
* for (String string : metadata.names()) {
* System.out.println(string+":"+metadata.get(string)); }
*/
inputStream.close();
return handler.toString(); return handler.toString();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
...@@ -58,21 +52,13 @@ public class TikaUtils { ...@@ -58,21 +52,13 @@ public class TikaUtils {
ContentHandler handler = new ToHTMLContentHandler(); ContentHandler handler = new ToHTMLContentHandler();
AutoDetectParser parser = new AutoDetectParser(); AutoDetectParser parser = new AutoDetectParser();
Metadata metadata = new Metadata(); Metadata metadata = new Metadata();
InputStream stream = null; try (InputStream stream = new FileInputStream(new File(fileName));) {
try {
stream = new FileInputStream(new File(fileName));
parser.parse(stream, handler, metadata); parser.parse(stream, handler, metadata);
FileHelper.writeFile(handler.toString(), outPutFile + ".html"); FileHelper.writeFile(handler.toString(), outPutFile + ".html");
FileHelper.parse(outPutFile + ".html"); FileHelper.parse(outPutFile + ".html");
return null;
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally {
} }
return null; return null;
} }
......
package com.yeejoin.precontrol.common.service.impl; package com.yeejoin.precontrol.common.service.impl;
import com.yeejoin.precontrol.common.service.PdfService; import com.yeejoin.precontrol.common.service.PdfService;
import com.yeejoin.precontrol.common.utils.ExtendedIOUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import sun.misc.BASE64Decoder; import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder; import sun.misc.BASE64Encoder;
...@@ -17,22 +16,16 @@ public class PdfServiceImpl implements PdfService { ...@@ -17,22 +16,16 @@ public class PdfServiceImpl implements PdfService {
@Override @Override
public void base64StringToPdf(String base64Content, String filePath) { public void base64StringToPdf(String base64Content, String filePath) {
BASE64Decoder decoder = new BASE64Decoder(); BASE64Decoder decoder = new BASE64Decoder();
BufferedInputStream bis = null; File file = new File(filePath);
FileOutputStream fos = null; try (ByteArrayInputStream byteInputStream = new ByteArrayInputStream(decoder.decodeBuffer(base64Content));
BufferedOutputStream bos = null; BufferedInputStream bis = new BufferedInputStream(byteInputStream);
FileOutputStream fos = new FileOutputStream(file);
try { BufferedOutputStream bos = new BufferedOutputStream(fos);
byte[] bytes = decoder.decodeBuffer(base64Content); ) {
ByteArrayInputStream byteInputStream = new ByteArrayInputStream(bytes);
bis = new BufferedInputStream(byteInputStream);
File file = new File(filePath);
File path = file.getParentFile(); File path = file.getParentFile();
if (!path.exists()) { if (!path.exists()) {
path.mkdirs(); path.mkdirs();
} }
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
byte[] buffer = new byte[1024]; byte[] buffer = new byte[1024];
int length = bis.read(buffer); int length = bis.read(buffer);
while (length != -1) { while (length != -1) {
...@@ -42,26 +35,16 @@ public class PdfServiceImpl implements PdfService { ...@@ -42,26 +35,16 @@ public class PdfServiceImpl implements PdfService {
bos.flush(); bos.flush();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally {
ExtendedIOUtils.closeQuietly(bis);
ExtendedIOUtils.closeQuietly(fos);
ExtendedIOUtils.closeQuietly(bos);
} }
} }
@Override @Override
public String pdfToBase64(File file) { public String pdfToBase64(File file) {
BASE64Encoder encoder = new BASE64Encoder(); BASE64Encoder encoder = new BASE64Encoder();
FileInputStream fin = null; try (FileInputStream fin = new FileInputStream(file);
BufferedInputStream bin = null; BufferedInputStream bin = new BufferedInputStream(fin);
ByteArrayOutputStream baos = null; ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedOutputStream bout = null; BufferedOutputStream bout = new BufferedOutputStream(baos);) {
try {
fin = new FileInputStream(file);
bin = new BufferedInputStream(fin);
baos = new ByteArrayOutputStream();
bout = new BufferedOutputStream(baos);
byte[] buffer = new byte[1024]; byte[] buffer = new byte[1024];
int len = bin.read(buffer); int len = bin.read(buffer);
while (len != -1) { while (len != -1) {
...@@ -72,18 +55,8 @@ public class PdfServiceImpl implements PdfService { ...@@ -72,18 +55,8 @@ public class PdfServiceImpl implements PdfService {
bout.flush(); bout.flush();
byte[] bytes = baos.toByteArray(); byte[] bytes = baos.toByteArray();
return encoder.encodeBuffer(bytes).trim(); return encoder.encodeBuffer(bytes).trim();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} finally {
try {
fin.close();
bin.close();
bout.close();
} catch (IOException e) {
e.printStackTrace();
}
} }
return null; return null;
} }
......
...@@ -20,6 +20,7 @@ import java.util.Optional; ...@@ -20,6 +20,7 @@ import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
...@@ -837,9 +838,8 @@ public class ProjectServiceImpl extends ServiceImpl<ProjectMapper, Project> impl ...@@ -837,9 +838,8 @@ public class ProjectServiceImpl extends ServiceImpl<ProjectMapper, Project> impl
public static List<String> getContent(String filePath) { public static List<String> getContent(String filePath) {
// 读取文件 // 读取文件
List<String> lineLists = null; List<String> lineLists = null;
try { try (Stream<String> lines = Files.lines(Paths.get(filePath), Charset.defaultCharset());) {
lineLists = Files.lines(Paths.get(filePath), Charset.defaultCharset()) lineLists = lines.flatMap(line -> Arrays.stream(line.split("\n"))).collect(Collectors.toList());
.flatMap(line -> Arrays.stream(line.split("\n"))).collect(Collectors.toList());
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
......
...@@ -32,6 +32,7 @@ import java.net.URLEncoder; ...@@ -32,6 +32,7 @@ import java.net.URLEncoder;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.channels.Channel; import java.nio.channels.Channel;
import java.nio.channels.FileChannel; import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.util.*; import java.util.*;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream; import java.util.zip.ZipOutputStream;
...@@ -52,11 +53,8 @@ public class FileHelper { ...@@ -52,11 +53,8 @@ public class FileHelper {
* @return * @return
*/ */
public static boolean isExcel2003(File file) { public static boolean isExcel2003(File file) {
InputStream is = null; try (InputStream is = new FileInputStream(file);
Workbook wb = null; Workbook wb = WorkbookFactory.create(is);) {
try {
is = new FileInputStream(file);
wb = WorkbookFactory.create(is);
if (wb instanceof XSSFWorkbook) { if (wb instanceof XSSFWorkbook) {
return false; return false;
} else if (wb instanceof HSSFWorkbook) { } else if (wb instanceof HSSFWorkbook) {
...@@ -64,17 +62,6 @@ public class FileHelper { ...@@ -64,17 +62,6 @@ public class FileHelper {
} }
} catch (Exception e) { } catch (Exception e) {
return false; return false;
} finally {
try {
if (null != is) {
is.close();
}
if (null != wb) {
wb.close();
}
} catch (IOException e) {
e.printStackTrace();
}
} }
return true; return true;
} }
...@@ -84,20 +71,10 @@ public class FileHelper { ...@@ -84,20 +71,10 @@ public class FileHelper {
* @return * @return
*/ */
public static boolean isWord2003(File file) { public static boolean isWord2003(File file) {
InputStream is = null; try (InputStream is = new FileInputStream(file);
try { HWPFDocument hwpfDocument = new HWPFDocument(is);) {
is = new FileInputStream(file);
new HWPFDocument(is);
} catch (Exception e) { } catch (Exception e) {
return false; return false;
} finally {
try {
if (null != is) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
} }
return true; return true;
} }
...@@ -126,24 +103,10 @@ public class FileHelper { ...@@ -126,24 +103,10 @@ public class FileHelper {
* @return * @return
*/ */
public static boolean isPPT2003(File file) { public static boolean isPPT2003(File file) {
InputStream is = null; try (InputStream is = new FileInputStream(file);
HSLFSlideShow ppt = null; HSLFSlideShow ppt = new HSLFSlideShow(is);) {
try {
is = new FileInputStream(file);
ppt = new HSLFSlideShow(is);
} catch (Exception e) { } catch (Exception e) {
return false; return false;
} finally {
try {
if (null != is) {
is.close();
}
if (null != ppt) {
ppt.close();
}
} catch (IOException e) {
e.printStackTrace();
}
} }
return true; return true;
} }
...@@ -154,13 +117,10 @@ public class FileHelper { ...@@ -154,13 +117,10 @@ public class FileHelper {
*/ */
public static StringBuffer readLocalFile(String path) { public static StringBuffer readLocalFile(String path) {
StringBuffer buffer = new StringBuffer(); StringBuffer buffer = new StringBuffer();
InputStream is = null; File file = new File(path);
BufferedReader br = null; try (InputStream is = new FileInputStream(file);
try { BufferedReader br = new BufferedReader(new InputStreamReader(is)); ) {
File file = new File(path);
if (file.exists()) { if (file.exists()) {
is = new FileInputStream(file);
br = new BufferedReader(new InputStreamReader(is));
String content = br.readLine(); String content = br.readLine();
while (null != content) { while (null != content) {
buffer.append(content); buffer.append(content);
...@@ -169,17 +129,6 @@ public class FileHelper { ...@@ -169,17 +129,6 @@ public class FileHelper {
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally {
try {
if (null != is) {
is.close();
}
if (null != br) {
br.close();
}
} catch (Exception e) {
e.printStackTrace();
}
} }
return buffer; return buffer;
} }
...@@ -193,13 +142,10 @@ public class FileHelper { ...@@ -193,13 +142,10 @@ public class FileHelper {
*/ */
public static StringBuffer readFile(String path, String split) { public static StringBuffer readFile(String path, String split) {
StringBuffer buffer = new StringBuffer(); StringBuffer buffer = new StringBuffer();
InputStream is = null; File file = new File(path);
BufferedReader br = null; try (InputStream is = new FileInputStream(file);
try { BufferedReader br = new BufferedReader(new InputStreamReader(is));) {
File file = new File(path);
if (file.exists()) { if (file.exists()) {
is = new FileInputStream(file);
br = new BufferedReader(new InputStreamReader(is));
String content = br.readLine(); String content = br.readLine();
while (null != content) { while (null != content) {
buffer.append(content).append(split); buffer.append(content).append(split);
...@@ -208,17 +154,6 @@ public class FileHelper { ...@@ -208,17 +154,6 @@ public class FileHelper {
} }
} catch (Exception exception) { } catch (Exception exception) {
exception.printStackTrace(); exception.printStackTrace();
} finally {
try {
if (null != is) {
is.close();
}
if (null != br) {
br.close();
}
} catch (Exception exception2) {
exception2.printStackTrace();
}
} }
return buffer; return buffer;
} }
...@@ -230,28 +165,17 @@ public class FileHelper { ...@@ -230,28 +165,17 @@ public class FileHelper {
* @param path 写入内容的文件路径 * @param path 写入内容的文件路径
*/ */
public static void writeFile(String content, String path) { public static void writeFile(String content, String path) {
OutputStream fos = null; File file = new File(path);
BufferedWriter bw = null; try (OutputStream fos = new FileOutputStream(file);
try { BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos, StandardCharsets.UTF_8)); ) {
File file = new File(path);
if (!file.getParentFile().exists()) { if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs(); file.getParentFile().mkdirs();
} }
fos = new FileOutputStream(file);
bw = new BufferedWriter(new OutputStreamWriter(fos, "UTF-8"));
bw.write(content); bw.write(content);
} catch (FileNotFoundException fnfe) { } catch (FileNotFoundException fnfe) {
fnfe.printStackTrace(); fnfe.printStackTrace();
} catch (IOException ioe) { } catch (IOException ioe) {
ioe.printStackTrace(); ioe.printStackTrace();
} finally {
try {
if (bw != null) {
bw.close();
}
} catch (IOException ioException) {
System.err.println(ioException.getMessage());
}
} }
} }
...@@ -335,11 +259,8 @@ public class FileHelper { ...@@ -335,11 +259,8 @@ public class FileHelper {
public static void rmrBlankLines(String inputFile, String outPutFile) throws IOException { public static void rmrBlankLines(String inputFile, String outPutFile) throws IOException {
File htmFile = new File(inputFile); File htmFile = new File(inputFile);
// 以GB2312读取文件 // 以GB2312读取文件
BufferedReader br = null; try (BufferedReader br = new BufferedReader(new FileReader(htmFile));
BufferedWriter bw = null; BufferedWriter bw = new BufferedWriter(new FileWriter(new File(outPutFile)));) {
try {
br = new BufferedReader(new FileReader(htmFile));
bw = new BufferedWriter(new FileWriter(new File(outPutFile)));
String result = null; String result = null;
while (null != (result = br.readLine())) { while (null != (result = br.readLine())) {
if (!"".equals(result.trim())) { if (!"".equals(result.trim())) {
...@@ -348,16 +269,6 @@ public class FileHelper { ...@@ -348,16 +269,6 @@ public class FileHelper {
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally {
try {
if (null != br) {
br.close();
}
if (null != bw) {
bw.close();
}
} catch (Exception e) {
}
} }
} }
...@@ -1095,13 +1006,10 @@ public class FileHelper { ...@@ -1095,13 +1006,10 @@ public class FileHelper {
*/ */
public static StringBuffer readFile(String path) { public static StringBuffer readFile(String path) {
StringBuffer buffer = new StringBuffer(); StringBuffer buffer = new StringBuffer();
InputStream is = null; File file = new File(path);
BufferedReader br = null; try (InputStream is = new FileInputStream(file);
try { BufferedReader br = new BufferedReader(new InputStreamReader(is));) {
File file = new File(path);
if (file.exists()) { if (file.exists()) {
is = new FileInputStream(file);
br = new BufferedReader(new InputStreamReader(is));
String content = br.readLine(); String content = br.readLine();
while (null != content) { while (null != content) {
buffer.append(content); buffer.append(content);
...@@ -1110,19 +1018,7 @@ public class FileHelper { ...@@ -1110,19 +1018,7 @@ public class FileHelper {
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally {
try {
if (null != is) {
is.close();
}
if (null != br) {
br.close();
}
} catch (Exception e) {
e.printStackTrace();
}
} }
return buffer; return buffer;
} }
} }
...@@ -26,14 +26,16 @@ public class FileUtil { ...@@ -26,14 +26,16 @@ public class FileUtil {
* @return * @return
*/ */
public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception { public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
File targetFile = new File(filePath); try (FileOutputStream out = new FileOutputStream(filePath + fileName);) {
if (!targetFile.exists()) { File targetFile = new File(filePath);
targetFile.mkdirs(); if (!targetFile.exists()) {
targetFile.mkdirs();
}
out.write(file);
out.flush();
} catch (IOException e) {
e.printStackTrace();
} }
FileOutputStream out = new FileOutputStream(filePath + fileName);
out.write(file);
out.flush();
out.close();
} }
/** /**
......
...@@ -25,29 +25,21 @@ public class HttpRequest { ...@@ -25,29 +25,21 @@ public class HttpRequest {
conn.setConnectTimeout(30 * 1000); conn.setConnectTimeout(30 * 1000);
//防止屏蔽程序抓取而返回403错误 //防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//得到输入流
InputStream inputStream = conn.getInputStream();
//获取自己数组
byte[] getData = readInputStream(inputStream);
//文件保存位置 //文件保存位置
File saveDir = new File(savePath); File saveDir = new File(savePath);
if (!saveDir.exists()) { if (!saveDir.exists()) {
saveDir.mkdir(); saveDir.mkdir();
} }
File file = new File(saveDir + File.separator + fileName); File file = new File(saveDir + File.separator + fileName);
FileOutputStream fos = new FileOutputStream(file); try (FileOutputStream fos = new FileOutputStream(file);
fos.write(getData); //得到输入流
if (fos != null) { InputStream inputStream = conn.getInputStream();) {
fos.close(); //获取自己数组
} byte[] getData = readInputStream(inputStream);
if (inputStream != null) { fos.write(getData);
inputStream.close(); } catch (IOException e) {
e.printStackTrace();
} }
System.out.println("info:" + url + " download success");
return file; return file;
} }
......
...@@ -164,43 +164,42 @@ public class HttpUtils { ...@@ -164,43 +164,42 @@ public class HttpUtils {
NoSuchAlgorithmException, KeyStoreException, KeyManagementException { NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
Assert.hasText(url, "url invalid"); Assert.hasText(url, "url invalid");
String result; String result;
CloseableHttpClient httpClient; // 创建一个SSL信任所有证书的httpClient对象
if (url.startsWith(HTTPS)) { try ( CloseableHttpClient httpClient = url.startsWith(HTTPS) ? HttpUtils.createSslInsecureClient() : HttpClients.createDefault();) {
// 创建一个SSL信任所有证书的httpClient对象 CloseableHttpResponse response = null;
httpClient = HttpUtils.createSslInsecureClient(); HttpPost httpPost = getHttpPost(url);
} else { if (GlobalCache.header != null) {
httpClient = HttpClients.createDefault(); for (String key : GlobalCache.header.keySet()) {
} String value = GlobalCache.header.get(key);
CloseableHttpResponse response = null; httpPost.setHeader(key, value);
HttpPost httpPost = getHttpPost(url); }
if (GlobalCache.header != null) {
for (String key : GlobalCache.header.keySet()) {
String value = GlobalCache.header.get(key);
httpPost.setHeader(key, value);
} }
} //加入全局请求令牌权限
//加入全局请求令牌权限 httpPost.setHeader("Http-Authorization", GlobalCache.paramMap.get("token"));
httpPost.setHeader("Http-Authorization", GlobalCache.paramMap.get("token")); if (GlobalCache.header.get("Content-Type") != null) {
if (GlobalCache.header.get("Content-Type") != null) { String contentType = GlobalCache.header.get("Content-Type");
String contentType = GlobalCache.header.get("Content-Type"); if ("application/x-www-form-urlencoded".equals(contentType)) {
if ("application/x-www-form-urlencoded".equals(contentType)) { JSONObject jsonObject = JSONObject.parseObject(jsonParams);
JSONObject jsonObject = JSONObject.parseObject(jsonParams); List<NameValuePair> params = new ArrayList<>();
List<NameValuePair> params = new ArrayList<>(); //循环json key value 仅能解决正常对象 若Json对象中嵌套数组 则可能需要单独处理
//循环json key value 仅能解决正常对象 若Json对象中嵌套数组 则可能需要单独处理 if (jsonObject != null) {
if (jsonObject != null) { for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
for (Map.Entry<String, Object> entry : jsonObject.entrySet()) { params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString())); }
httpPost.setEntity(new UrlEncodedFormEntity(params, DEFAULT_ENCODING));
} }
httpPost.setEntity(new UrlEncodedFormEntity(params, DEFAULT_ENCODING));
} }
} if ("application/json;charset=UTF-8".equals(contentType)) {
if ("application/json;charset=UTF-8".equals(contentType)) { httpPost.setEntity(new StringEntity(jsonParams, ContentType.create("application/json", DEFAULT_ENCODING)));
}
} else {
httpPost.setEntity(new StringEntity(jsonParams, ContentType.create("application/json", DEFAULT_ENCODING))); httpPost.setEntity(new StringEntity(jsonParams, ContentType.create("application/json", DEFAULT_ENCODING)));
} }
} else { return baseRequest(httpClient, httpPost);
httpPost.setEntity(new StringEntity(jsonParams, ContentType.create("application/json", DEFAULT_ENCODING))); } catch (IOException e) {
e.printStackTrace();
} }
return baseRequest(httpClient, httpPost); return new ResponeVo();
} }
/** /**
...@@ -239,44 +238,43 @@ public class HttpUtils { ...@@ -239,44 +238,43 @@ public class HttpUtils {
public static ResponeVo put(String url, String jsonParams) throws IOException, NoSuchAlgorithmException, public static ResponeVo put(String url, String jsonParams) throws IOException, NoSuchAlgorithmException,
KeyStoreException, KeyManagementException { KeyStoreException, KeyManagementException {
log.info("----->调用请求 url:" + url + " ---->json参数:" + jsonParams); log.info("----->调用请求 url:" + url + " ---->json参数:" + jsonParams);
CloseableHttpClient httpClient = null;
String content; String content;
if (url.startsWith(HTTPS)) { // 创建一个SSL信任所有证书的httpClient对象
// 创建一个SSL信任所有证书的httpClient对象 try ( CloseableHttpClient httpClient = url.startsWith(HTTPS) ? HttpUtils.createSslInsecureClient() : HttpClients.createDefault();) {
httpClient = HttpUtils.createSslInsecureClient(); CloseableHttpResponse response = null;
} else { HttpPut httpPut = new HttpPut(url);
httpClient = HttpClients.createDefault(); if (GlobalCache.header != null) {
} for (String key : GlobalCache.header.keySet()) {
CloseableHttpResponse response = null; String value = GlobalCache.header.get(key);
HttpPut httpPut = new HttpPut(url); httpPut.setHeader(key, value);
if (GlobalCache.header != null) { }
for (String key : GlobalCache.header.keySet()) {
String value = GlobalCache.header.get(key);
httpPut.setHeader(key, value);
} }
} //加入全局请求令牌权限
//加入全局请求令牌权限 httpPut.setHeader("Http-Authorization", GlobalCache.paramMap.get("token"));
httpPut.setHeader("Http-Authorization", GlobalCache.paramMap.get("token")); if (GlobalCache.header.get("Content-Type") != null) {
if (GlobalCache.header.get("Content-Type") != null) { String contentType = GlobalCache.header.get("Content-Type");
String contentType = GlobalCache.header.get("Content-Type"); if ("application/x-www-form-urlencoded".equals(contentType)) {
if ("application/x-www-form-urlencoded".equals(contentType)) { JSONObject jsonObject = JSONObject.parseObject(jsonParams);
JSONObject jsonObject = JSONObject.parseObject(jsonParams); List<NameValuePair> params = new ArrayList<>();
List<NameValuePair> params = new ArrayList<>(); //循环json key value 仅能解决正常对象 若Json对象中嵌套数组 则可能需要单独处理
//循环json key value 仅能解决正常对象 若Json对象中嵌套数组 则可能需要单独处理 if (jsonObject != null) {
if (jsonObject != null) { for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
for (Map.Entry<String, Object> entry : jsonObject.entrySet()) { params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString())); }
httpPut.setEntity(new UrlEncodedFormEntity(params, DEFAULT_ENCODING));
} }
httpPut.setEntity(new UrlEncodedFormEntity(params, DEFAULT_ENCODING));
} }
if ("application/json;charset=UTF-8".equals(contentType)) {
httpPut.setEntity(new StringEntity(jsonParams, ContentType.create("application/json", DEFAULT_ENCODING)));
}
} else {
log.error("请求头为空");
} }
if ("application/json;charset=UTF-8".equals(contentType)) { return baseRequest(httpClient, httpPut);
httpPut.setEntity(new StringEntity(jsonParams, ContentType.create("application/json", DEFAULT_ENCODING))); } catch (IOException e) {
} e.printStackTrace();
} else {
log.error("请求头为空");
} }
return baseRequest(httpClient, httpPut); return new ResponeVo();
} }
/** /**
...@@ -434,16 +432,12 @@ public class HttpUtils { ...@@ -434,16 +432,12 @@ public class HttpUtils {
} }
public static void inputStreamToFile(InputStream ins, File file) { public static void inputStreamToFile(InputStream ins, File file) {
OutputStream os = null; try (OutputStream os = new FileOutputStream(file);) {
try {
os = new FileOutputStream(file);
int bytesRead = 0; int bytesRead = 0;
byte[] buffer = new byte[8192]; byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) { while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead); os.write(buffer, 0, bytesRead);
} }
os.close();
ins.close();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
......
...@@ -33,18 +33,12 @@ public class TikaUtils { ...@@ -33,18 +33,12 @@ public class TikaUtils {
public static String fileToTxt(File file) { public static String fileToTxt(File file) {
Parser parser = new AutoDetectParser(); Parser parser = new AutoDetectParser();
try { try (InputStream inputStream = new FileInputStream(file);) {
InputStream inputStream = new FileInputStream(file);
DefaultHandler handler = new BodyContentHandler(); DefaultHandler handler = new BodyContentHandler();
Metadata metadata = new Metadata(); Metadata metadata = new Metadata();
ParseContext parseContext = new ParseContext(); ParseContext parseContext = new ParseContext();
parseContext.set(Parser.class, parser); parseContext.set(Parser.class, parser);
parser.parse(inputStream, handler, metadata, parseContext); parser.parse(inputStream, handler, metadata, parseContext);
/*
* for (String string : metadata.names()) {
* System.out.println(string+":"+metadata.get(string)); }
*/
inputStream.close();
return handler.toString(); return handler.toString();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
...@@ -57,16 +51,12 @@ public class TikaUtils { ...@@ -57,16 +51,12 @@ public class TikaUtils {
ContentHandler handler = new ToHTMLContentHandler(); ContentHandler handler = new ToHTMLContentHandler();
AutoDetectParser parser = new AutoDetectParser(); AutoDetectParser parser = new AutoDetectParser();
Metadata metadata = new Metadata(); Metadata metadata = new Metadata();
InputStream stream = null; try (InputStream stream = new FileInputStream(new File(fileName))) {
try {
stream = new FileInputStream(new File(fileName));
parser.parse(stream, handler, metadata); parser.parse(stream, handler, metadata);
FileHelper.writeFile(handler.toString(), outPutFile + ".html"); FileHelper.writeFile(handler.toString(), outPutFile + ".html");
FileHelper.parse(outPutFile + ".html"); FileHelper.parse(outPutFile + ".html");
return null;
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally {
} }
return null; return null;
} }
......
...@@ -71,6 +71,7 @@ import javax.servlet.http.HttpServletRequest; ...@@ -71,6 +71,7 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.*; import java.util.*;
import java.util.stream.Collectors; import java.util.stream.Collectors;
...@@ -1132,21 +1133,18 @@ public class CommandController extends BaseController { ...@@ -1132,21 +1133,18 @@ public class CommandController extends BaseController {
} }
File htmlFile = new File(htmlFileName); File htmlFile = new File(htmlFileName);
WordConverterUtils.wordToHtml(fileName, htmlFileName, imagePathStr, readUrl, remoteSecurityService, product, appKey, token); WordConverterUtils.wordToHtml(fileName, htmlFileName, imagePathStr, readUrl, remoteSecurityService, product, appKey, token);
FileInputStream fis = new FileInputStream(htmlFile); try (FileInputStream fis = new FileInputStream(htmlFile);
// response.setContentType("multipart/form-data"); ServletOutputStream out = response.getOutputStream();) {
// response.setCharacterEncoding("UTF-8"); int b = 0;
// response.setContentType("text/html"); byte[] buffer = new byte[1024];
ServletOutputStream out; while ((b = fis.read(buffer)) != -1) {
out = response.getOutputStream(); // 4.写到输出流(out)中
int b = 0; out.write(buffer, 0, b);
byte[] buffer = new byte[1024]; }
while ((b = fis.read(buffer)) != -1) { out.flush();
// 4.写到输出流(out)中 } catch (IOException e) {
out.write(buffer, 0, b); e.printStackTrace();
} }
fis.close();
out.flush();
out.close();
return ResponseHelper.buildResponse(""); return ResponseHelper.buildResponse("");
} else { } else {
return null; return null;
......
...@@ -7,10 +7,12 @@ import java.io.FileOutputStream; ...@@ -7,10 +7,12 @@ import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStreamWriter; import java.io.OutputStreamWriter;
import java.io.Writer; import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
...@@ -150,9 +152,9 @@ public class FileController extends AbstractBaseController { ...@@ -150,9 +152,9 @@ public class FileController extends AbstractBaseController {
@TycloudOperation(ApiLevel = UserType.AGENCY) @TycloudOperation(ApiLevel = UserType.AGENCY)
@RequestMapping(value = "/download/**", method = RequestMethod.GET) @RequestMapping(value = "/download/**", method = RequestMethod.GET)
public void download(HttpServletResponse response, HttpServletRequest request) throws Exception { public void download(HttpServletResponse response, HttpServletRequest request) throws Exception {
try { try (FileInputStream inputStream = new FileInputStream(fileUploadDir + request.getServletPath().substring(15));
String path = request.getServletPath().substring(15); ServletOutputStream outputStream = response.getOutputStream();) {
IOUtils.copy(new FileInputStream(fileUploadDir + path), response.getOutputStream()); IOUtils.copy(inputStream, outputStream);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
ResponseUtils.renderText(response, "File not exists!"); ResponseUtils.renderText(response, "File not exists!");
...@@ -253,12 +255,9 @@ public class FileController extends AbstractBaseController { ...@@ -253,12 +255,9 @@ public class FileController extends AbstractBaseController {
} }
String htmlContent = (String) processData.get("html"); String htmlContent = (String) processData.get("html");
try { try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFileName), StandardCharsets.UTF_8));) {
Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFileName), "UTF-8"));
writer.write(htmlContent); writer.write(htmlContent);
writer.flush(); writer.flush();
writer.close();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
......
...@@ -51,8 +51,6 @@ public class PlanVisual3dController extends AbstractBaseController { ...@@ -51,8 +51,6 @@ public class PlanVisual3dController extends AbstractBaseController {
@Autowired @Autowired
HttpServletResponse response; HttpServletResponse response;
@Autowired
HttpServletRequest request;
@TycloudOperation(ApiLevel = UserType.AGENCY) @TycloudOperation(ApiLevel = UserType.AGENCY)
@ApiOperation(value = "预案应用树", notes = "预案应用树") @ApiOperation(value = "预案应用树", notes = "预案应用树")
...@@ -76,7 +74,7 @@ public class PlanVisual3dController extends AbstractBaseController { ...@@ -76,7 +74,7 @@ public class PlanVisual3dController extends AbstractBaseController {
if (testPlan != null) { if (testPlan != null) {
String path = testPlan.getFilePath(); String path = testPlan.getFilePath();
if (path != null && !"".equals(path)) { if (path != null && !"".equals(path)) {
try { try (InputStream fis = new BufferedInputStream(new FileInputStream(fileUploadDir + path));) {
// path是指欲下载的文件的路径。 // path是指欲下载的文件的路径。
File file = new File(fileUploadDir + path); File file = new File(fileUploadDir + path);
if (file.exists()) { if (file.exists()) {
...@@ -84,12 +82,9 @@ public class PlanVisual3dController extends AbstractBaseController { ...@@ -84,12 +82,9 @@ public class PlanVisual3dController extends AbstractBaseController {
String filename = file.getName(); String filename = file.getName();
// 取得文件的后缀名。 // 取得文件的后缀名。
String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase(); String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
// 以流的形式下载文件。 // 以流的形式下载文件。
InputStream fis = new BufferedInputStream(new FileInputStream(fileUploadDir + path));
byte[] buffer = new byte[fis.available()]; byte[] buffer = new byte[fis.available()];
fis.read(buffer); fis.read(buffer);
fis.close();
// 清空response // 清空response
// response.reset(); // response.reset();
// 设置response的Header // 设置response的Header
......
...@@ -83,11 +83,8 @@ public class FileHelper { ...@@ -83,11 +83,8 @@ public class FileHelper {
* @return * @return
*/ */
public static boolean isExcel2003(File file) { public static boolean isExcel2003(File file) {
InputStream is = null; try (InputStream is = new FileInputStream(file);
Workbook wb = null; Workbook wb = WorkbookFactory.create(is);) {
try {
is = new FileInputStream(file);
wb = WorkbookFactory.create(is);
if (wb instanceof XSSFWorkbook) { if (wb instanceof XSSFWorkbook) {
return false; return false;
} else if (wb instanceof HSSFWorkbook) { } else if (wb instanceof HSSFWorkbook) {
...@@ -95,17 +92,6 @@ public class FileHelper { ...@@ -95,17 +92,6 @@ public class FileHelper {
} }
} catch (Exception e) { } catch (Exception e) {
return false; return false;
} finally {
try {
if (null != is) {
is.close();
}
if (null != wb) {
wb.close();
}
} catch (IOException e) {
e.printStackTrace();
}
} }
return true; return true;
} }
...@@ -187,13 +173,10 @@ public class FileHelper { ...@@ -187,13 +173,10 @@ public class FileHelper {
*/ */
public static StringBuffer readFile(String path) { public static StringBuffer readFile(String path) {
StringBuffer buffer = new StringBuffer(); StringBuffer buffer = new StringBuffer();
InputStream is = null; File file = new File(path);
BufferedReader br = null; try (InputStream is = new FileInputStream(file);
try { BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
File file = new File(path);
if (file.exists()) { if (file.exists()) {
is = new FileInputStream(file);
br = new BufferedReader(new InputStreamReader(is));
String content = br.readLine(); String content = br.readLine();
while (null != content) { while (null != content) {
buffer.append(content); buffer.append(content);
...@@ -202,19 +185,7 @@ public class FileHelper { ...@@ -202,19 +185,7 @@ public class FileHelper {
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally {
try {
if (null != is) {
is.close();
}
if (null != br) {
br.close();
}
} catch (Exception e) {
e.printStackTrace();
}
} }
return buffer; return buffer;
} }
...@@ -227,13 +198,10 @@ public class FileHelper { ...@@ -227,13 +198,10 @@ public class FileHelper {
*/ */
public static StringBuffer readFile(String path, String split) { public static StringBuffer readFile(String path, String split) {
StringBuffer buffer = new StringBuffer(); StringBuffer buffer = new StringBuffer();
InputStream is = null; File file = new File(path);
BufferedReader br = null; try (InputStream is = new FileInputStream(file);
try { BufferedReader br = new BufferedReader(new InputStreamReader(is));) {
File file = new File(path);
if (file.exists()) { if (file.exists()) {
is = new FileInputStream(file);
br = new BufferedReader(new InputStreamReader(is));
String content = br.readLine(); String content = br.readLine();
while (null != content) { while (null != content) {
buffer.append(content).append(split); buffer.append(content).append(split);
...@@ -242,19 +210,7 @@ public class FileHelper { ...@@ -242,19 +210,7 @@ public class FileHelper {
} }
} catch (Exception exception) { } catch (Exception exception) {
exception.printStackTrace(); exception.printStackTrace();
} finally {
try {
if (null != is) {
is.close();
}
if (null != br) {
br.close();
}
} catch (Exception exception2) {
exception2.printStackTrace();
}
} }
return buffer; return buffer;
} }
...@@ -265,28 +221,15 @@ public class FileHelper { ...@@ -265,28 +221,15 @@ public class FileHelper {
* @param path 写入内容的文件路径 * @param path 写入内容的文件路径
*/ */
public static void writeFile(String content, String path) { public static void writeFile(String content, String path) {
OutputStream fos = null; File file = new File(path);
BufferedWriter bw = null; try (OutputStream fos = new FileOutputStream(file);
try { BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos, StandardCharsets.UTF_8));) {
File file = new File(path);
if (!file.getParentFile().exists()) { if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs(); file.getParentFile().mkdirs();
} }
fos = new FileOutputStream(file);
bw = new BufferedWriter(new OutputStreamWriter(fos, "UTF-8"));
bw.write(content); bw.write(content);
} catch (FileNotFoundException fnfe) { } catch (IOException fnfe) {
fnfe.printStackTrace(); fnfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (bw != null) {
bw.close();
}
} catch (IOException ioException) {
System.err.println(ioException.getMessage());
}
} }
} }
...@@ -375,11 +318,8 @@ public class FileHelper { ...@@ -375,11 +318,8 @@ public class FileHelper {
public static void rmrBlankLines(String inputFile, String outPutFile) throws IOException { public static void rmrBlankLines(String inputFile, String outPutFile) throws IOException {
File htmFile = new File(inputFile); File htmFile = new File(inputFile);
// 以GB2312读取文件 // 以GB2312读取文件
BufferedReader br = null; try (BufferedReader br = new BufferedReader(new FileReader(htmFile));
BufferedWriter bw = null; BufferedWriter bw = new BufferedWriter(new FileWriter(new File(outPutFile)));) {
try {
br = new BufferedReader(new FileReader(htmFile));
bw = new BufferedWriter(new FileWriter(new File(outPutFile)));
String result = null; String result = null;
while (null != (result = br.readLine())) { while (null != (result = br.readLine())) {
if (!"".equals(result.trim())) { if (!"".equals(result.trim())) {
...@@ -388,20 +328,7 @@ public class FileHelper { ...@@ -388,20 +328,7 @@ public class FileHelper {
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally {
try {
if (null != br) {
br.close();
}
if (null != bw) {
bw.close();
}
} catch (Exception e) {
}
} }
} }
/** /**
...@@ -1192,34 +1119,25 @@ public class FileHelper { ...@@ -1192,34 +1119,25 @@ public class FileHelper {
*/ */
public static void getExcel(String url, String fileName, HttpServletResponse response, HttpServletRequest request) { public static void getExcel(String url, String fileName, HttpServletResponse response, HttpServletRequest request) {
//1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
response.setContentType("multipart/form-data");
//2.设置文件头:最后一个参数是设置下载文件名
try { try {
//1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
response.setContentType("multipart/form-data");
//2.设置文件头:最后一个参数是设置下载文件名
response.setHeader("Content-disposition", "attachment; filename=\"" response.setHeader("Content-disposition", "attachment; filename=\""
+ encodeChineseDownloadFileName(request, fileName + ".xls") + "\""); + encodeChineseDownloadFileName(request, fileName + ".xls") + "\"");
// response.setHeader("Content-Disposition", "attachment;filename=" } catch (UnsupportedEncodingException e) {
// + new String(fileName.getBytes("UTF-8"), "ISO-8859-1") + ".xls"); //中文文件名 e.printStackTrace();
}
//通过文件路径获得File对象 try (//通过文件路径获得File对象
File file = new File(url); FileInputStream in = new FileInputStream(new File(url));
//3.通过response获取OutputStream对象(out)
FileInputStream in = new FileInputStream(file); OutputStream out = new BufferedOutputStream(response.getOutputStream());) {
//3.通过response获取OutputStream对象(out)
OutputStream out = new BufferedOutputStream(response.getOutputStream());
int b = 0; int b = 0;
byte[] buffer = new byte[2048]; byte[] buffer = new byte[2048];
while ((b = in.read(buffer)) != -1) { while ((b = in.read(buffer)) != -1) {
out.write(buffer, 0, b); //4.写到输出流(out)中 out.write(buffer, 0, b); //4.写到输出流(out)中
} }
in.close();
out.flush(); out.flush();
out.close();
} catch (IOException e) { } catch (IOException e) {
log.error("下载Excel模板异常", e); log.error("下载Excel模板异常", e);
} }
......
...@@ -26,10 +26,12 @@ public class FileUtil { ...@@ -26,10 +26,12 @@ public class FileUtil {
if (!targetFile.exists()) { if (!targetFile.exists()) {
targetFile.mkdirs(); targetFile.mkdirs();
} }
FileOutputStream out = new FileOutputStream(filePath + fileName); try (FileOutputStream out = new FileOutputStream(filePath + fileName);) {
out.write(file); out.write(file);
out.flush(); out.flush();
out.close(); } catch (IOException e) {
e.printStackTrace();
}
} }
/** /**
......
...@@ -60,6 +60,7 @@ import java.net.URLEncoder; ...@@ -60,6 +60,7 @@ import java.net.URLEncoder;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.channels.Channel; import java.nio.channels.Channel;
import java.nio.channels.FileChannel; import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
...@@ -121,20 +122,10 @@ public class FileHelper { ...@@ -121,20 +122,10 @@ public class FileHelper {
* @return * @return
*/ */
public static boolean isWord2003(File file) { public static boolean isWord2003(File file) {
InputStream is = null; try (InputStream is = new FileInputStream(file);
try { HWPFDocument hwpfDocument = new HWPFDocument(is);) {
is = new FileInputStream(file);
new HWPFDocument(is);
} catch (Exception e) { } catch (Exception e) {
return false; return false;
} finally {
try {
if (null != is) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
} }
return true; return true;
} }
...@@ -164,24 +155,10 @@ public class FileHelper { ...@@ -164,24 +155,10 @@ public class FileHelper {
* @return * @return
*/ */
public static boolean isPPT2003(File file) { public static boolean isPPT2003(File file) {
InputStream is = null; try (InputStream is = new FileInputStream(file);
HSLFSlideShow ppt = null; HSLFSlideShow ppt = new HSLFSlideShow(is);) {
try {
is = new FileInputStream(file);
ppt = new HSLFSlideShow(is);
} catch (Exception e) { } catch (Exception e) {
return false; return false;
} finally {
try {
if (null != is) {
is.close();
}
if (null != ppt) {
ppt.close();
}
} catch (IOException e) {
e.printStackTrace();
}
} }
return true; return true;
} }
...@@ -193,13 +170,10 @@ public class FileHelper { ...@@ -193,13 +170,10 @@ public class FileHelper {
*/ */
public static StringBuffer readFile(String path) { public static StringBuffer readFile(String path) {
StringBuffer buffer = new StringBuffer(); StringBuffer buffer = new StringBuffer();
InputStream is = null; File file = new File(path);
BufferedReader br = null; try (InputStream is = new FileInputStream(file);
try { BufferedReader br = new BufferedReader(new InputStreamReader(is));) {
File file = new File(path);
if (file.exists()) { if (file.exists()) {
is = new FileInputStream(file);
br = new BufferedReader(new InputStreamReader(is));
String content = br.readLine(); String content = br.readLine();
while (null != content) { while (null != content) {
buffer.append(content); buffer.append(content);
...@@ -208,19 +182,7 @@ public class FileHelper { ...@@ -208,19 +182,7 @@ public class FileHelper {
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally {
try {
if (null != is) {
is.close();
}
if (null != br) {
br.close();
}
} catch (Exception e) {
e.printStackTrace();
}
} }
return buffer; return buffer;
} }
...@@ -232,13 +194,10 @@ public class FileHelper { ...@@ -232,13 +194,10 @@ public class FileHelper {
*/ */
public static StringBuffer readFile(String path, String split) { public static StringBuffer readFile(String path, String split) {
StringBuffer buffer = new StringBuffer(); StringBuffer buffer = new StringBuffer();
InputStream is = null; File file = new File(path);
BufferedReader br = null; try (InputStream is = new FileInputStream(file);
try { BufferedReader br = new BufferedReader(new InputStreamReader(is));) {
File file = new File(path);
if (file.exists()) { if (file.exists()) {
is = new FileInputStream(file);
br = new BufferedReader(new InputStreamReader(is));
String content = br.readLine(); String content = br.readLine();
while (null != content) { while (null != content) {
buffer.append(content).append(split); buffer.append(content).append(split);
...@@ -247,19 +206,7 @@ public class FileHelper { ...@@ -247,19 +206,7 @@ public class FileHelper {
} }
} catch (Exception exception) { } catch (Exception exception) {
exception.printStackTrace(); exception.printStackTrace();
} finally {
try {
if (null != is) {
is.close();
}
if (null != br) {
br.close();
}
} catch (Exception exception2) {
exception2.printStackTrace();
}
} }
return buffer; return buffer;
} }
...@@ -269,28 +216,17 @@ public class FileHelper { ...@@ -269,28 +216,17 @@ public class FileHelper {
* @param path 写入内容的文件路径 * @param path 写入内容的文件路径
*/ */
public static void writeFile(String content, String path) { public static void writeFile(String content, String path) {
OutputStream fos = null; File file = new File(path);
BufferedWriter bw = null; try (OutputStream fos = new FileOutputStream(file);
try { BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos, StandardCharsets.UTF_8)); ) {
File file = new File(path);
if (!file.getParentFile().exists()) { if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs(); file.getParentFile().mkdirs();
} }
fos = new FileOutputStream(file);
bw = new BufferedWriter(new OutputStreamWriter(fos, "UTF-8"));
bw.write(content); bw.write(content);
} catch (FileNotFoundException fnfe) { } catch (FileNotFoundException fnfe) {
fnfe.printStackTrace(); fnfe.printStackTrace();
} catch (IOException ioe) { } catch (IOException ioe) {
ioe.printStackTrace(); ioe.printStackTrace();
} finally {
try {
if (bw != null) {
bw.close();
}
} catch (IOException ioException) {
System.err.println(ioException.getMessage());
}
} }
} }
...@@ -379,11 +315,8 @@ public class FileHelper { ...@@ -379,11 +315,8 @@ public class FileHelper {
public static void rmrBlankLines(String inputFile, String outPutFile) throws IOException { public static void rmrBlankLines(String inputFile, String outPutFile) throws IOException {
File htmFile = new File(inputFile); File htmFile = new File(inputFile);
// 以GB2312读取文件 // 以GB2312读取文件
BufferedReader br = null; try (BufferedReader br = new BufferedReader(new FileReader(htmFile));
BufferedWriter bw = null; BufferedWriter bw = new BufferedWriter(new FileWriter(new File(outPutFile)));) {
try {
br = new BufferedReader(new FileReader(htmFile));
bw = new BufferedWriter(new FileWriter(new File(outPutFile)));
String result = null; String result = null;
while (null != (result = br.readLine())) { while (null != (result = br.readLine())) {
if (!"".equals(result.trim())) { if (!"".equals(result.trim())) {
...@@ -392,17 +325,6 @@ public class FileHelper { ...@@ -392,17 +325,6 @@ public class FileHelper {
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally {
try {
if (null != br) {
br.close();
}
if (null != bw) {
bw.close();
}
} catch (Exception e) {
}
} }
...@@ -1198,35 +1120,24 @@ private static void defaultExport(List<Map<String, Object>> list, String fileNam ...@@ -1198,35 +1120,24 @@ private static void defaultExport(List<Map<String, Object>> list, String fileNam
* @throws * @throws
*/ */
public static void getExcel(String url, String fileName, HttpServletResponse response,HttpServletRequest request){ public static void getExcel(String url, String fileName, HttpServletResponse response,HttpServletRequest request){
//1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
try { response.setContentType("multipart/form-data");
//2.设置文件头:最后一个参数是设置下载文件名
//1.设置文件ContentType类型,这样设置,会自动判断下载文件类型 try {
response.setContentType("multipart/form-data"); response.setHeader("Content-disposition", "attachment; filename=\""
+ encodeChineseDownloadFileName(request, fileName+".xls") +"\"");
//2.设置文件头:最后一个参数是设置下载文件名 } catch (UnsupportedEncodingException e) {
response.setHeader("Content-disposition", "attachment; filename=\"" e.printStackTrace();
+ encodeChineseDownloadFileName(request, fileName+".xls") +"\""); }
// response.setHeader("Content-Disposition", "attachment;filename=" try (FileInputStream in = new FileInputStream(new File(url));
// + new String(fileName.getBytes("UTF-8"), "ISO-8859-1") + ".xls"); //中文文件名 //3.通过response获取OutputStream对象(out)
OutputStream out = new BufferedOutputStream(response.getOutputStream());) {
//通过文件路径获得File对象
File file = new File(url);
FileInputStream in = new FileInputStream(file);
//3.通过response获取OutputStream对象(out)
OutputStream out = new BufferedOutputStream(response.getOutputStream());
int b = 0; int b = 0;
byte[] buffer = new byte[2048]; byte[] buffer = new byte[2048];
while ((b=in.read(buffer)) != -1){ while ((b=in.read(buffer)) != -1){
out.write(buffer,0,b); //4.写到输出流(out)中 out.write(buffer,0,b); //4.写到输出流(out)中
} }
in.close();
out.flush(); out.flush();
out.close();
} catch (IOException e) { } catch (IOException e) {
log.error("下载Excel模板异常", e); log.error("下载Excel模板异常", e);
} }
......
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