本篇原创,转载请注明网址,谢谢!
1 文件生成____根据路径生成文件
1.1 github网址
1.2 相关功能
根据eclipse拿到的相对路径生成相关的文件夹和文件
1.3 相关代码
CreateFolderAndFileTest
package com.imooc.coupon; import lombok.extern.slf4j.Slf4j; import java.io.*; /** * CreateFolderAndFileTest * * @author 魏豆豆 * @date 2021/6/25 */ @Slf4j public class CreateFolderAndFileTest { //分别定义字符串目录文件路径,源文件前缀路径,生成文件前缀路径,和目录文件编码。使用时记得初始化 private final String contentPath,sourcePre,targetPre,charset; public CreateFolderAndFileTest(){ contentPath = "C:/Users/weijingli/Desktop/aaa/aaa.txt"; sourcePre = "F:/kewai"; targetPre = "C:/Users/weijingli/Desktop"; charset = "GBK"; } /** * 读取文件处理 * @param args * @throws IOException */ public static void main(String[] args) throws IOException { CreateFolderAndFileTest test = new CreateFolderAndFileTest(); File contentFile = new File(test.contentPath); if(!contentFile.getParentFile().exists()){ log.error("目录文件不存在!"); return; }else{ FileInputStream contentStream = new FileInputStream(contentFile); InputStreamReader isr = new InputStreamReader(contentStream, test.charset); BufferedReader br = new BufferedReader(isr); String lineText; while((lineText=br.readLine())!=null){ test.lineHandle(lineText); } } } /** * 每行处理,将字符串处理成文件过程 * @param commonPath */ public void lineHandle(String commonPath){ File sourceFile,targetFile; sourceFile = new File(sourcePre+commonPath); targetFile = new File(targetPre+commonPath); if(!targetFile.getParentFile().exists()){ targetFile.getParentFile().mkdirs(); } copyFile(sourceFile,targetFile); } /** * copy文件处理 */ public void copyFile(File sourceFile,File targetFile){ try { FileInputStream in = new FileInputStream(sourceFile); FileOutputStream out = new FileOutputStream(targetFile); byte[] bs = new byte[1024]; int count = 0; while(-1!=(count=in.read(bs,0,bs.length))){ out.write(bs,0,count); } in.close(); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } } }
2 文件上传____原生方法上传服务器
2.1 针对问题:
针对文件从windows上传时是windows路径,linux环境无此路径报错问题
2.2 需要引入资源:
commons-fileupload-1.2.1.jar和commons-io-1.3.2.jar
2.3 相关代码
index.jsp(前台展示):
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>文件测试界面</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> </head> <body> <div align="center"> <form action="ddd" enctype="multipart/form-data" method="post"> 名称:<input name="name" /> <br> 图片:<input name="img" type="file"/><br> <input type="submit" value="提交" /> <input type="reset" value="重置" /> </form> </div> </body> </html>
web.xml:(servlet处理)
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>CommonUtils</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>UploadServlet</servlet-name> <servlet-class>com.ddwei.file.Upload.UploadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UploadServlet</servlet-name> <url-pattern>/ddd</url-pattern> </servlet-mapping> </web-app>
UploadServlet.java
package com.ddwei.file.Upload; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import java.util.UUID; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; public class UploadServlet extends HttpServlet { /** * Constructor of the object. */ public UploadServlet() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); DiskFileItemFactory sf= new DiskFileItemFactory();//实例化磁盘被文件列表工厂 String path = request.getRealPath("/aaa");//得到上传文件的存放目录 sf.setRepository(new File(path));//设置文件存放目录 sf.setSizeThreshold(1024*1024);//设置文件上传小于1M放在内存中 String rename = "";//文件新生成的文件名 String fileName = "";//文件原名称 String name = "";//普通field字段 //从工厂得到servletupload文件上传类 ServletFileUpload sfu = new ServletFileUpload(sf); try { List<FileItem> lst = sfu.parseRequest(request);//得到request中所有的元素 for (FileItem fileItem : lst) { if(fileItem.isFormField()){ if("name".equals(fileItem.getFieldName())){ name = fileItem.getString("UTF-8"); } }else{ //获得文件名称 fileName = fileItem.getName(); fileName = fileName.substring(fileName.lastIndexOf("\\")+1); String houzhui = fileName.substring(fileName.lastIndexOf(".")); rename = UUID.randomUUID()+houzhui; fileItem.write(new File(path, rename)); } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("普通字段"+name); System.out.println("文件名称"+fileName); System.out.println("修改后生成的文件名称"+rename); response.sendRedirect("ok.jsp"); out.flush(); out.close(); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } }
3 文件上传____SpringBoot
3.1 针对问题:
小文件上传
3.2 相关代码:
hello.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/imooc/upload" method="post" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" value="上传"> </form> </body> </html>
java类:
package com.imooc.springboot.application.upload; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.File; /** * FileUploadController * * @author 魏豆豆 * @date 2021/7/28 */ @Controller public class FileUploadController { @RequestMapping("/oneFile") public String index(){ return "upload"; } @RequestMapping("/upload") @ResponseBody public String upload(HttpServletRequest req, MultipartFile file){ try{ String uploadDir = req.getSession().getServletContext().getRealPath("/")+"upload/"; File dir = new File(uploadDir); if(!dir.exists()){ dir.mkdir(); } FileUtil.executeUpload(uploadDir,file); }catch(Exception e){ e.printStackTrace(); return "上传失败"; } return "上传成功"; } }
调用类:
package com.imooc.springboot.application.upload; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.util.UUID; public class FileUtil { public static void executeUpload(String uploadDir, MultipartFile file) throws Exception{ //文件后缀 String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); //文件随机名 String filename = UUID.randomUUID()+suffix; //创建文件对象 File serverFile = new File(uploadDir + filename); //转储文件 file.transferTo(serverFile); } }
application.yml
spring:
# profiles:
# active: prod
#注意:这里不能有profiles active: dev,否则 按application-dev配置文件的端口号
# active: dev
application:
name: imooc_springboot_study
server:
#端口号
port: 8081
servlet:
context-path: /imooc
com:
imooc:
userid: 110
username: aaa
management:
endpoint:
shutdown:
enabled: true # 最特殊的监控端点,开通后可以通过shutdown url对程序进行关闭动作。一般不会开启
endpoints:
web:
exposure:
include: "*" # 打开所有端点
#127.0.0.1:8081/imooc/actuator/
info:
app:
name: imooc_springboot_study
groupid: org.springframework.boot
version: 2.1.4.RELEASE
servlet: multipart: max-file-size: 10MB max-request-size: 100MB
4 文件上传____SpringBoot+ajax
4.1 需要注意:
引入jquery.js
4.2 相关代码:
index2.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/jquery.min.js"></script> </head> <script type="text/javascript"> function uploadFile() { var file = $("#file")[0].files[0]; var formData = new FormData(); formData.append("file",file); $.ajax({ type:'post', url:'/imooc/upload', processData: false, contentType:false, data:formData, success:function (msg) { $("#result").html(msg); } }) } </script> <body> <div id="result"></div> <input type="file" id="file"> <input type="button" value="上传" onclick="uploadFile()"> </body> </html>
java类
package com.imooc.springboot.application.upload; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.File; /** * FileUploadController * * @author 魏豆豆 * @date 2021/7/28 */ @Controller public class FileUploadController { @RequestMapping("/oneFile") public String index(){ return "upload"; } @RequestMapping("/upload") @ResponseBody public String upload(HttpServletRequest req, MultipartFile file){ try{ String uploadDir = req.getSession().getServletContext().getRealPath("/")+"upload/"; File dir = new File(uploadDir); if(!dir.exists()){ dir.mkdir(); } FileUtil.executeUpload(uploadDir,file); }catch(Exception e){ e.printStackTrace(); return "上传失败"; } return "上传成功"; } }
引用类:
package com.imooc.springboot.application.upload; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.util.UUID; public class FileUtil { public static void executeUpload(String uploadDir, MultipartFile file) throws Exception{ //文件后缀 String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); //文件随机名 String filename = UUID.randomUUID()+suffix; //创建文件对象 File serverFile = new File(uploadDir + filename); //转储文件 file.transferTo(serverFile); } }
5 文件上传____ftp上传单文件
5.1 自备jar包
需要commons-net-ftp jar包,我已经上传百度云盘,大家可以下载
https://pan.baidu.com/s/1dbsbaZ48o4zhmCdTRxhj6g
密码:aqg0
5.2 相关代码
GetFtpFile.java
package com.ddwei.file.Upload.ftp; /** * Description:将数据文件上传FTP服务器指定文件 */ import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import org.apache.commons.net.ftp.FTP; public class GetFtpFile { private String exportDate = ""; public int execute() { exportDate = "2021/07/29"; // 数据日期 String epxortDateNorm = exportDate.replace("/", ""); // 获取生成的打包完后的.rar路径 System.out.println("-----getftpfile===" + epxortDateNorm); String path = System.getProperty("user.dir") + "/export/"; String tar = "20210729" + "_103.tar"; String txt = "103_" + "demo" + ".ok"; // FTP上传文件 File srcFile = new File(path + tar); // 本地的文件路径 System.out.println("----------------------开始上传文件===" + srcFile); File srcFile1 = new File(path + txt); // 本地的文件路径 if (!srcFile1.exists()) try { srcFile1.createNewFile(); } catch (IOException e1) { e1.printStackTrace(); } System.out.println("----------------------开始上传文件===" + srcFile1); FileInputStream fis,fis1; try { fis = new FileInputStream(srcFile); fis1 = new FileInputStream(srcFile1); FtpFile ff = new FtpFile(); // 输入正确的FTP的IP,用户名,密码,服务器路径 ff.uploadFile("127.0.0.1", 21, "ftpput", "ftpput", "/ftpput/aaa/STD/CM", tar, fis, FTP.BINARY_FILE_TYPE); System.out.print("----------------------上传成功"); ff.uploadFile("127.0.0.1", 21, "ftpput", "ftpput", "/ftpput/aaa/STD/CM", txt, fis1, FTP.BINARY_FILE_TYPE); System.out.print("----------------------上传成功"); } catch (FileNotFoundException e) { e.printStackTrace(); System.out.print("----------------------上传失败"); } return 1; } }
FtpFile.java
package com.ddwei.file.Upload.ftp; /* * Description:将数据文件上传FTP服务器指定文件 */ import java.io.IOException; import java.io.InputStream; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPReply; public class FtpFile { /** * Description: 向FTP服务器上传文件 * @param url FTP服务器hostname * @param port FTP服务器端口 * @param username FTP登录账号 * @param password FTP登录密码 * @param path FTP服务器保存目录 * @param filename 上传到FTP服务器上的文件名 * @param input 输入流 * @return 成功返回true,否则返回false */ public boolean uploadFile(String url, int port, String username, String password, String path, String filename, InputStream input) { return uploadFile(url,port,username,password,path,filename,input,FTP.BINARY_FILE_TYPE); } /** * Description: 向FTP服务器上传文件 * @param url FTP服务器hostname * @param port FTP服务器端口 * @param username FTP登录账号 * @param password FTP登录密码 * @param path FTP服务器保存目录 * @param filename 上传到FTP服务器上的文件名 * @param input 输入流 * @return 成功返回true,否则返回false */ public boolean uploadFile(String url, int port, String username, String password, String path, String filename, InputStream input,int iFileType) { // 初始表示上传失败 boolean success = false; // 创建FTPClient对象 FTPClient ftp = new FTPClient(); try { int reply; // 连接FTP服务器 // 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器 ftp.connect(url, port); // 登录ftp ftp.login(username, password); // 看返回的值是不是230,如果是,表示登陆成功 reply = ftp.getReplyCode(); System.out.println("reply="+reply); // 以2开头的返回值就会为真 if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return success; } ftp.setFileType(iFileType); // 转到指定上传目录 ftp.changeWorkingDirectory(path); // 将上传文件存储到指定目录 ftp.storeFile(filename, input); // 关闭输入流 input.close(); // 退出ftp ftp.logout(); // 表示上传成功 success = true; } catch (IOException e) { e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } return success; } /** * Description: 从FTP服务器下载文件 * @param url FTP服务器hostname * @param port FTP服务器端口 * @param username FTP登录账号 * @param password FTP登录密码 * @param remotePath FTP服务器上的相对路径 * @param fileName 要下载的文件名 * @param localPath 下载后保存到本地的路径 * @return */ /* public boolean downFile(String url, int port, String username, String password, String remotePath, String fileName, String localPath) { // 初始表示下载失败 boolean success = false; // 创建FTPClient对象 FTPClient ftp = new FTPClient(); try { int reply; // 连接FTP服务器 // 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器 ftp.connect(url, port); // 登录ftp ftp.login(username, password); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return success; } // 转到指定下载目录 ftp.changeWorkingDirectory(remotePath); // 列出该目录下所有文件 FTPFile[] fs = ftp.listFiles(); // 遍历所有文件,找到指定的文件 for (FTPFile ff : fs) { if (ff.getName().equals(fileName)) { // 根据绝对路径初始化文件 File localFile = new File(localPath + "/" + ff.getName()); // 输出流 OutputStream is = new FileOutputStream(localFile); // 下载文件 ftp.retrieveFile(ff.getName(), is); is.close(); } } // 退出ftp ftp.logout(); // 下载成功 success = true; } catch (IOException e) { e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { ioe.printStackTrace(); } } } return success; } */ }
6 文件上传____ftp上传多文件
6.1 注意事项:
需要 jsch-0.1.53.jar(这个jar包maven里有),实在找不到的可以留言联系我
6.2 相关代码
主类:
package com.ddwei.file.ftp; import java.io.File; /** * SFTP上传本地图像到远程服务器 */ public class UploadAssetImageFile { private final int SFTP_PORT = 22; public String uploadByFTP() throws Exception{ String result = ""; //2.将本地文件上传 String localPath = "C:"+File.separator+"aaa";//本地文件夹路径 File filePath = new File(localPath); File [] files = filePath.listFiles(); String filePaths = ""; if (files.length > 0) { for (File f : files) { filePaths +=localPath +File.separator+ f.getName() + ","; } if (null != filePaths && filePaths.length() > 0) { filePaths = filePaths.substring(0,filePaths.length() - 1); } }else { System.out.println("文件夹下文件为空"); } //3.调用FTP服务 /** * 参数: * 1.远程路径 :/upload/52业务流水号/文件名.jpg * 2.本地路径 * 3.远程IP * 4.远程端口 * 5.远程用户 * 6.远程用户密码 * 7.上传模式 * 8.文件 */ try{ System.out.println("本地路径localpath================"+localPath); System.out.println("remotePaht==============REMOTE_PATH"+File.separator+"ywls"); System.out.println("files================"+filePaths); String YWserialNo = "ywls"; //上传到sftp result = uploadToSftp(YWserialNo,filePaths); try { Thread.sleep(3000);//睡眠三秒 } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } if (result.equals(CodeConstant.FAIL)) { System.out.println("文件上传SFTP服务器失败"); return "文件上传SFTP服务器失败"; } else { //调用文件上传成功通知接口 //删除本地文件 this.deleteDir(filePath); result = CodeConstant.SUCCESS; } } catch (Exception e) { e.printStackTrace(); System.out.println("文件上传SFTP服务器失败"); return "文件上传SFTP服务器失败"; } return result; } public String uploadToSftp(String ywserialNo,String filePaths){ String result = CodeConstant.FAIL; String REMOTE_IP = "127.0.0.1"; String REMOTE_USER = "REMOTE_USER"; String REMOTE_PASSWORD = "REMOTE_PASSWORD"; String REMOTE_PATH = "REMOTE_PATH"; SFTPUtil sftp = new SFTPUtil(REMOTE_IP,REMOTE_USER,REMOTE_PASSWORD,SFTP_PORT); try { sftp.connect(); String [] paths = filePaths.split(","); for (String localFile : paths) { sftp.upload(REMOTE_PATH+ywserialNo, localFile); Thread.sleep(1000); } result = CodeConstant.SUCCESS; } catch (Exception e) { e.printStackTrace(); System.out.println("SFTP服务器连接失败"); } return result; } /* * 递归删除文件 */ public boolean deleteDir(File dir){ if (dir.isDirectory()) { File [] files = dir.listFiles(); for (File fi : files) { if (fi.isDirectory()) { //递归调用,删除文件夹 deleteDir(fi); } if (fi.isDirectory() && fi.length() == 0) { fi.delete(); } if (fi.isFile()) { fi.delete(); } } }else { System.out.println("此文件不是目录"); } return dir.delete(); } }
工具类:
package com.ddwei.file.ftp; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.Properties; import com.jcraft.jsch.Channel; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.JSch; import com.jcraft.jsch.Session; import com.jcraft.jsch.SftpException; public class SFTPUtil { private String host; private String username; private String password; private int port = 22; private ChannelSftp sftp = null; /** * 指定端口 * @param host * @param username * @param password * @param port */ public SFTPUtil(String host,String username,String password,int port){ this.host = host; this.username = username; this.password = password; this.port = port; } /** * 默认端口 * @param host * @param username * @param password */ public SFTPUtil(String host,String username,String password){ this.host = host; this.username = username; this.password = password; } /** * connect server via sftp */ public void connect() throws Exception{ JSch jsch = new JSch(); Session sshSession = jsch.getSession(username, host, port); System.out.println("Session created."); sshSession.setPassword(password); Properties sshConfig = new Properties(); sshConfig.put("StrictHostKeyChecking", "no"); sshSession.setConfig(sshConfig); sshSession.connect(); System.out.println("Session connected."); System.out.println("Opening Channel."); Channel channel = sshSession.openChannel("sftp"); channel.connect(); sftp = (ChannelSftp) channel; System.out.println("Connected to " + host + "."); } /** * Disconnect with server */ public void disconnect() { if(this.sftp != null){ if(this.sftp.isConnected()){ this.sftp.disconnect(); }else if(this.sftp.isClosed()){ System.out.println("sftp is closed already"); } } } /** * @param remote 远程文件路径 * @param downloadFile 远程文件名 * @param saveFile 本地文件绝对路径文件 * @throws Exception */ public void download(String remote, String downloadFile,String localFile) throws Exception{ sftp.cd(remote); File file = new File(localFile); FileOutputStream os = new FileOutputStream(file); sftp.get(downloadFile, os); os.close(); } /** * * @param remote 远程文件路径 * @param localFile 本地文件绝对路径文件 * @throws Exception */ public void upload(String remote,String localFile) throws Exception{ mkdir(remote); sftp.cd(remote); File rfile = new File(localFile); String filename = rfile.getName(); FileInputStream is = new FileInputStream(localFile); this.sftp.put(is, filename); is.close(); } /** * create remote * @param filepath * @param sftp */ private void mkdir(String filepath) throws Exception{ File file = new File(filepath); String ppath = file.getParent(); try { this.sftp.cd(filepath); } catch (SftpException e1) { mkdir(ppath); this.sftp.cd(ppath); this.sftp.mkdir(filepath); this.sftp.cd(filepath); } } }
代码常量类:
package com.ddwei.file.ftp; /** * 类描述:代码常量类(系统中使用的所有代码需要在此处维护) */ public class CodeConstant { /*********************** 常量定义区域 *********************************/ /** 成功 **/ public final static String SUCCESS = "SUCCESS"; /** 失败 **/ public final static String FAIL = "FAIL"; }
7 文件下载____cd上传下载
7.1 注意事项
a 需要jar包
我的百度网盘:https://pan.baidu.com/s/1EApbC5APLuMpURsjqcZIig
密码:4olm
b 上传下载的时候ip 写自己的,不是对方的
c 需要开通权限(填写表)
7.2 相关代码
cd下载
public static void main(String[] args) { CDTransParam param = new CDTransParam("10.1.4.3", "1366", "cdadm", "password", "/home/cdadm/ttt.txt", "/home/cdadm/11.txt", "CDIISRV", "unix", "unix"); String a = getProcessFile(param, "put"); System.out.println(a); }
cd上传(txt文档,同一行 不同字段用小方格分开,注意文件最后一个字段必须有值)
package com.ddwei.file.cd; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigDecimal; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.cd.invoke.CDConstants; import com.cd.invoke.CDTransParam; import com.cd.invoke.CDTransfer; public class EcifUpdateToLoan { private PreparedStatement pstmt0 = null; //通用sql查询 private String updateDate;//获取前一天时间 不带/ public int execute() { int initResult = init(); if(TaskConstants.ES_FAILED == initResult){ return TaskConstants.ES_FAILED; } int iResult = 1; String sRemoteFileName = "",sLocalFileName = "",sLogName = ""; //1.更新表 sRemoteFileName = "remote"; sLocalFileName = "local"; sLogName = "客户信息"; iResult = handlEntInfo(sRemoteFileName,sLocalFileName,sLogName); if(TaskConstants.ES_SUCCESSFUL!=iResult){ System.out.println("------------------同步变更"+sLogName+"失败------------------"); return TaskConstants.ES_FAILED; } return TaskConstants.ES_SUCCESSFUL; } /** * 1 处理客户信息列表 */ public int handlEntInfo(String sRemoteFileName,String sLocalFileName,String sLogName){ String mfCustomerId = null,customerId; //【1】.获取并创建文件、路径 System.out.println("------------------1.获取"+sLogName+".获取文件开始------------------"); String fpath = "/ccc/bbb/aaa"+"/"+updateDate+"/"+sRemoteFileName+updateDate+".txt";//远程路径 String tpath = "C:/Users/John/Documents/aaa.txt";//本地路径 File file = new File(tpath); if(!file.getParentFile().exists()){ file.getParentFile().mkdirs(); System.out.println(file.getParentFile()); } System.out.println("------------------2.获取"+sLogName+".获取文件路径:fpath:"+fpath+" , tpath:"+tpath+"------------------"); //【2】.通过java程序调用C:D完成文件传输 CDTransParam param = new CDTransParam( "10.1.4.3", "1366", "cdadm", "password", fpath, tpath, "CDIISRV", CDConstants.UNIX, CDConstants.UNIX); CDTransfer.execute(param,CDConstants.DIRECTION_GET); if(!file.exists()){ System.out.println("CD获取文件失败!"); return TaskConstants.ES_FAILED; } System.out.println("------------------3.获取"+sLogName+".获取文件结束------------------"); //【3】.读取并更新数据 int count = 0; try { System.out.println("------------------5.获取"+sLogName+".读取文件------------------"); if(file!=null&&file.exists()){ FileInputStream sFileInputStream = new FileInputStream(file); InputStreamReader reader = new InputStreamReader(sFileInputStream, "GBK"); BufferedReader bufferedReader = new BufferedReader(reader); StringBuffer stringBuffer = new StringBuffer(); String lineText = null; while ((lineText = bufferedReader.readLine()) != null) { List<String[]> array = new ArrayList<String[]>(); count++; String[] record = lineText.split(""); // 读取数据以□分割 String varible1 = NullToString(record[9]); String varible2 = NullToString(record[14]); String varible3 = NullToString(record[16]); String registerCapitalEcif = NullToString(record[21]); // 注册资本 mfCustomerId = NullToString(record[30]); //1.2.0 Double 注册资本 单位转换 if(!"".equals(registerCapitalEcif)){ BigDecimal bRegistercapital = new BigDecimal(registerCapitalEcif); BigDecimal bParam = new BigDecimal("10000"); bRegistercapital = bRegistercapital.divide(bParam,4,BigDecimal.ROUND_HALF_UP); registerCapitalEcif = bRegistercapital.toPlainString(); } customerId = getCustomerID(mfCustomerId); //客户编号 //1.2.1 日期格式转换 stringBuffer.setLength(0); varible2 = ((varible2.length()==8)?stringBuffer.append(varible2).insert(4, "/").insert(7, "/").toString():varible2); stringBuffer.setLength(0); varible3 = ((varible3.length()==8)?stringBuffer.append(varible3).insert(4, "/").insert(7, "/").toString():varible3); //1.2.3 异常标识 该条记录停止 if("FAIL".equals(customerId)){ return TaskConstants.ES_FAILED; } //1.2.4 判断标识 boolean bWhiteAccessFlag = false; //白名单标识 boolean bsCustomerIDFlag = false; //客户编号标识 if(!"".equals(customerId)){ bsCustomerIDFlag = true; } if(bWhiteAccessFlag && bsCustomerIDFlag){ String stateTypeLoan = "",registerCapitalLoan = ""; String sql = "select column2 from TableName where column1 = ? "; ResultSet rsQuery = null; Connection conn = DriverManager.getConnection("url","userId","passWord");;; pstmt0 = conn.prepareStatement(sql); pstmt0.setString(1, customerId); rsQuery = pstmt0.executeQuery(); if(rsQuery.next()){ stateTypeLoan = NullToString(rsQuery.getString(1)); } rsQuery.close(); if(pstmt0!=null)pstmt0.close(); conn.close(); if(!stateTypeLoan.equals(varible1)){ array.add(new String[]{"statetype",stateTypeLoan,varible1}); } //注册资本处理 if("".equals(registerCapitalEcif)){ array.add(new String[]{"registercapital",registerCapitalLoan,registerCapitalEcif}); }else{ BigDecimal registerCapitalLoanBig = new BigDecimal(registerCapitalLoan); BigDecimal registerCapitalEcifBig = new BigDecimal(registerCapitalEcif); if(registerCapitalLoanBig.compareTo(registerCapitalEcifBig)!=0){ array.add(new String[]{"registercapital",registerCapitalLoan,registerCapitalEcif}); } } } } handleEnd(reader,bufferedReader,sFileInputStream); }else{ System.out.println("------------------未找到文件,不进行状态更新------------------"); } } catch (FileNotFoundException e) { System.out.println("需要读取的文件没有找到"); e.printStackTrace(); return TaskConstants.ES_FAILED; } catch (IOException e) { System.out.println("IO异常"); e.printStackTrace(); return TaskConstants.ES_FAILED; } catch (Exception e) { System.out.println("处理异常"); e.printStackTrace(); return TaskConstants.ES_FAILED; } return TaskConstants.ES_SUCCESSFUL; } public String getSerialNo(String sTableName,String sKey){ return "aaa"; } /** * @param aaa * @return */ public String getCustomerID(String aaa){ return aaa; } /** * 将空值转换为空串 * @param sStr * @return */ public static String NullToString(String sStr){ if(sStr==null){ sStr = ""; }else if(sStr.equals(" ")){//将空格转换为空串 sStr = ""; }else{ return sStr; } return sStr; } public int init(){ //初始化当天日期 updateDate = "20210729"; return 1; } /** * 处理关闭IO * @param reader * @param bufferedReader * @param sFileInputStream * @throws IOException */ public void handleEnd(InputStreamReader reader,BufferedReader bufferedReader,FileInputStream sFileInputStream) throws IOException{ if(reader != null){ reader.close(); reader = null; } if(bufferedReader != null){ bufferedReader.close(); bufferedReader = null; } if(sFileInputStream != null){ sFileInputStream.close(); sFileInputStream = null; } } }
package com.ddwei.file.cd; public class TaskConstants { public TaskConstants() { } public static final int ES_UNKNOWN = -1; public static final int ES_UNEXECUTE = 0; public static final int ES_SUCCESSFUL = 1; public static final int ES_FAILED = 2; public static final int ES_WARNING = 3; public static final int TS_INACTIVE = 0; public static final int TS_WAIT = 1; public static final int TS_RUNNING = 2; public static final int TS_FINISHED = 3; }
8 文件上传____图片 base64加密
8.1 注意事项
引入阿里巴巴的fastjson.jar
base64原理:
https://blog.csdn.net/wodeyuer125/article/details/45150223
8.2 相关代码
package com.ddwei.pic.base64; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.Socket; import java.text.SimpleDateFormat; import java.util.Date; import com.alibaba.fastjson.JSONObject; public class folekaifa { /** * @param args */ public static void main(String[] args) { String result = null; try { //1.1 生成Base64流 byte[] imgData = readFileByBytes("C:\\Users\\weijingli\\Desktop\\220254.jpg"); String imgStr = encode(imgData); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); String mas = "{\"MsgRtrInfo\":{\"MRIPartyId\":\"1234\",\"MRIVer\":\"1.0.0\",\"MRIRqSysName\":\"FNMS\",\"MRISrvSysName\":\"OOPS\",\"MRITrnCode\":\"0660001133\",\"MRIMsgSndDate\":\"20190225\",\"MRIMsgSndTime\":\"101849000000\",\"MRIMsgId\":\"08010020190225109516\",\"MRIMsgDrct\":\"2\"},\"CmnRsInfo\":{\"RQIFstSysName\":\"FNMS\",\"RQIFstSysDate\":\"20190225\",\"RQIFstSysTime\":\"101849000000\",\"RQIFstSysSN\":\"BSCP2019022508010001292456\",\"RQIRqDate\":\"20200624\",\"RQIRqTime\":\"101849\",\"RQIRqSN\":\"BSCP2019022508010001292456\",\"RQIRqBrNo\":\"080100\",\"RQIRqTeNo\":\"00851\"},\"DevInfo\":{\"DIDevNo\":\"0049002E3336510F37\"},\"CmnRqInfo\":{\"RQIRqSubSysName\":\"OOPS_1\",\"RQIRqDate\":\"20200610\",\"RQIRqTime\":\"222222\",\"RQIRqSN\":\"NC0000000099\"},\"SecInfo\":{},\"BizInfo\":{\"TRANSNO\":\"" + dateFormat.format(new Date())+ "\",\"ECMID\":\"1.jpg\",\"TYPE\":\"0\",\"LINK\":\"2\",\"IMGDATA\":\""+imgStr+"\",\"VOUCODE\":\"01\",\"BI\":\"\",\"BII\":\"\"}}"; JSONObject json = JSONObject.parseObject(mas); String sl = (mas.getBytes("UTF-8")).length + ""; if (sl.length() < 8) { while (true) { sl = "0" + sl; if (sl.length() == 8) { break; } } } System.out.println(sl + mas); //1.2 解析base64流 // ip和端口可能需要改 Socket socket = new Socket("127.0.0.1", 1133); socket.setSoTimeout(Integer.valueOf("60000000")); BufferedWriter pw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8")); InputStream in = socket.getInputStream(); pw.write(sl + mas); pw.flush(); BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8")); String returnMsg = br.readLine(); System.out.println(returnMsg); } catch (Exception e) { System.out.println(e); } } // 读取图片 public static byte[] readFileByBytes(String filePath) throws IOException { File file = new File(filePath); if (!file.exists()) { throw new FileNotFoundException(filePath); } else { ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length()); BufferedInputStream in = null; try { in = new BufferedInputStream(new FileInputStream(file)); short bufSize = 1024; byte[] buffer = new byte[bufSize]; int len1; while (-1 != (len1 = in.read(buffer, 0, bufSize))) { bos.write(buffer, 0, len1); } byte[] var7 = bos.toByteArray(); return var7; } finally { try { if (in != null) { in.close(); } } catch (IOException var14) { var14.printStackTrace(); } bos.close(); } } } // base64编码 private static final char last2byte = (char) Integer.parseInt("00000011", 2); private static final char last4byte = (char) Integer.parseInt("00001111", 2); private static final char last6byte = (char) Integer.parseInt("00111111", 2); private static final char lead6byte = (char) Integer.parseInt("11111100", 2); private static final char lead4byte = (char) Integer.parseInt("11110000", 2); private static final char lead2byte = (char) Integer.parseInt("11000000", 2); private static final char[] encodeTable = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'}; public static String encode(byte[] from) { StringBuilder to = new StringBuilder((int) ((double) from.length * 1.34D) + 3); int num = 0; char currentByte = 0; int i; for (i = 0; i < from.length; ++i) { for (num %= 8; num < 8; num += 6) { switch (num) { case 0: currentByte = (char) (from[i] & lead6byte); currentByte = (char) (currentByte >>> 2); case 1: case 3: case 5: default: break; case 2: currentByte = (char) (from[i] & last6byte); break; case 4: currentByte = (char) (from[i] & last4byte); currentByte = (char) (currentByte << 2); if (i + 1 < from.length) { currentByte = (char) (currentByte | (from[i + 1] & lead2byte) >>> 6); } break; case 6: currentByte = (char) (from[i] & last2byte); currentByte = (char) (currentByte << 4); if (i + 1 < from.length) { currentByte = (char) (currentByte | (from[i + 1] & lead4byte) >>> 4); } } to.append(encodeTable[currentByte]); } } if (to.length() % 4 != 0) { for (i = 4 - to.length() % 4; i > 0; --i) { to.append("="); } } return to.toString(); } }