diff --git a/src/sc545/pay/utils/FileUtils.java b/src/sc545/pay/utils/FileUtils.java deleted file mode 100644 index d3a9366..0000000 --- a/src/sc545/pay/utils/FileUtils.java +++ /dev/null @@ -1,1106 +0,0 @@ -package sc545.pay.utils; - -import java.awt.Color; -import java.awt.Font; -import java.awt.image.BufferedImage; -import java.io.BufferedWriter; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.net.URL; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Random; -import java.util.UUID; - -import javax.imageio.ImageIO; -import javax.servlet.ServletContext; - -import net.coobird.thumbnailator.Thumbnails; -import net.coobird.thumbnailator.geometry.Positions; - -import org.apache.commons.codec.binary.Base64; -import org.apache.commons.fileupload.FileItem; -import org.apache.commons.fileupload.disk.DiskFileItemFactory; -import org.apache.commons.io.IOUtils; -import org.springframework.core.io.FileSystemResource; -import org.springframework.http.HttpHeaders; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.web.multipart.MultipartFile; -import org.springframework.web.multipart.commons.CommonsMultipartFile; - -import sun.misc.BASE64Encoder; - -import com.freeway.image.combiner.ImageCombiner; -import com.freeway.image.combiner.enums.OutputFormat; -import com.freeway.image.combiner.enums.ZoomMode; -import com.google.zxing.*; -import com.google.zxing.common.BitMatrix; - -public class FileUtils { - - public static void main(String[] args) throws Exception { - System.out.println("/a/b".substring(0, "/a/b".length()-1)); - } - - - - - -public static final int BLACK = 0xFF000000; -public static final int WHITE = 0xFFFFFFFF; -public static BufferedImage toBufferedImage(BitMatrix matrix) { - int width = matrix.getWidth(); - int height = matrix.getHeight(); - BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); - for (int x = 0; x < width; x++) { - for (int y = 0; y < height; y++) { - image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE); - } - } - return image; -} - -private static void writeToFile(BitMatrix matrix, String format, File file) throws IOException { - BufferedImage image = toBufferedImage(matrix); - if (!ImageIO.write(image, format, file)) { - throw new IOException("Could not write an image of format " + format + " to " + file); - } -} - -/** - * 删除二维码白边 - * @param matrix - * @return - */ -public static BitMatrix deleteQRWhite(BitMatrix matrix) { - int[] rec = matrix.getEnclosingRectangle(); - int resWidth = rec[2] + 1; - int resHeight = rec[3] + 1; - - BitMatrix resMatrix = new BitMatrix(resWidth, resHeight); - resMatrix.clear(); - for (int i = 0; i < resWidth; i++) { - for (int j = 0; j < resHeight; j++) { - if (matrix.get(i + rec[0], j + rec[1])) - resMatrix.set(i, j); - } - } - return resMatrix; -} - - - -/** - * 生成一张二维码图片文件 - * @param content 二维码内容 - * @param widthHeight 宽高度 - * @param path 图片存储路径(不带文件名) - * @return - */ -public static String QrImgFile(String content,int widthHeight,String path) { - try { - String codeName = UUID.randomUUID().toString();// 二维码的图片名 - String imageType = "jpg";// 图片类型 - MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); - Map hints = new HashMap(); - hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); - BitMatrix bitMatrix= multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, widthHeight, widthHeight, hints); - bitMatrix= deleteQRWhite(bitMatrix); - // BufferedImage imgbuf = toBufferedImage(bitMatrix); - File file1 = new File(path, codeName + "." + imageType); - writeToFile(bitMatrix, imageType, file1); - return path+codeName + "." + imageType; - - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - return null; -} - - -/** - * 生成一张二维码图片(BufferedImage) - * @param content 二维码内容 - * @param widthHeight 宽高度 - * @return - */ -public static BufferedImage QrImgBuf(String content,int widthHeight) { - try { - MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); - Map hints = new HashMap(); - hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); - BitMatrix bitMatrix= multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, widthHeight, widthHeight, hints); - bitMatrix= deleteQRWhite(bitMatrix); - BufferedImage imgbuf = toBufferedImage(bitMatrix); - return imgbuf; - - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - return null; -} - - -/** - * 生成一张二维码图片(base64)
- * data:image/jpg;base64,base64_code - * @param content 二维码内容 - * @param widthHeight 宽高度 - * @return - */ -public static String QrImgB64(String content,int widthHeight) { - try { - MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); - Map hints = new HashMap(); - hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); - BitMatrix bitMatrix= multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, widthHeight, widthHeight, hints); - bitMatrix= deleteQRWhite(bitMatrix); - BufferedImage imgbuf = toBufferedImage(bitMatrix); - ByteArrayOutputStream os = new ByteArrayOutputStream();//新建流。 - ImageIO.write(imgbuf, "jpg", os);//利用ImageIO类提供的write方法,将bi以png图片的数据模式写入流。 - byte b[] = os.toByteArray();//从流中获取数据数组。 - String str = new BASE64Encoder().encode(b); - return str; - - } catch (Exception e) { - e.printStackTrace(); - } - - return null; -} - - -/** - * 图片质量压缩 - * @param img 文件流 - * @param quality 压缩质量 0~1/1为最高质量 - * @return - */ -public static BufferedImage rarImgBuf(InputStream img, double quality) { - BufferedImage buf =null; - try { - buf = Thumbnails.of(img).scale(1f).outputQuality(quality).asBufferedImage(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - return buf; -} - -/** - * 图片质量压缩 - * @param img 文件地址 - * @param quality 压缩质量 0~1/1为最高质量 - * @return - */ -public static File rarImgFile(File img, double quality) { - File arg0 = img; - try { - Thumbnails.of(img).scale(1f).outputQuality(quality).toFile(arg0); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - return arg0; -} - -/** - * 裁剪图片
- * 从左上角开始裁切
- * 另存图片保持等比缩放,若填写的高度不符合自动调整为等比例 - * - * @param img 图片文件 - * @param p 裁切位置 Positions.TOP/BOTTOM_LEFT/RIGHT、CENTER - * @param x 裁切x轴范围 - * @param y 裁切y轴范围 - * @param width 另存图片的宽度 - * @param height 另存图片的高度 - * @return - */ -public static File cutImgFile(File img,Positions p,int x,int y,int width,int height) { - File arg0 = img; - try { - Thumbnails.of(img).sourceRegion(p, x, y).size(width, height).keepAspectRatio(true).toFile(arg0); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - return arg0; -} - - -/** - * 裁剪图片
- * 从左上角开始裁切
- * 另存图片保持等比缩放,若填写的高度不符合自动调整为等比例 - * - * @param img 图片流 - * @param p 裁切位置 Positions.TOP/BOTTOM_LEFT/RIGHT、CENTER - * @param x 裁切x轴范围 - * @param y 裁切y轴范围 - * @param width 另存图片的宽度 - * @param height 另存图片的高度 - * @return - */ -public static BufferedImage cutImgBuf(InputStream img,Positions p,int x,int y,int width,int height) { - BufferedImage buf =null; - try { - buf=Thumbnails.of(img).sourceRegion(p, x, y).size(width, height).keepAspectRatio(true).asBufferedImage(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - return buf; -} - - - -/** - * 将图片存放在项目根路径下 - * @param servletContext - * @param file MultipartFile文件 - * @param path 在项目根目录下的存放路径 - * @param towhere 数据库入库格式,格式:表#id#字段 - * @return 图片路径(相对) - */ -public static String putImg(ServletContext servletContext,MultipartFile file,String path,String towhere) { - int maxSize = 1024*1024*2; //上传最大为2MB - if (file==null||file.getSize()>maxSize) { - return "图片最大上传2MB"; - } - - - File targetFile=null; - String realurl="";//返回存储路径 - String rid=""; - String fileName=file.getOriginalFilename();//获取文件名加后缀 - if(fileName.trim().length()<1) return "图片不能为空"; - if(fileName!=null&&fileName!=""){ - String lpath=path; - - if(servletContext==null) - path = "D:/"+(lpath.replaceAll("D:/", "").replaceAll("D://", "").replaceAll("D:", "").replaceAll("c:", ""));//图片存储在C盘下的路径 - else{ - //修改:原本存储在项目根路径下的,为了防止删除项目文件丢失 - //path = servletContext.getRealPath(lpath);//图片存储在项目根目录下的路径 - //现修改为:存储到固定文件夹(子路径保留),读取的时候通过url获取base64格式图片 - String basePath = ReadTxt.getSetting(null, "setting.ini", "FilePath", "D://scbox_settings/webFile"); - if("/".equals(basePath.substring(basePath.length()-1, basePath.length()))) basePath=basePath.substring(0, basePath.length()-1); - String np=lpath; - if(lpath.indexOf(":")>0){ - np = lpath.substring(lpath.indexOf(":")+2,lpath.length()); - if(!"/".equals(np.substring(0, 1))) np="/"+np; - }else{ - if(!"/".equals(np.substring(0, 1))) np="/"+np; - } - path = basePath+np; - } - String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());//文件后缀 - if (!(fileF.equals(".jpg") || fileF.equals(".jpeg") || fileF.equals(".png") || fileF.equals(".gif"))) { - return "只能上传jpg,jpeg,png,gif格式图片"; - } - //新的文件名 - fileName=new Date().getTime()+"_"+new Random().nextInt(1000)+fileF; - //获取文件夹路径 - File file1=new File(path); - //如果文件夹不存在则创建 - if(!file1.exists() && !file1.isDirectory()){ - file1.mkdirs(); - } - //将图片存入文件夹 - targetFile = new File(file1, fileName); - - try { - //将上传的文件写到服务器上指定的文件。 - file.transferTo(targetFile); - rarImgFile(targetFile, 0.8f); - //赋予权限 - /*String command = "chmod 775 -R " + targetFile; - Runtime runtime = Runtime.getRuntime(); - Process proc = runtime.exec(command);*/ - //生成文件地址 - - if(servletContext==null) realurl=path+"/"+fileName; - else realurl=ReadTxt.getSetting(null, "setting.ini", "resweb", "")+path+"/"+fileName; - //System.out.println("图片上传成功 \nUrl:"+realurl); - } catch (Exception e) { - e.printStackTrace(); - return "系统异常,图片上传失败"; - } - - /** - * 存储完成之后把信息存到数据库,后续用数据库ID来取用文件 - * - * **/ - DBUtil db = new DBUtil(); - int i = db.execUpdate("insert savefile(realurl) values('"+realurl+"')", null); - if(i>0){ - List> rs = db.execQuery("select * from savefile where realurl='"+realurl+"'", null); - if(rs!=null&&rs.size()>0) rid=rs.get(0).get("id")+""; - } - - //成功/添加图片用处 - if(towhere != null && !"".equals(towhere)) - saveSql(realurl, towhere,fileName); - } - - if(servletContext != null) return "/getImg/"+rid; - else return realurl; -} - -/** - * 将图片存放在项目根路径下(带名称,不含文件格式后缀) - * @param servletContext - * @param file MultipartFile文件 - * @param path 在项目根目录下的存放路径 - * @param towhere 数据库入库格式,格式:表#id#字段 - * @return 图片路径(相对) - */ -public static String putImgAsName(ServletContext servletContext,MultipartFile file,String path,String filename,String towhere) { - int maxSize = 1024*1024*2; //上传最大为2MB - if (file==null||file.getSize()>maxSize) { - return "图片最大上传2MB"; - } - File targetFile=null; - String rid=""; - String realurl="";//返回存储路径 - String fileName=file.getOriginalFilename();//获取文件名加后缀 - if(fileName.trim().length()<1) return "图片不能为空"; - if(fileName!=null&&fileName!=""){ - String lpath=path; - if(servletContext==null) - path = "D:/"+(lpath.replaceAll("D:/", "").replaceAll("D://", "").replaceAll("D:", "").replaceAll("c:", ""));//图片存储在C盘下的路径 - else{ - //修改:原本存储在项目根路径下的,为了防止删除项目文件丢失 - //path = servletContext.getRealPath(lpath);//图片存储在项目根目录下的路径 - //现修改为:存储到固定文件夹(子路径保留),读取的时候通过url获取base64格式图片 - String basePath = ReadTxt.getSetting(null, "setting.ini", "FilePath", "D://scbox_settings/webFile"); - if("/".equals(basePath.substring(basePath.length()-1, basePath.length()))) basePath=basePath.substring(0, basePath.length()-1); - String np=lpath; - if(lpath.indexOf(":")>0){ - np = lpath.substring(lpath.indexOf(":")+2,lpath.length()); - if(!"/".equals(np.substring(0, 1))) np="/"+np; - }else{ - if(!"/".equals(np.substring(0, 1))) np="/"+np; - } - path = basePath+np; - } - - String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());//文件后缀 - if (!(fileF.equals(".jpg") || fileF.equals(".jpeg") || fileF.equals(".png") || fileF.equals(".gif"))) { - return "只能上传jpg,jpeg,png,gif格式图片"; - } - //新的文件名 - if(filename!=null&&filename.length()>0) - fileName=filename+fileF; - else - fileName=new Date().getTime()+"_"+new Random().nextInt(1000)+fileF; - //获取文件夹路径 - File file1=new File(path); - //如果文件夹不存在则创建 - if(!file1.exists() && !file1.isDirectory()){ - file1.mkdirs(); - } - //将图片存入文件夹 - targetFile = new File(file1, fileName); - - try { - //将上传的文件写到服务器上指定的文件。 - file.transferTo(targetFile); - rarImgFile(targetFile, 0.8f); - //赋予权限 - /*String command = "chmod 775 -R " + targetFile; - Runtime runtime = Runtime.getRuntime(); - Process proc = runtime.exec(command);*/ - //生成文件地址 - if(servletContext==null) realurl=path+"/"+fileName; - else realurl=ReadTxt.getSetting(null, "setting.ini", "resweb", "")+path+"/"+fileName; - //System.out.println("图片上传成功 \nUrl:"+realurl); - } catch (Exception e) { - e.printStackTrace(); - return "系统异常,图片上传失败"; - } - - /** - * 存储完成之后把信息存到数据库,后续用数据库ID来取用文件 - * - * **/ - DBUtil db = new DBUtil(); - int i = db.execUpdate("insert savefile(realurl) values('"+realurl+"')", null); - if(i>0){ - List> rs = db.execQuery("select * from savefile where realurl='"+realurl+"'", null); - if(rs!=null&&rs.size()>0) rid=rs.get(0).get("id")+""; - } - - //成功/添加图片用处 - if(towhere != null && !"".equals(towhere)) - saveSql(realurl, towhere,fileName); - } - - if(servletContext != null) return "/getImg/"+rid; - else return realurl; -} - - -/** - * 将视频存放在项目根路径下 - * @param servletContext - * @param file MultipartFile文件 - * @param path 在项目根目录下的存放路径 - * @param towhere 数据库入库格式,格式:表#id#字段 - * @return 图片路径(相对) - */ -public static String putVideo(ServletContext servletContext,MultipartFile file,String path,String towhere) { - int maxSize = 1024*1024*10; //上传最大为2MB - if (file==null) { - return ""; - } - if (file.getSize()>maxSize) { - return "视频最大上传10MB"; - } - File targetFile=null; - String rid=""; - String realurl="";//返回存储路径 - String fileName=file.getOriginalFilename();//获取文件名加后缀 - if(fileName.trim().length()<1) return ""; - if(fileName!=null&&fileName!=""){ - String lpath=path; - if(servletContext==null) - path = "D:/"+(lpath.replaceAll("D:/", "").replaceAll("D://", "").replaceAll("D:", "").replaceAll("c:", ""));//图片存储在C盘下的路径 - else{ - - //修改:原本存储在项目根路径下的,为了防止删除项目文件丢失 - //path = servletContext.getRealPath(lpath);//图片存储在项目根目录下的路径 - //现修改为:存储到固定文件夹(子路径保留),读取的时候通过url获取base64格式图片 - String basePath = ReadTxt.getSetting(null, "setting.ini", "FilePath", "D://scbox_settings/webFile"); - if("/".equals(basePath.substring(basePath.length()-1, basePath.length()))) basePath=basePath.substring(0, basePath.length()-1); - String np=lpath; - if(lpath.indexOf(":")>0){ - np = lpath.substring(lpath.indexOf(":")+2,lpath.length()); - if(!"/".equals(np.substring(0, 1))) np="/"+np; - }else{ - if(!"/".equals(np.substring(0, 1))) np="/"+np; - } - path = basePath+np; - - } - - String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());//文件后缀 - if (!(fileF.equals(".mp4"))) { - return "只能上传mp4格式视频"; - } - //新的文件名 - fileName=new Date().getTime()+"_"+new Random().nextInt(1000)+fileF; - //获取文件夹路径 - File file1=new File(path); - //如果文件夹不存在则创建 - if(!file1.exists() && !file1.isDirectory()){ - file1.mkdirs(); - } - //将图片存入文件夹 - targetFile = new File(file1, fileName); - - try { - //将上传的文件写到服务器上指定的文件。 - file.transferTo(targetFile); - rarImgFile(targetFile, 0.8f); - //赋予权限 - /*String command = "chmod 775 -R " + targetFile; - Runtime runtime = Runtime.getRuntime(); - Process proc = runtime.exec(command);*/ - //生成文件地址 - if(servletContext==null) realurl=path+"/"+fileName; - else realurl=ReadTxt.getSetting(null, "setting.ini", "resweb", "")+path+"/"+fileName; - //System.out.println("图片上传成功 \nUrl:"+realurl); - } catch (Exception e) { - e.printStackTrace(); - return "系统异常,视频上传失败"; - } - - /** - * 存储完成之后把信息存到数据库,后续用数据库ID来取用文件 - * - * **/ - DBUtil db = new DBUtil(); - int i = db.execUpdate("insert savefile(realurl) values('"+realurl+"')", null); - if(i>0){ - List> rs = db.execQuery("select * from savefile where realurl='"+realurl+"'", null); - if(rs!=null&&rs.size()>0) rid=rs.get(0).get("id")+""; - } - - //成功/添加图片用处 - if(towhere != null && !"".equals(towhere)) - saveSql(realurl, towhere,fileName); - } - - if(servletContext != null) return "/getImg/"+rid; - else return realurl; -} - - - - -/** - * 将文件存放在项目根路径下 - * @param servletContext - * @param file MultipartFile文件 - * @param filename 文件名 不含后缀格式,为空自动生成 - * @param path 在项目根目录下的存放路径 - * @param towhere 数据库入库格式,格式:表#id#字段 - * @return 图片路径(相对) - */ -public static String putFile(ServletContext servletContext,MultipartFile file,String filename,String path,String towhere) { - int maxSize = 1024*1024*10; //上传最大为2MB - if (file==null) { - return ""; - } - if (file.getSize()>maxSize) { - return "文件最大上传20MB"; - } - File targetFile=null; - String rid=""; - String realurl="";//返回存储路径 - String fileName=file.getOriginalFilename();//获取文件名加后缀 - if(fileName.trim().length()<1) return ""; - if(fileName!=null&&fileName!=""){ - String lpath=path; - if(servletContext==null) - path = "D:/"+(lpath.replaceAll("D:/", "").replaceAll("D://", "").replaceAll("D:", "").replaceAll("c:", ""));//图片存储在C盘下的路径 - else{ - //修改:原本存储在项目根路径下的,为了防止删除项目文件丢失 - //path = servletContext.getRealPath(lpath);//图片存储在项目根目录下的路径 - //现修改为:存储到固定文件夹(子路径保留),读取的时候通过url获取base64格式图片 - String basePath = ReadTxt.getSetting(null, "setting.ini", "FilePath", "D://scbox_settings/webFile"); - if("/".equals(basePath.substring(basePath.length()-1, basePath.length()))) basePath=basePath.substring(0, basePath.length()-1); - String np=lpath; - if(lpath.indexOf(":")>0){ - np = lpath.substring(lpath.indexOf(":")+2,lpath.length()); - if(!"/".equals(np.substring(0, 1))) np="/"+np; - }else{ - if(!"/".equals(np.substring(0, 1))) np="/"+np; - } - path = basePath+np; - } - - String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());//文件后缀 - - //新的文件名 - if(filename!=null&&filename.length()>0) - fileName=filename+fileF; - else - fileName=new Date().getTime()+"_"+new Random().nextInt(1000)+fileF; - //获取文件夹路径 - File file1=new File(path); - //如果文件夹不存在则创建 - if(!file1.exists() && !file1.isDirectory()){ - file1.mkdirs(); - } - //将图片存入文件夹 - targetFile = new File(file1, fileName); - - try { - //将上传的文件写到服务器上指定的文件。 - file.transferTo(targetFile); - //赋予权限 - /*String command = "chmod 775 -R " + targetFile; - Runtime runtime = Runtime.getRuntime(); - Process proc = runtime.exec(command);*/ - //生成文件地址 - if(servletContext==null) realurl=path+"/"+fileName; - else realurl=ReadTxt.getSetting(null, "setting.ini", "resweb", "")+path+"/"+fileName; - //System.out.println("图片上传成功 \nUrl:"+realurl); - } catch (Exception e) { - e.printStackTrace(); - return "系统异常,视频上传失败"; - } - - /** - * 存储完成之后把信息存到数据库,后续用数据库ID来取用文件 - * - * **/ - DBUtil db = new DBUtil(); - int i = db.execUpdate("insert savefile(realurl) values('"+realurl+"')", null); - if(i>0){ - List> rs = db.execQuery("select * from savefile where realurl='"+realurl+"'", null); - if(rs!=null&&rs.size()>0) rid=rs.get(0).get("id")+""; - } - - //成功/添加图片用处 - if(towhere != null && !"".equals(towhere)) - saveSql(realurl, towhere,fileName); - } - - if(servletContext != null) return "/getFile/"+rid; - else return realurl; -} - - -/** - * 把上传的文件信息存入数据库 - * @param realurl 文件路径 - * @param towhere 数据库入库格式,格式:表#id#字段 - * @param saveName 显示文件名称 - */ -public static void saveSql(String realurl, String towhere, String saveName) { - - if(realurl.indexOf("http")>=0 || realurl.indexOf("upload")<0) return; - - //标记文件被使用的地方,方便后续清理无用文件 - // 标记位置格式:表#id#字段,比如哪个表里哪条数据的哪个字段使用该文件,byx_class#16#clist - DBUtil db = new DBUtil(); - - if(towhere.split("#").length>2&&realurl.trim().length()>0){ - String mstab = towhere.split("#")[0]; - String msid = towhere.split("#")[1]; - String mstag = towhere.split("#")[2]; - - if(realurl.indexOf("/getImg/")==0) { - realurl=realurl.replace("/getImg/", ""); - if(db.execSql("select * from savefile where id = '"+realurl+"'", null)>0){//已存在 - db.execUpdate("update savefile set mstab=?,msid=?,mstag=?,savename=? where id=?", new String[]{mstab.trim(),msid.trim(),mstag.trim(),realurl.trim(),saveName==null?"":saveName.trim()}); - }else{//不存在 - //db.execUpdate("insert into savefile(realurl,mstab,msid,mstag,savename) values(?,?,?,?,?)", new String[]{realurl.trim(),mstab.trim(),msid.trim(),mstag.trim(),saveName==null?"":saveName.trim()}); - } - }else{ - if(db.execSql("select * from savefile where realurl = '"+realurl+"'", null)>0){//已存在 - db.execUpdate("update savefile set mstab=?,msid=?,mstag=?,savename=? where realurl=?", new String[]{mstab.trim(),msid.trim(),mstag.trim(),realurl.trim(),saveName==null?"":saveName.trim()}); - }else{//不存在 - db.execUpdate("insert into savefile(realurl,mstab,msid,mstag,savename) values(?,?,?,?,?)", new String[]{realurl.trim(),mstab.trim(),msid.trim(),mstag.trim(),saveName==null?"":saveName.trim()}); - } - } - - - } - -} - - -/** - * 创建一个文件并写入内容 - * @param servletContext - * @param path 路径(不含文件名) - * @param content 内容 - * @param suffix 后缀名(不含点) - * @param oldfile 自己设定文件名(含后缀) 可带路径,若为空则根据时间戳生成随机文件名 - * @return - */ -public static String writeFile(ServletContext servletContext, String path, - String content, String suffix, String oldfile) { - - if(".".equals(suffix.substring(0, 1))) suffix=suffix.substring(1, suffix.length()); - - //兼容文件名含路径 - if(oldfile!=null&&!"".equals(oldfile.trim())){ - int i = oldfile.replace("\\","/").lastIndexOf("/"); - if(i>0) - path=oldfile.substring(0, i); - oldfile=oldfile.substring(i+1, oldfile.length()); - } - - String path1 = path; - if(path.indexOf("./")==0) - path =path.substring(1, path.length()); - - if (servletContext == null) { - if(path.indexOf(":") <= 0&&path.indexOf("/") <0) - path1 = "D:\\" + path; - else path1 = path; - } else { - //修改:原本存储在项目根路径下的,为了防止删除项目文件丢失 - //path = servletContext.getRealPath(lpath);//图片存储在项目根目录下的路径 - //现修改为:存储到固定文件夹(子路径保留),读取的时候通过url获取base64格式图片 - String basePath = ReadTxt.getSetting(null, "setting.ini", "FilePath", "D://scbox_settings/webFile"); - if("/".equals(basePath.substring(basePath.length()-1, basePath.length()))) basePath=basePath.substring(0, basePath.length()-1); - String np=path; - if(path.indexOf(":")>0){ - np = path.substring(path.indexOf(":")+2,path.length()); - if(!"/".equals(np.substring(0, 1))) np="/"+np; - }else{ - if(!"/".equals(np.substring(0, 1))) np="/"+np; - } - path1 = basePath+np; - } - - if(!"/".equals(path1.replace("\\", "/").substring(path1.replace("\\", "/").length()-1))) path1+="/"; - File file1 = new File(path1); - if (!file1.exists() && !file1.isDirectory()) { - file1.mkdirs(); - } - - String fileName = new Date().getTime() + "_" - + new Random().nextInt(1000) + "." + suffix; - if(oldfile!=null&&!"".equals(oldfile.trim())) fileName = oldfile; - path1 += fileName; - file1 = new File(path1); - - try { - if (!file1.exists()) { - file1.createNewFile(); - } - PrintWriter out = new PrintWriter( - new BufferedWriter(new OutputStreamWriter( - new FileOutputStream(path1), "UTF-8"))); - out.write(content); - out.flush(); - out.close(); - } catch (IOException e) { - e.printStackTrace(); - } - - return fileName; -} - -/** - * 删除上传的文件,联通表数据一块删除 - *
servletContext为空默认C盘 - */ -public static void delfile(ServletContext servletContext, String path) { - path=path.replace(ReadTxt.getSetting(null, "setting.ini", "resweb", ""),""); - if(path.indexOf("http")==0 || path.indexOf("//")==0) return ; - if(path.indexOf("./")==0) - path =path.substring(1, path.length()); - - String path1 = path; - if (servletContext == null) { - if(path.indexOf(":") <= 0) - path1 = "D:\\" + path; - } else { - if(path.indexOf("/getImg/")==0){ - String rid = path.replace("/getImg/", ""); - DBUtil db = new DBUtil(); - List> rs = db.execQuery("select * from savefile where id ="+rid, null); - if(rs!=null&&rs.size()>0){ - path=rs.get(0).get("realurl")+""; - path1=rs.get(0).get("realurl")+""; - } - } else path1 = servletContext.getRealPath(path); - } - - File file1 = new File(path1); - if(file1.exists()) { - file1.delete(); - //兼容 - new DBUtil().execUpdate("delete from savefile where realurl=?", new String[]{path}); - - } - - -} - - -/** - * 删除字符串中提取的图片文件 - * - * @param path - * 项目根目录下的文件路径(servletContext若null为c盘下的) - */ -public static void delFileForStr(ServletContext servletContext, String str) { - - ArrayList imgs = Utils.getImgStr(str, true); - DBUtil db = new DBUtil(); - - for (String path : imgs) { - path=path.replace(ReadTxt.getSetting(null, "setting.ini", "resweb", ""),""); - if(path.indexOf("http")==0 || path.indexOf("//")==0) continue; - String oldpath = path; - if(path.indexOf("./")==0) - path =path.substring(1, path.length()); - - path=path.replace(ReadTxt.getSetting(null, "setting.ini", "resweb", ""),""); - - String path1 = path; - if (servletContext == null) { - if(path.indexOf(":") <= 0) - path1 = "D:\\" + path; - } else { - if(path.indexOf("/getImg/")==0){ - String rid = path.replace("/getImg/", ""); - List> rs = db.execQuery("select * from savefile where id ="+rid, null); - if(rs!=null&&rs.size()>0){ - oldpath=rs.get(0).get("realurl")+""; - path1=rs.get(0).get("realurl")+""; - } - } else path1 = servletContext.getRealPath(path); - } - - File file1 = new File(path1); - if(file1.exists()) { - file1.delete(); - - //兼容img_tag - db.execUpdate("delete from savefile where realurl='"+oldpath+"'", null); - - } - } - - -} - -/** - * 提取字符串中的图片地址存入数据库 - * @param str - * @param towhere - * @param saveName - */ -public static void intoSqlForStr(String str,String towhere,String saveName) { - ArrayList imgs = Utils.getImgStr(str, true); - DBUtil db = new DBUtil(); - String mstab = towhere.split("#")[0]; - String msid = towhere.split("#")[1]; - String mstag=""; - if(towhere.split("#").length>2) - mstag = towhere.split("#")[2]; - - for (String path : imgs) { - if(path.indexOf("/getImg/")==0){ - String rid = path.replace("/getImg/", ""); - List> rs = db.execQuery("select * from savefile where id ="+rid, null); - if(rs!=null&&rs.size()>0){ - path=rs.get(0).get("realurl")+""; - - } - } - - if(path.indexOf("http")>=0 || path.indexOf("upload")<0) continue; - - if(db.execSql("select * from savefile where realurl = '"+path+"'", null)>0){//已存在 - db.execUpdate("update savefile set mstab=?,msid=?,mstag=?,savename=? where realurl=?", new String[]{mstab.trim(),msid.trim(),mstag.trim(),saveName==null?"":saveName.trim(),path.trim()}); - }else{//不存在 - db.execUpdate("insert into savefile(realurl,mstab,msid,mstag,savename) values(?,?,?,?,?)", new String[]{path.trim(),mstab.trim(),msid.trim(),mstag.trim(),saveName==null?"":saveName.trim()}); - } - } - -} - - - -/** - * 下载url图片 - * @param url - * @return - */ -public static File downloadImage(String url) { - File file = null; - - URL urlfile; - InputStream inputStream = null; - OutputStream outputStream= null; - try { - file = File.createTempFile(new Date().getTime()+"_"+new Random().nextInt(1000), url.substring(url.lastIndexOf("."))); - //下载 - urlfile = new URL(url); - inputStream = urlfile.openStream(); - outputStream= new FileOutputStream(file); - - int bytesRead = 0; - byte[] buffer = new byte[8192]; - while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) { - outputStream.write(buffer, 0, bytesRead); - } - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - if (null != outputStream) { - outputStream.close(); - } - if (null != inputStream) { - inputStream.close(); - } - - } catch (Exception e) { - e.printStackTrace(); - } - } - return file; -} - -public static MultipartFile getMultipartFile(File file) { - FileItem item = new DiskFileItemFactory().createItem("file" - , MediaType.MULTIPART_FORM_DATA_VALUE - , true - , file.getName()); - try (InputStream input = new FileInputStream(file); - OutputStream os = item.getOutputStream()) { - // 流转移 - IOUtils.copy(input, os); - } catch (Exception e) { - throw new IllegalArgumentException("Invalid file: " + e, e); - } - - return new CommonsMultipartFile(item); -} - -/** - * 返回文件类型 - * @param file - * @return - */ -public static ResponseEntity returnFile(File file) { - if (file == null) { - return null; - } - HttpHeaders headers = new HttpHeaders(); - headers.add("Cache-Control", "no-cache, no-store, must-revalidate"); - headers.add("Content-Disposition", "attachment; filename=" + file.getName()); - headers.add("Pragma", "no-cache"); - headers.add("Expires", "0"); - headers.add("Last-Modified", new Date().toString()); - headers.add("ETag", String.valueOf(System.currentTimeMillis())); - return ResponseEntity - .ok() - .headers(headers) - .contentLength(file.length()) - .contentType(MediaType.parseMediaType("application/octet-stream")) - .body(new FileSystemResource(file)); -} - - - -/** - * 制作合成图片 -* @param title 课程名称 15字内 - * @param des 课程简介 48字内 - * @param teacher 老师名称 - * @param teacherImgUrl 老师透明照片180*318 - * @param localUrl 二维码地址 - * @return - */ -public static String imgPS(String title,String des,String teacher,String teacherImgUrl,String localUrl) { - String r=null; - try { - String bjUrl = "file:///C://webimg/bj.jpg"; - String imgUrl = teacherImgUrl; - - //标题x,y轴,字体大小,最大行数,行高 - int title_x=27; - int title_y=30; - int title_f=100; - int title_h=2; - int title_l=120; - if(title.length()<=6){//6字以内 - title_x=40; - title_y=30; - title_f=100; - title_h=2; - title_l=120; - }else if(title.length()>6&&title.length()<9){ //7-8字 - title_x=22; - title_y=67; - title_f=85; - title_h=2; - title_l=88; - }else if(title.length()>8&&title.length()<13){ //9-12字 - title_x=33; - title_y=32; - title_f=80; - title_h=3; - title_l=85; - }else{ - title_x=27; - title_y=30; - title_f=65; - title_h=3; - title_l=75; - } - - //简介x,y轴,字体大小 - int des_x=27; - int des_y=30; - int des_f=20; - int des_h=2; - int des_l=25; - if(des.length()<=16){//16字以内 - des_y=310; - des_h=1; - }else if(title.length()>16&&title.length()<33){ //16-32字 - des_y=303; - des_h=2; - }else{ //32++ - des_y=290; - des_h=3; - } - - teacher = "主讲人:"+teacher; - //讲师x轴 - int tx = (178-(teacher.length()*24))/2; - - - Color c1=new Color(26, 121, 134); - //合成器(指定背景图和输出格式,整个图片的宽高和相关计算依赖于背景图,所以背景图的大小是个基准) - ImageCombiner combiner = new ImageCombiner( bjUrl, 385, 666, ZoomMode.Height, OutputFormat.JPG); - - //标题 - combiner.addTextElement(title, new Font("微软雅黑",Font.BOLD, title_f), title_x, title_y) //内容,默认字体为阿里普惠,字体大小,x,y - .setCenter(false) //居中绘制(会忽略x坐标,改为自动计算) - .setAlpha(1.0f) //透明度(0.0~1.0) - .setRotate(0) //旋转(0~360) - .setAutoBreakLine(340, title_h, title_l) //自动换行 - .setColor(c1); //颜色 - - //简介 - combiner.addTextElement(des, new Font("微软雅黑",Font.BOLD, des_f), des_x,des_y) //内容,默认字体为阿里普惠,字体大小,x,y - .setCenter(false) //居中绘制(会忽略x坐标,改为自动计算) - .setAutoBreakLine(335, des_h, des_l) //自动换行 /最大宽度,最大行数,行高 - .setColor(c1); //颜色 - - //讲师 - combiner.addTextElement(teacher, new Font("微软雅黑",Font.BOLD, 24), tx+22, 390) //内容,默认字体为阿里普惠,字体大小,x,y - .setCenter(false) //居中绘制(会忽略x坐标,改为自动计算) - .setAlpha(1.0f) //透明度(0.0~1.0) - .setRotate(0) //旋转(0~360) - .setAutoBreakLine(178, 1, 24) //自动换行 /最大宽度,最大行数,行高 - .setColor(Color.WHITE); //颜色 - - //图片 - combiner.addImageElement(imgUrl, 205, 349, 180, 318, ZoomMode.Width) //imgUrl, x, y, width, height, zoomMode - .setCenter(false) //居中绘制(会忽略x坐标,改为自动计算) - .setRoundCorner(0); //设置圆角 - - - //生成二维码Buffer - BufferedImage imgbuf = QrImgBuf(localUrl, 200); - combiner.addImageElement(imgbuf, 29, 441, 165, 165, ZoomMode.WidthHeight) - .setRoundCorner(0);//圆角 - - //执行图片合并 - combiner.combine(); - - //可以获取流(并上传oss等) - //InputStream is = combiner.getCombinedImageStream(); - - //也可以保存到本地 - //combiner.save("D://image.jpg"); - - //压缩图片 - //BufferedImage img = rarImgBuf(combiner.getCombinedImageStream(),0.5f); - - //输出为base64 - byte[] arr = IOUtils.toByteArray(combiner.getCombinedImageStream()); - r = Base64.encodeBase64String(arr);//转换为base64格式 - - } catch (Exception e) { - System.out.println(e); - } - - return r; -} - - - -} diff --git a/src/sc545/pay/utils/ReadTxt.java b/src/sc545/pay/utils/ReadTxt.java deleted file mode 100644 index ad3c9d1..0000000 --- a/src/sc545/pay/utils/ReadTxt.java +++ /dev/null @@ -1,710 +0,0 @@ -package sc545.pay.utils; - -import java.io.*; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map.Entry; - -import javax.servlet.ServletContext; - -public class ReadTxt { - - public static void main(String[] args) { - } - - /** - * 按行读取txt文件 - * - * @param path - * 文件地址(默认D:\\scbox_settings开头) - * @return ArrayList 返回每行数据为一个items的集合 - */ - public static ArrayList readFileLine(ServletContext servletContext, String path) { - - if(path.indexOf("./")==0) - path =path.substring(1, path.length()); - - if (servletContext == null) { - if(path.indexOf(":") <= 0&&path.indexOf("/") <0) - path = "D:\\scbox_settings\\" + path; - } else { - path = servletContext.getRealPath(path); - } - - - - ArrayList strarr = null; - try { - File file = new File(path); - if (file.isFile() && file.exists()) { // 判断文件是否存在 - InputStreamReader read = new InputStreamReader( - new FileInputStream(file), "UTF-8"); - BufferedReader bufferedReader = new BufferedReader(read); - String lineTxt = null; - strarr = new ArrayList(); - while ((lineTxt = bufferedReader.readLine()) != null) { - - strarr.add(lineTxt); - } - - read.close(); - } else { - strarr = null; - } - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - return strarr; - } - - - - /** - * 写入txt文档,已存在就修改,否则写入末尾,自动加换行 (文件格式:key=value,换行分隔) - * - * @param path - * 文件地址(默认D:\\scbox_settings开头) - * @param keyname - * 要修改的参数名 - * @param content - * 要修改的参数值 - */ - public static void writeSetting(ServletContext servletContext, String path, String keyname, String content) { - - /**************/ - // 如果存在,则追加内容;如果文件不存在,则创建文件 - if(path.indexOf("./")==0) - path =path.substring(1, path.length()); - - if (servletContext == null) { - if(path.indexOf(":") <= 0&&path.indexOf("/") <0) - path = "D:\\scbox_settings\\" + path; - } else { - path = servletContext.getRealPath(path); - } - - try { - File file = new File(path); - if (file.isFile() && file.exists()) { // 判断文件是否存在 - InputStreamReader read = new InputStreamReader( - new FileInputStream(file), "UTF-8"); - BufferedReader bufferedReader = new BufferedReader(read); - String lineTxt = null; - boolean isread = false;// 是否读取到该行并修改 - // 将内容全部读出来,存为新的数据流 - // 读到要修改的行进行修改存入,否则原样读取存入 - StringBuffer buf = new StringBuffer(); - while ((lineTxt = bufferedReader.readLine()) != null) { - if (lineTxt.startsWith(keyname + "=")) { - buf.append(keyname + "=" + content + "\r\n"); - isread = true; - } else { - buf.append(lineTxt + "\r\n"); - } - } - read.close(); - if (!isread) {// 没有读取到,写入末尾 - buf.append(keyname + "=" + content + "\r\n"); - } - - // 把新内容覆盖写入文件 - PrintWriter out = new PrintWriter(new BufferedWriter( - new OutputStreamWriter(new FileOutputStream(path), - "UTF-8"))); - out.write(buf.toString()); - out.flush(); - out.close(); - - } else {// 不存在,创建写入 - String path2 = path.substring(0, path.replace("\\", "/").lastIndexOf("/")); - File file1 = new File(path2); - // 如果文件夹不存在则创建 - if (!file1.exists() && !file1.isDirectory()) { - file1.mkdirs(); - } - File file2 = new File(path); - if (!file2.exists()) { - file2.createNewFile(); - } - - PrintWriter out = new PrintWriter(new BufferedWriter( - new OutputStreamWriter(new FileOutputStream(path), - "UTF-8"))); - out.write(keyname + "=" + content + "\r\n"); - out.flush(); - out.close(); - } - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - /**************/ - - } - - /** - * 读取txt配置,返回map集合(文件格式:key=value,换行分隔) - * - * @param path - * 文件地址(默认D:\\scbox_settings开头) - * @return hashmap - */ - public static HashMap readSetting(ServletContext servletContext, String path) { - if(path.indexOf("./")==0) - path =path.substring(1, path.length()); - - if (servletContext == null) { - if(path.indexOf(":") <= 0&&path.indexOf("/") <0) - path = "D:\\scbox_settings\\" + path; - } else { - path = servletContext.getRealPath(path); - } - - HashMap strarr = null; - try { - File file = new File(path); - if (file.isFile() && file.exists()) { // 判断文件是否存在 - InputStreamReader read = new InputStreamReader( - new FileInputStream(file), "UTF-8"); - BufferedReader bufferedReader = new BufferedReader(read); - String lineTxt = null; - strarr = new HashMap(); - while ((lineTxt = bufferedReader.readLine()) != null) { - if(lineTxt.indexOf("#")==0){ - continue; - } - String[] arr = new String[2]; - if (lineTxt.split("=").length >= 2) { - arr[0] = lineTxt.split("=")[0]; - arr[1] = lineTxt.replace(arr[0]+"=", ""); - strarr.put(arr[0], arr[1]); - } - } - - read.close(); - } else { - strarr = null; - } - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - return strarr; - } - - - /** - * 获取配置文件中所有设置属性(含注释)
- * map.get("z") 取注释
- * map.get("k") 取key
- * map.get("v") 取value
- * - * - * @param path - * 文件地址(默认D:\\scbox_settings开头) - * - * @param t 只取以此字符开头的,不限制填null - * @param st 从以此字符开头的行开始读取,不限制填null - * @param et 读到以此字符开头的行结束,不限制填null - * @return - */ - public static ArrayList> getSettingAll(ServletContext servletContext, String path,String t,String st,String et) { - if(st==null||st.length()<1) st=""; - if(et==null||et.length()<1) et=""; - if(t==null||t.length()<1) t=""; - if(path.indexOf("./")==0) - path =path.substring(1, path.length()); - - if (servletContext == null) { - if(path.indexOf(":") <= 0&&path.indexOf("/") <0) - path = "D:\\scbox_settings\\" + path; - } else { - path = servletContext.getRealPath(path); - } - - ArrayList> list=new ArrayList<>(); - try { - File file = new File(path); - if (file.isFile() && file.exists()) { // 判断文件是否存在 - InputStreamReader read = new InputStreamReader( - new FileInputStream(file), "UTF-8"); - BufferedReader bufferedReader = new BufferedReader(read); - String lineTxt = null; - String zs="";//注释文本 - while ((lineTxt = bufferedReader.readLine()) != null) { - if((!"".equals(st))||lineTxt.indexOf(st)!=0) continue; - if((!"".equals(et))&&lineTxt.indexOf(et)==0) break; - HashMap map = new HashMap(); - if(lineTxt.indexOf("#")==0){ - zs=lineTxt; - continue; - } - String[] arr = new String[2]; - if (lineTxt.split("=").length >= 2&&lineTxt.indexOf(t)==0) { - arr[0] = lineTxt.split("=")[0]; - arr[1] = lineTxt.replace(arr[0]+"=", ""); - map.put("z", zs); - map.put("k", arr[0]); - map.put("v", arr[1]); - list.add(map); - //把注释也加进去 - zs=""; - } - } - - read.close(); - } else { - list = null; - } - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - return list; - } - - /** - * 读取txt配置文件的某一项设置值 (文件格式:key=value,换行分隔) - * - * @param path - * 文件地址 - * @param settingName - * 设置名 - * @param nullString - * 设置值为空时默认返回的内容 - * @return string - */ - public static String getSetting(ServletContext servletContext, String path, String settingName,String nullString) { - HashMap setting = ReadTxt.readSetting(servletContext,path); - String val = setting == null ? nullString : setting.get(settingName); - val = val == null ? "" : val; - return "".equals(val.trim()) ? nullString : val; - } - - /** - * 获取所有设置名以[settingName]开头的数据 - * */ - public static ArrayList getSettingW(ServletContext servletContext, String path, String settingName) { - HashMap setting = ReadTxt.readSetting(servletContext,path); - if(setting==null||setting.size()<1) return null; - Iterator> it = setting.entrySet().iterator(); - ArrayList rs=new ArrayList<>(); - while (it.hasNext()) { - Entry en=it.next(); - String k = en.getKey(); - String v = en.getValue(); - if(k.indexOf(settingName)==0){ - rs.add(k+"="+v); - } - } - - return rs; - } - - /** - * 删除某一项设置值 (文件格式:key=value,换行分隔) - * - * @param path - * 文件地址 - * @param settingName - * 设置名 - * @param nullString - * 设置值为空时默认返回的内容 - * @return string - */ - public static void delSetting(ServletContext servletContext, String path, String settingName) { - - - /**************/ - // 如果存在,则追加内容;如果文件不存在,则创建文件 - if(path.indexOf("./")==0) - path =path.substring(1, path.length()); - - if (servletContext == null) { - if(path.indexOf(":") <= 0&&path.indexOf("/") <0) - path = "D:\\scbox_settings\\" + path; - } else { - path = servletContext.getRealPath(path); - } - - try { - File file = new File(path); - if (file.isFile() && file.exists()) { // 判断文件是否存在 - InputStreamReader read = new InputStreamReader( - new FileInputStream(file), "UTF-8"); - BufferedReader bufferedReader = new BufferedReader(read); - String lineTxt = null; - // 将内容全部读出来,存为新的数据流 - // 读到要修改的行进行修改存入,否则原样读取存入 - StringBuffer buf = new StringBuffer(); - while ((lineTxt = bufferedReader.readLine()) != null) { - if (lineTxt.startsWith(settingName + "=")) { - } else { - buf.append(lineTxt + "\r\n"); - } - } - read.close(); - - // 把新内容覆盖写入文件 - PrintWriter out = new PrintWriter(new BufferedWriter( - new OutputStreamWriter(new FileOutputStream(path), - "UTF-8"))); - out.write(buf.toString()); - out.flush(); - out.close(); - - } else {// 不存在,创建 - String path2 = path.substring(0, path.replace("\\", "/").lastIndexOf("/")); - File file1 = new File(path2); - // 如果文件夹不存在则创建 - if (!file1.exists() && !file1.isDirectory()) { - file1.mkdirs(); - } - File file2 = new File(path); - if (!file2.exists()) { - file2.createNewFile(); - } - - } - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - /**************/ - - } - - - /** - * 删除设置名以[settingName]开头的数据 - * @param servletContext - * @param path - * @param settingName - */ - public static void delSettingW(ServletContext servletContext, String path, String settingName) { - - - /**************/ - // 如果存在,则追加内容;如果文件不存在,则创建文件 - if(path.indexOf("./")==0) - path =path.substring(1, path.length()); - - if (servletContext == null) { - if(path.indexOf(":") <= 0&&path.indexOf("/") <0) - path = "D:\\scbox_settings\\" + path; - } else { - path = servletContext.getRealPath(path); - } - - try { - File file = new File(path); - if (file.isFile() && file.exists()) { // 判断文件是否存在 - InputStreamReader read = new InputStreamReader( - new FileInputStream(file), "UTF-8"); - BufferedReader bufferedReader = new BufferedReader(read); - String lineTxt = null; - // 将内容全部读出来,存为新的数据流 - // 读到要修改的行进行修改存入,否则原样读取存入 - StringBuffer buf = new StringBuffer(); - while ((lineTxt = bufferedReader.readLine()) != null) { - if (lineTxt.split("=")[0].indexOf(settingName)==0) { - } else { - buf.append(lineTxt + "\r\n"); - } - } - read.close(); - - // 把新内容覆盖写入文件 - PrintWriter out = new PrintWriter(new BufferedWriter( - new OutputStreamWriter(new FileOutputStream(path), - "UTF-8"))); - out.write(buf.toString()); - out.flush(); - out.close(); - - } else {// 不存在,创建 - String path2 = path.substring(0, path.replace("\\", "/").lastIndexOf("/")); - File file1 = new File(path2); - // 如果文件夹不存在则创建 - if (!file1.exists() && !file1.isDirectory()) { - file1.mkdirs(); - } - File file2 = new File(path); - if (!file2.exists()) { - file2.createNewFile(); - } - - } - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - /**************/ - - } - - - /** - * 删除过期的所有设置值 (文件格式:key=value,换行分隔) - *
key为检测源 - * @param servletContext - * @param path 路径 - * @param d 有效天数 - */ - public static void delOutDateSetting(ServletContext servletContext, String path, int d) { - - - /**************/ - // 如果存在,则追加内容;如果文件不存在,则创建文件 - if(path.indexOf("./")==0) - path =path.substring(1, path.length()); - - if (servletContext == null) { - if(path.indexOf(":") <= 0&&path.indexOf("/") <0) - path = "D:\\scbox_settings\\" + path; - } else { - path = servletContext.getRealPath(path); - } - - try { - File file = new File(path); - if (file.isFile() && file.exists()) { // 判断文件是否存在 - InputStreamReader read = new InputStreamReader( - new FileInputStream(file), "UTF-8"); - BufferedReader bufferedReader = new BufferedReader(read); - String lineTxt = null; - // 将内容全部读出来,存为新的数据流 - // 读到要修改的行进行修改存入,否则原样读取存入 - StringBuffer buf = new StringBuffer(); - boolean ts=false; - while ((lineTxt = bufferedReader.readLine()) != null) { - - if(lineTxt.indexOf("=")>0&&lineTxt.indexOf("#")<0){ - String[] ls = lineTxt.split("="); - int has = ls[0].length()-ls[0].replaceAll("-", "").length(); - if(has>1){//日期时间 - if(Utils.dateout(ls[0], d)){ - buf.append(lineTxt + "\r\n"); - }else{ - ts=true; - }//过期 - }else{//月份时间 - buf.append(lineTxt + "\r\n"); - } - - }else{//注释或者不是setting - buf.append(lineTxt + "\r\n"); - } - - } - read.close(); - if(ts){ - // 把新内容覆盖写入文件 - PrintWriter out = new PrintWriter(new BufferedWriter( - new OutputStreamWriter(new FileOutputStream(path), - "UTF-8"))); - out.write(buf.toString()); - out.flush(); - out.close(); - } - - } else {// 不存在,创建 - String path2 = path.substring(0, path.replace("\\", "/").lastIndexOf("/")); - File file1 = new File(path2); - // 如果文件夹不存在则创建 - if (!file1.exists() && !file1.isDirectory()) { - file1.mkdirs(); - } - File file2 = new File(path); - if (!file2.exists()) { - file2.createNewFile(); - } - - } - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - /**************/ - - } - - - - /** - * 删除过期的所有设置值 (文件格式:key=value,换行分隔) - *
value为检测源 - * @param servletContext - * @param path 路径 - * @param d 有效天数 - */ - public static void delOutDateSettingValue(ServletContext servletContext, String path, int d) { - - - /**************/ - // 如果存在,则追加内容;如果文件不存在,则创建文件 - if(path.indexOf("./")==0) - path =path.substring(1, path.length()); - - if (servletContext == null) { - if(path.indexOf(":") <= 0&&path.indexOf("/") <0) - path = "D:\\scbox_settings\\" + path; - } else { - path = servletContext.getRealPath(path); - } - - try { - File file = new File(path); - if (file.isFile() && file.exists()) { // 判断文件是否存在 - InputStreamReader read = new InputStreamReader( - new FileInputStream(file), "UTF-8"); - BufferedReader bufferedReader = new BufferedReader(read); - String lineTxt = null; - // 将内容全部读出来,存为新的数据流 - // 读到要修改的行进行修改存入,否则原样读取存入 - StringBuffer buf = new StringBuffer(); - boolean ts=false; - while ((lineTxt = bufferedReader.readLine()) != null) { - - if(lineTxt.indexOf("=")>0&&lineTxt.indexOf("#")<0){ - String[] ls = lineTxt.split("="); - int has = ls[1].length()-ls[1].replaceAll("-", "").length(); - if(has>1){//日期时间 - if(Utils.dateout(ls[1], d)){ - buf.append(lineTxt + "\r\n"); - }else{ - ts=true; - }//过期 - }else{//月份时间 - buf.append(lineTxt + "\r\n"); - } - - }else{//注释或者不是setting - buf.append(lineTxt + "\r\n"); - } - - } - read.close(); - if(ts){ - // 把新内容覆盖写入文件 - PrintWriter out = new PrintWriter(new BufferedWriter( - new OutputStreamWriter(new FileOutputStream(path), - "UTF-8"))); - out.write(buf.toString()); - out.flush(); - out.close(); - } - - } else {// 不存在,创建 - String path2 = path.substring(0, path.replace("\\", "/").lastIndexOf("/")); - File file1 = new File(path2); - // 如果文件夹不存在则创建 - if (!file1.exists() && !file1.isDirectory()) { - file1.mkdirs(); - } - File file2 = new File(path); - if (!file2.exists()) { - file2.createNewFile(); - } - - } - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - /**************/ - - } - - - /** - * 删除全部内容 - * - * @param path - * 文件地址 - * @param nullString - * 设置值为空时默认返回的内容 - * @return string - */ - public static void delAll(ServletContext servletContext, String path) { - - - /**************/ - // 如果存在,则追加内容;如果文件不存在,则创建文件 - if(path.indexOf("./")==0) - path =path.substring(1, path.length()); - - if (servletContext == null) { - if(path.indexOf(":") <= 0&&path.indexOf("/") <0) - path = "D:\\scbox_settings\\" + path; - } else { - path = servletContext.getRealPath(path); - } - - try { - File file = new File(path); - if (file.isFile() && file.exists()) { // 判断文件是否存在 - - // 把新内容覆盖写入文件 - PrintWriter out = new PrintWriter(new BufferedWriter( - new OutputStreamWriter(new FileOutputStream(path), - "UTF-8"))); - out.write("".toString()); - out.flush(); - out.close(); - - } else {// 不存在,创建 - String path2 = path.substring(0, path.replace("\\", "/").lastIndexOf("/")); - File file1 = new File(path2); - // 如果文件夹不存在则创建 - if (!file1.exists() && !file1.isDirectory()) { - file1.mkdirs(); - } - File file2 = new File(path); - if (!file2.exists()) { - file2.createNewFile(); - } - - } - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - /**************/ - - } - - - - /** - * 将InputStream装换成某种字符编码的String - * - * @param in - * @param encoding - * @return - */ - public static String InputStreamTOString(InputStream in, String encoding) { - int BUFFER_SIZE = 4096; - String res = null; - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - byte[] data = new byte[BUFFER_SIZE]; - int count = -1; - try { - while ((count = in.read(data, 0, BUFFER_SIZE)) != -1) { - outputStream.write(data, 0, count); - } - } catch (Exception e) { - e.printStackTrace(); - } - try { - res = new String(outputStream.toByteArray(), encoding); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } - return res; - } - - -}