zoukankan      html  css  js  c++  java
  • java:工具(汉语转拼音,压缩包,EXCEL,JFrame窗口和文件选择器,SFTP上传下载,FTP工具类,SSH)

    1.汉语转拼音:

    import net.sourceforge.pinyin4j.PinyinHelper;
    import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
    import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
    import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
    import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
    import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
    
    public class Test {
    
        /** 
         * 将文字转为汉语拼音
         * @param chineselanguage 要转成拼音的中文
         */
        public static String toHanyuPinyin(String ChineseLanguage){
            char[] cl_chars = ChineseLanguage.trim().toCharArray();
            String hanyupinyin = "";
            HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
            defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);// 输出拼音全部小写
            defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);// 不带声调
            defaultFormat.setVCharType(HanyuPinyinVCharType.WITH_V) ;
            try {
                for (int i=0; i<cl_chars.length; i++){
                    if (String.valueOf(cl_chars[i]).matches("[u4e00-u9fa5]+")){// 如果字符是中文,则将中文转为汉语拼音
                        hanyupinyin += PinyinHelper.toHanyuPinyinStringArray(cl_chars[i], defaultFormat)[0];
                    } else {// 如果字符不是中文,则不转换
                        hanyupinyin += cl_chars[i];
                    }
                }
            } catch (BadHanyuPinyinOutputFormatCombination e) {
                System.out.println("字符不能转成汉语拼音");
            }
            return hanyupinyin;
        }
        
        /**
         * 首字母全大写
         * @param ChineseLanguage
         * @return
         */
        public static String getFirstLettersUp(String ChineseLanguage){
            return getFirstLetters(ChineseLanguage ,HanyuPinyinCaseType.UPPERCASE);
        }
        /**
         * 首字母全小写
         * @param ChineseLanguage
         * @return
         */
        public static String getFirstLettersLo(String ChineseLanguage){
            return getFirstLetters(ChineseLanguage ,HanyuPinyinCaseType.LOWERCASE);
        }
        
        public static String getFirstLetters(String ChineseLanguage,HanyuPinyinCaseType caseType) {
            char[] cl_chars = ChineseLanguage.trim().toCharArray();
            String hanyupinyin = "";
            HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
            defaultFormat.setCaseType(caseType);// 输出拼音全部大写
            defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);// 不带声调
            try {
                for (int i = 0; i < cl_chars.length; i++) {
                    String str = String.valueOf(cl_chars[i]);
                    if (str.matches("[u4e00-u9fa5]+")) {// 如果字符是中文,则将中文转为汉语拼音,并取第一个字母
                        hanyupinyin += PinyinHelper.toHanyuPinyinStringArray(cl_chars[i], defaultFormat)[0].substring(0, 1);
                    } else if (str.matches("[0-9]+")) {// 如果字符是数字,取数字
                        hanyupinyin += cl_chars[i];
                    } else if (str.matches("[a-zA-Z]+")) {// 如果字符是字母,取字母
                        hanyupinyin += cl_chars[i];
                    } else {// 否则不转换
                        hanyupinyin += cl_chars[i];//如果是标点符号的话,带着
                    }
                }
            } catch (BadHanyuPinyinOutputFormatCombination e) {
                System.out.println("字符不能转成汉语拼音");
            }
            return hanyupinyin;
        }
        
       
        /**
         * 取第一个汉字的第一个字符
        * @Title: getFirstLetter 
        * @Description: TODO 
        * @return String   
        * @throws
         */
        public static String getFirstLetter(String ChineseLanguage){
            char[] cl_chars = ChineseLanguage.trim().toCharArray();
            String hanyupinyin = "";
            HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
            defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);// 输出拼音全部大写
            defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);// 不带声调
            try {
                String str = String.valueOf(cl_chars[0]);
                if (str.matches("[u4e00-u9fa5]+")) {// 如果字符是中文,则将中文转为汉语拼音,并取第一个字母
                    hanyupinyin = PinyinHelper.toHanyuPinyinStringArray(
                    cl_chars[0], defaultFormat)[0].substring(0, 1);;
                } else if (str.matches("[0-9]+")) {// 如果字符是数字,取数字
                    hanyupinyin += cl_chars[0];
                } else if (str.matches("[a-zA-Z]+")) {// 如果字符是字母,取字母
    
                    hanyupinyin += cl_chars[0];
                } else {// 否则不转换
    
                }
            } catch (BadHanyuPinyinOutputFormatCombination e) {
                System.out.println("字符不能转成汉语拼音");
            }
            return hanyupinyin;
        }
        
        public static void main(String[] args) {
            
            System.out.println(getFirstLettersUp("测试"));
        }
    }

    2.压缩包

    import java.io.BufferedInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipOutputStream;
     
    
     
    public class ZIPUtil {
     
        
     
        /**s
         * 压缩文件
         * @param srcFilePath 压缩源路径
         * @param destFilePath 压缩目的路径
         */
        public static void compress(String srcFilePath, String destFilePath) {
            //
            File src = new File(srcFilePath);
     
            if (!src.exists()) {
                throw new RuntimeException(srcFilePath + "不存在");
            }
            File zipFile = new File(destFilePath);
     
            try {
     
                FileOutputStream fos = new FileOutputStream(zipFile);
                ZipOutputStream zos = new ZipOutputStream(fos);
                String baseDir = "";
                compressbyType(src, zos, baseDir);
                zos.close();
              
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
     
            }
        }
        /**
         * 按照原路径的类型就行压缩。文件路径直接把文件压缩,
         * @param src
         * @param zos
         * @param baseDir
         */
         private static void compressbyType(File src, ZipOutputStream zos,String baseDir) {
     
                if (!src.exists())
                    return;
                //判断文件是否是文件,如果是文件调用compressFile方法,如果是路径,则调用compressDir方法;
                if (src.isFile()) {
                    //src是文件,调用此方法
                    compressFile(src, zos, baseDir);
                     
                } else if (src.isDirectory()) {
                    //src是文件夹,调用此方法
                    compressDir(src, zos, baseDir);
     
                }
     
            }
          
            /**
             * 压缩文件
            */
            private static void compressFile(File file, ZipOutputStream zos,String baseDir) {
                if (!file.exists())
                    return;
                try {
                    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
                    ZipEntry entry = new ZipEntry(baseDir + file.getName());
                    zos.putNextEntry(entry);
                    int count;
                    byte[] buf = new byte[1024];
                    while ((count = bis.read(buf)) != -1) {
                        zos.write(buf, 0, count);
                    }
                    bis.close();
     
                } catch (Exception e) {
                  // TODO: handle exception
     
                }
            }
             
            /**
             * 压缩文件夹
             */
            private static void compressDir(File dir, ZipOutputStream zos,String baseDir) {
                if (!dir.exists())
                    return;
                File[] files = dir.listFiles();
                if(files.length == 0){
                    try {
                        zos.putNextEntry(new ZipEntry(baseDir + dir.getName()+File.separator));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                for (File file : files) {
                    compressbyType(file, zos, baseDir + dir.getName() + File.separator);
                }
        }
            
            public static void test(){
                String path = "C:\Users\dell\Desktop\统计表\转换模板_20181031\模板_20181101\财务模板_20181202";
                File f = new File(path);
                File [] file = f.listFiles();
                for (int i = 0; i < file.length; i++) {
                    String sourceFile = path+"/"+file[i].getName();
                    String targetFile = "";
                    targetFile = sourceFile+".zip";
                    compress(sourceFile,targetFile);
                }
                System.out.println("完成");
            }
            /**
             * @param args 主方法
             */
            public static void main(String[] args) {
                // TODO Auto-generated method stub
                //第一个参数是需要压缩的源路径;第二个参数是压缩文件的目的路径,这边需要将压缩的文件名字加上去
    //            compress("Q:/bbbb/123.txt","Q:/bbbb/ceshi.zip");
                test();
            
            }
    }

     3.EXCEL

    import java.util.ArrayList;
    import java.util.List;
    
    import org.apache.commons.lang.StringUtils;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.ss.usermodel.Cell;
    import org.apache.poi.ss.usermodel.Row;
    import org.apache.poi.ss.usermodel.Sheet;
    import org.apache.poi.ss.usermodel.Workbook;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.web.multipart.MultipartFile;
    
    public class ExcelUtil {
        
        private static final Logger LOGGER = LoggerFactory.getLogger(ExcelUtil.class);
        
         //判断是否是2003的excel 
        public static boolean isExcel2003(String filePath)  {  
             return filePath.matches("^.+\.(?i)(xls)$");  
         }  
       
        //判断是否是2007的excel
        public static boolean isExcel2007(String filePath)  {  
             return filePath.matches("^.+\.(?i)(xlsx)$");  
         }  
        
        public static List<Object> readExcel(MultipartFile mfile) throws Exception{
            List<Object> list = new ArrayList<Object>();
            Workbook wb = null;
            String fileName = mfile.getOriginalFilename();
            boolean isExcel2003 = ExcelUtil.isExcel2003(fileName);
            boolean isExcel2007 = ExcelUtil.isExcel2007(fileName);
            ArrayList<String> columns = new ArrayList<String>();
            ArrayList<String> datas = new ArrayList<String>();
            Integer columnsCount = 0;
            if (isExcel2003) {
                wb = new HSSFWorkbook(mfile.getInputStream());
            } else if (isExcel2007) {
                wb = new XSSFWorkbook(mfile.getInputStream());
            } else {
                throw new Exception("该类型文件不是excel");
            }
            Sheet sheet = null;
            // 获取第一个sheet表
            sheet = wb.getSheetAt(0);
            int rowCount = sheet.getLastRowNum();
            int cellCount = sheet.getRow(0).getLastCellNum();
            for (int j = 0; j < rowCount + 1; j++) {
                Row row = sheet.getRow(j);
                if (row != null) {
                    for (int k = 0; k < cellCount; k++) {
                        if(row.getCell(k)!=null){
                            row.getCell(k).setCellType(Cell.CELL_TYPE_STRING);
                        }
                        //需要去除空格
                        String value = (row.getCell(k)+"").trim();
                        if(!StringUtils.isBlank(value)){
                            value = value.trim();
                        }
                        if (j == 0) {
                            columns.add("[" + value + "]");
                            columnsCount++;
                        } else {
                            datas.add("'" + value + "'");
    
                        }
                    }
                }
            }
            list.add(datas);
            list.add(columns);
            list.add(columnsCount);
            return list;
        }
    }

     4.JFrame窗口和文件选择器

    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.File;
    import java.io.IOException;
    import java.sql.SQLException;
    
    import javax.swing.JButton;
    import javax.swing.JFileChooser;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JTextField;
    
    import org.apache.commons.lang.StringUtils;
    
    import com.zskj.etl.util.dbmanager.impl.SqlServerDBManager;
    
    import pojo.DBServer;
    
    @SuppressWarnings("serial")
    public class RestoreAccess extends JFrame implements ActionListener {
        static JButton open = null;
        static JFrame frame = null;
        static boolean Flag = false;
        static String errorInfo = "";
        static DBServer dbServer = new DBServer();
    
        public static void main(String[] args) {
            shows();
            String s = "";
        }
    
        public static void shows() {
            // 创建文件选择器
            RestoreAccess fileChooser = new RestoreAccess();
            frame = new JFrame();
            frame.setTitle("还原Access文件");
            frame.setDefaultCloseOperation(3); // 发起close时默认执行操作(读者可自行百度)
            frame.setSize(380, 200);
            frame.setLocationRelativeTo(null); // 设置窗体显示在居中位置
            frame.setResizable(false);
            frame.setLayout(new FlowLayout());
    
            // 创建标签
            JLabel L1 = new JLabel("数据库名称 :");
            JTextField DBName = new JTextField(20);
    
            JLabel L2 = new JLabel("   数据库 IP :");
            JTextField IP = new JTextField(20);
    
            JLabel L3 = new JLabel("       数据库账号 :");
            JTextField user = new JTextField(20);
    
            JLabel L4 = new JLabel("       数据库密码 :");
            JTextField pwd = new JTextField(20);
    
            open = new JButton("选择要还原的Access文件");
            fileChooser.add(open);
            //button按钮是否单独显示
    //        fileChooser.setVisible(true);
            fileChooser.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            open.addActionListener(fileChooser);
    
            // 添加标签
            
            frame.add(L2);
            frame.add(IP);
            frame.add(L1);
            frame.add(DBName);
            frame.add(L3);
            frame.add(user);
            frame.add(L4);
            frame.add(pwd);
            frame.add(open);
            frame.setVisible(true);
    
            ButtonListener bl = new ButtonListener(DBName, IP, user, pwd);
            open.addActionListener(bl);
    
        }
    
        @Override
        public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
            JFileChooser jfc = new JFileChooser();
            jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
            jfc.showDialog(new JLabel(), "选择");
            File file = jfc.getSelectedFile();
            if (file.isDirectory()) {
                System.out.println("文件夹:" + file.getAbsolutePath());
            } else if (file.isFile()) {
                System.out.println("文件:" + file.getAbsolutePath());
                System.out.println("name:" + dbServer.getDBName());
                System.out.println("IP:" + dbServer.getIP());
                System.out.println("pwd:" + dbServer.getPwd());
                System.out.println("user:" + dbServer.getUser());
                try {
                    //还原ACCESS功能
                    SqlServerDBManager sqlServerDBManager = new SqlServerDBManager(dbServer.getIP(), dbServer.getUser(),
                            dbServer.getPwd(), "1433", dbServer.getDBName());
                    JackcessUtil.importDataToSqlServer(sqlServerDBManager, file.getAbsolutePath());
                    Flag = true;
                } catch (ClassNotFoundException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                    errorInfo = e1.getMessage();
                } catch (SQLException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                    errorInfo = e1.getMessage();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                    errorInfo = e1.getMessage();
                }finally{
                    if(Flag == true){
                        JOptionPane.showMessageDialog(null, "还原成功!");
                        errorInfo = "";
                    }else{
                        if(!StringUtils.isBlank(errorInfo)){
                            JOptionPane.showMessageDialog(null, errorInfo);
                        }else{
                            JOptionPane.showMessageDialog(null, "该文件不是Access文件");
                        }
                        errorInfo = "";
                        
                    }
                    
                }
    
            }
            System.out.println(jfc.getSelectedFile().getName());
    
        }
    
        // 自己定义一个类来实现接口
        public static class ButtonListener implements java.awt.event.ActionListener { // 实现ActionListener
            public JTextField DBName = new JTextField(); // 传参
            public JTextField IP = new JTextField();
            public JTextField user = new JTextField();
            public JTextField pwd = new JTextField();
    
            // public Huaban hua=new Huaban(); //一个画板对象
            public ButtonListener(JTextField DBName, JTextField IP, JTextField user, JTextField pwd) {// 重载
                this.DBName = DBName; // 窗体上的账号框,密码框传到监听上来
                this.IP = IP;
                this.pwd = pwd;
                this.user = user;
    
            }
    
            public ButtonListener() {
    
            }
    
            public void actionPerformed(ActionEvent e) { // 捕获点击动作
                dbServer.setUser(user.getText());
                dbServer.setIP(IP.getText());
                dbServer.setPwd(pwd.getText());
                dbServer.setDBName(DBName.getText());
            }
    
        }
    
    }

     5.SFTP上传下载

      首先安装Freesshd,配置账号密码和路径

           

      
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.InputStream;
    import java.io.UnsupportedEncodingException;
    import java.util.Vector;
    
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    
    import com.jcraft.jsch.Channel;
    import com.jcraft.jsch.ChannelSftp;
    import com.jcraft.jsch.JSch;
    import com.jcraft.jsch.JSchException;
    import com.jcraft.jsch.Session;
    import com.jcraft.jsch.SftpATTRS;
    import com.jcraft.jsch.SftpException;  
      
    /** 
     * SFTP帮助类 
     * 
     */  
    public class SFTPUtil {  
          
        private static Log log = LogFactory.getLog(SFTPUtil.class);  
          
        public static void main(String[] args) {
            ChannelSftp sftp = null;  
            Session session = null;  
            try {  
                session = SFTPUtil.connect("100.80.10.36", 22, "tt", "123456");  
                Channel channel = session.openChannel("sftp");  
                channel.connect();  
                sftp = (ChannelSftp) channel;  
    //            SFTPUtil.upload("kkkk","D:/otherFiles/1.bat", sftp);  
                SFTPUtil.download("kkkk","qqq.txt","D:\otherFiles\sss\", sftp);
                System.out.println("已完成");
            } catch (Exception e) {  
                e.printStackTrace();  
                log.debug(e);  
            }finally{  
                if(sftp != null)sftp.disconnect();  
                if(session != null)session.disconnect();  
            }  
        }
        
        /** 
         * 连接sftp服务器 
         * @param host 远程主机ip地址 
         * @param port sftp连接端口,null 时为默认端口 
         * @param user 用户名 
         * @param password 密码 
         * @return 
         * @throws JSchException  
         */  
        public static Session connect(String host, Integer port, String user, String password) throws JSchException{  
            Session session = null;  
            try {  
                JSch jsch = new JSch();  
                if(port != null){  
                    session = jsch.getSession(user, host, port.intValue());  
                }else{  
                    session = jsch.getSession(user, host);  
                }  
                session.setPassword(password);  
                //设置第一次登陆的时候提示,可选值:(ask | yes | no)  
                session.setConfig("StrictHostKeyChecking", "no");  
                //30秒连接超时  
                session.connect(30000);
            } catch (JSchException e) {  
                e.printStackTrace();  
                System.out.println("SFTPUitl 获取连接发生错误");  
                throw e;  
            }  
            return session;  
        }  
          
        /**
         *  
         * @param directory 相对目标路径 ,只能处理一层
         * @param uploadFile 上传文件路径
         * @param sftp
         * @throws Exception
         */
        public static void upload(String directory, String uploadFile, ChannelSftp sftp) throws Exception{
            System.out.println("sftp upload file [directory] : "+ directory);  
            System.out.println("sftp upload file [uploadFile] : "+ uploadFile);  
            File file = new File(uploadFile);  
            if(file.exists()){
                isExistFolder(directory, sftp);
                //必须进入才能创建
                sftp.cd(directory);
                if(file.isFile()){  
                    InputStream ins = new FileInputStream(file); 
                    //中文名称的  
                    sftp.put(ins, new String(file.getName().getBytes(),"UTF-8"));  
                }
              
            }  
        }  
          
        /**
         * 判断文件夹是否存在不存在就创建,只处理一层
         * @param directory
         * @param uploadFile
         * @param sftp
         */
        public static boolean isExistFolder(String directory,ChannelSftp sftp){
            boolean flag = false;
            try {
                // 判断子目录文件夹是否存在,不存在即创建
                SftpATTRS attrs = null;
                try {
                    attrs = sftp.stat(directory);
                } catch (Exception e) {
                    // TODO: handle exception
                }
                if (attrs == null) {
                    sftp.mkdir(directory);
                    log.info("创建子目录:" + directory);
                }else{
                    flag = true;
                }
            } catch (SftpException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return flag;
        }
        
        /**
         * 
         * @param srcDirectory 源路径,相对路径
         * @param srcFileName 源文件名称
         * @param savePath 保存路径
         * @param sftp 
         * @throws UnsupportedEncodingException
         */
        public static void download(String srcDirectory,String srcFileName, String savePath, ChannelSftp sftp) throws UnsupportedEncodingException {  
            Vector v = null;
            String temp = "";
            File sp = new File(savePath);
            boolean flag = false;
            try {
                v = sftp.ls(srcDirectory);
                flag = isExistFolder(srcDirectory, sftp);
                if(flag == true){
                    sftp.cd(srcDirectory);
                }
                if(!sp.exists()){
                    sp.mkdirs();
                }
                for (Object object : v) {
                    temp = object.toString();
                    temp = temp.substring(temp.lastIndexOf(" ")+1);
                    if(temp.equals(srcFileName)){
                        sftp.get(srcFileName,savePath+File.separator+srcFileName);
                    }
                }
            } catch (SftpException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 
        }  
    }  

    6.FTP工具类

    package com.zskj.pd.util;
    
    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.nio.charset.Charset;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    import org.apache.commons.net.ftp.FTPClient;
    import org.apache.commons.net.ftp.FTPFile;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import com.zskj.pd.pojo.FtpEntity;
    
    public class ftpUtil {
        
        private final static Logger LOG = LoggerFactory.getLogger(ftpUtil.class);
        
        public static void main(String args[]) {
            FtpEntity m = new FtpEntity("100.80.10.38", 21, "test", "test");
            FTPClient fTPClient = login(m);
            uploadFile(fTPClient, "6666666666", "doc", "2.bat", "D:\otherFiles");
            
        }    
    
        
        
         //验证登录
             public static FTPClient login(FtpEntity ftpEntity) {
                 FTPClient ftp = null;
                 try {
                     ftp = new FTPClient();
                     ftp.connect(ftpEntity.getIp(), ftpEntity.getPort());
                     ftp.login(ftpEntity.getName(), ftpEntity.getPwd());
                     ftp.setCharset(Charset.forName("UTF-8"));
                     ftp.setControlEncoding("UTF-8");
                     LOG.info(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+" 登录成功");
                 } catch (IOException e) {
                 // TODO Auto-generated catch block
                 e.printStackTrace();
                 }
                 return ftp;
             }
    
            // 获取ftp某一文件(路径)下的文件名字,用于查看文件列表
            public static void getFilesName(FTPClient fTPClient) {
                try {
                    // 获取ftp里面,“Windows”文件夹里面的文件名字,存入数组中
                    FTPFile[] files = fTPClient.listFiles("/Windows");
                    // 打印出ftp里面,“Windows”文件夹里面的文件名字
                    for (int i = 0; i < files.length; i++) {
                        System.out.println(files[i].getName());
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
    
            /**
             * 
             * @param targetFileName
             * @param targetPath
             * @param sourceFileName
             * @param sourcePath
             */
            public static void uploadFile(FTPClient fTPClient,String targetFileName,String targetPath,String sourceFileName,String sourcePath) {
                try {
                    File sfp = new File(sourcePath+"\"+sourceFileName);
                    fTPClient.storeFile(targetPath+"\"+targetFileName, new FileInputStream(sfp));
                    LOG.info(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+" 上传完成");
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            
            /**
             * 
             * @param targetFileName
             * @param targetPath
             * @param sourceFileName
             * @param sourcePath
             */
            public static void uploadFile2(FTPClient fTPClient,String targetFileName,String targetPath,String sourceFileName,String sourcePath) {
                OutputStream os = null;
                FileInputStream fis = null;
                try {
                    os = fTPClient.storeFileStream(targetPath+"\"+targetFileName);
                    fis = new FileInputStream(new File(sourcePath+"\"+sourceFileName));
                    byte[] b = new byte[1024];
                    int len = 0;
                    while ((len = fis.read(b)) != -1) {
                        os.write(b, 0, len);
                    }
                    os.flush();
                    LOG.info(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+" 上传完成");
                } catch (IOException e) {
                    e.printStackTrace();
                }finally{
                    try {
                        os.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    try {
                        fis.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
    
            /**
             * 
             * @param targetFileName
             * @param targetPath
             * @param sourceFileName
             * @param sourcePath
             */
            public static void downloadFile(FTPClient fTPClient,String targetFileName,String targetPath,String sourceFileName,String sourcePath) {
                try {
                    // 将ftp根目录下的"jsoup-1.10.2.jar"文件下载到本地目录文件夹下面,并重命名为"1.jar"
                    fTPClient.retrieveFile(sourcePath+"\"+sourceFileName, new FileOutputStream(new File(targetPath+"\"+targetFileName)));
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
    
            /**
             * 
             * @param targetFileName
             * @param targetPath
             * @param sourceFileName
             * @param sourcePath
             */
            public static void downloadFile2(FTPClient fTPClient,String targetFileName,String targetPath,String sourceFileName,String sourcePath) {
                InputStream is = null;
                FileOutputStream fos = null;
                try {
                    is = fTPClient.retrieveFileStream(sourcePath+"\"+sourceFileName);
                    fos = new FileOutputStream(new File(targetPath+"\"+targetFileName));
                    byte[] b = new byte[1024];
                    int len = 0;
                    while ((len = is.read(b)) != -1) {
                        fos.write(b, 0, len);
                    }
                    fos.flush();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }finally{
                    try {
                        fos.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    try {
                        is.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
    
    }

     

    7.SSH

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.util.concurrent.TimeUnit;
    
    import com.jcraft.jsch.Channel;
    import com.jcraft.jsch.JSch;
    import com.jcraft.jsch.Session;
    
    import ch.ethz.ssh2.Connection;
    import ch.ethz.ssh2.StreamGobbler;
    
    public class SSHSUtil {
    
        private Channel channel;
        private Session session = null;
        private int timeout = 60000;
    
        /*
         * 例如启动tomcat 可以写成绝对路径 /usr/apache-tomcat-7.0.47/bin/startup.sh
     还可以写成这样 cd
         * /usr/apache-tomcat-7.0.47/bin/
    ./startup.sh
     相当于在命令行里先 cd
         * /usr/apache-tomcat-7.0.47/bin 回车进入到tomcat的bin目录。
         * 然后在通过./startup.sh启动tomcat 这里的
    就相当于回车了。
         */
        public static void main(final String[] args) throws Exception {
    
            // shutdown.sh
            // SSHSUtil sshUtil = new SSHSUtil("100.80.10.38", "tt", "123456");
            // String res = sshUtil.runShell("cmd /k start D:\kkkk\1.bat",
            // "utf-8");
            // System.out.println(res);
            // sshUtil.close();
            test();
            // runbat();
    
        }
    
        public static void runbat() {
            String cmd = "cmd /k start D:\otherFiles\1.bat";// pass
            try {
                Process ps = Runtime.getRuntime().exec(cmd);
                InputStream in = ps.getInputStream();
                int c;
                while ((c = in.read()) != -1) {
                    System.out.print(c);// 如果你不需要看输出,这行可以注销掉
                    break;
                }
                in.close();
                ps.destroy();
                // ps.waitFor();
    
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
            // catch (InterruptedException e) {
            // // TODO Auto-generated catch block
            // e.printStackTrace();
            // }
            System.out.println("child thread donn");
        }
    
        public static void test() {
            String hostname = "192.168.11.2";
            String username = "a";
            String password = "123456";
            try {
                // 建立连接
                Connection conn = new Connection(hostname);
                // System.out.println("set up connections");
                conn.connect();
                // 利用用户名和密码进行授权
                boolean isAuthenticated = conn.authenticateWithPassword(username, password);
                if (isAuthenticated == false) {
                    // System.out.println("--------");
                    throw new IOException("Authorication failed");
                }
                // 打开会话
                ch.ethz.ssh2.Session sess = conn.openSession();
                 System.out.println("cmd----");
    //             执行命令
                sess.execCommand("start D:\otherFiles\1.bat");
                 System.out.println("The execute command output is:");
                InputStream stdout = new StreamGobbler(sess.getStdout());
                BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
                while (true) {
                    String line = br.readLine();
                    if (line == null)
                        break;
                    System.out.println(line);
                }
                // System.out.println("Exit code "+sess.getExitStatus());
                sess.close();
                conn.close();
                // System.out.println("Connection closed");
    
            } catch (IOException e) {
                System.out.println("can not access the remote machine");
            }
        }
    
        public SSHSUtil(final String ipAddress, final String username, final String password) throws Exception {
            JSch jsch = new JSch();
            this.session = jsch.getSession(username, ipAddress, 22);
            this.session.setPassword(password);
            this.session.setConfig("StrictHostKeyChecking", "no");
            this.session.setTimeout(this.timeout);
            this.session.connect();
            this.channel = this.session.openChannel("shell");
            this.channel.connect(1000);
        }
    
        public String runShell(String cmd, String charset) throws Exception {
            String temp = null;
            InputStream instream = null;
            OutputStream outstream = null;
            try {
                instream = this.channel.getInputStream();
                outstream = this.channel.getOutputStream();
                outstream.write(cmd.getBytes());
                outstream.flush();
                TimeUnit.SECONDS.sleep(2);
                if (instream.available() > 0) {
                    byte[] data = new byte[instream.available()];
                    int nLen = instream.read(data);
    
                    if (nLen < 0) {
                        throw new Exception("network error.");
                    }
                    temp = new String(data, 0, nLen, "UTF-8");
                }
            } finally {
                outstream.close();
                instream.close();
            }
            return temp;
        }
    
        public void close() {
            this.channel.disconnect();
            this.session.disconnect();
        }
    }
  • 相关阅读:
    华为云DevCloud为开发者提供高效智能的可信开发环境
    【HC资料合集】2019华为全联接大会主题资料一站式汇总,免费下载!
    在modelarts上部署mask-rcnn模型
    独立物理机和虚拟机比较有什么优势?
    .Net Core下使用MQTT协议直连IoT平台
    解惑Python模块学习,该如何着手操作...
    sar命令,linux中最为全面的性能分析工具之一
    窥探日志的秘密
    Debian 如何使用测试版更新软件包到最新的版本
    如何使用vsphere client 克隆虚拟机
  • 原文地址:https://www.cnblogs.com/kuangzhisen/p/9479750.html
Copyright © 2011-2022 走看看