本篇原創,轉載請注明網址,謝謝!
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(); } }