package com.dzx;
import com.google.gson.Gson;
/**
* 程序主入口
*/
public class Home {
public static void main(String[] args) {
//jps 命令可以获取进程号
// runtimeCommand("jps");
UserConfig userConfig;
if (args.length == 6) {
userConfig = new UserConfig();
userConfig.setFtpIp(args[0]);
userConfig.setFtpPort(Utils.getStrInt(args[1]));
userConfig.setFtpUserName(args[2]);
userConfig.setFtpPassword(args[3]);
userConfig.setUsbDiskName(args[4]);
userConfig.setEjectUsbPath(args[5]);
Utils.saveFile(Utils.getJarPath(userConfig.getClass()) + "/" + userConfig.getUserConfigFileName(),
new Gson().toJson(userConfig));
} else {
userConfig = new UserConfig();
String fileContent = Utils.readFile(
Utils.getJarPath(userConfig.getClass()) + "/" + userConfig.getUserConfigFileName());
if (!"".equals(fileContent)) {
userConfig = new Gson().fromJson(fileContent, UserConfig.class);
}
}
UserGui userGui = new UserGui(userConfig);
System.out.println("当前jar包所在的路径=" + Utils.getJarPath(userGui.getClass()));
CopyFileFromJar copyFileFromJar = new CopyFileFromJar(userConfig.getEjectUsbPath());
copyFileFromJar.loadRecourseFromJar("/resource/USB_Disk_Eject.exe");
}
}
package com.dzx;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.nio.file.Files;
import java.nio.file.Path;
/**
* 主界面显示文件
* 复制apk文件到U盘并删除之前的apk文件
* <p>
* 桌面程序,复制与删除文件
*/
@SuppressWarnings({"FieldCanBeLocal", "unused", "SameParameterValue", "WeakerAccess"})
public class UserGui extends JFrame implements ActionListener {
private static int copySuccess = 0b1, deleteSuccess = 0b10, maskFlag = 0;
private static String resultInfo = "";
private JTextField copyFlieName = new JTextField(10);
private JTextField deleteFileName = new JTextField(10);
// private JPasswordField jpf = new JPasswordField(10);
private JLabel copyFlieInfo = new JLabel("要复制的文件名称(不需要.apk):");
private JLabel deleteFlieInfo = new JLabel("要删除的文件名称(不需要.apk):");
private JButton excuteButton = new JButton("开始执行");
private JButton resetButton = new JButton("重置文件名称");
private JButton removeUsbButton = new JButton("移除U盘");
private JButton copyFileToUsbButton = new JButton("复制ftp文件到U盘,删除指定U盘文件,弹出U盘");
private JLabel result = new JLabel();
private JPanel container = new JPanel();
/**
* 输入框及说明相关坐标
*/
private int leftX = 30, copyFlieInfoLeftY = 20, explainWidth = 200, explainHeight = 30,
deleteFlieInfoLeftY = 70, gaps = 30, fieldWidth = 360, fieldHeight = 30;
/**
* 移除U盘按钮x坐标
*/
private int removeUsbButtonLeftX = 510;
/**
* 重置按钮x坐标
*/
private int resetButtonLeftX = 280;
/**
* 按钮的宽高,y坐标
*/
private int excuteButtonWidth = 180, excuteButtonHeight = 30, ButtonLeftY = 130;
/**
* excuteButton 开始执行 按钮 x坐标位置
*/
private int excuteButtonLeftX = 50;
/**
* 结果显示文本位置,宽高
*/
private int resultLeftX = 30, resultLeftY = 250, resultWidth = 790, resultHeight = 300;
/**
* copyFileToUsbButton的位置坐标,宽高
*/
private int copyFileToUsbButtonLeftX = 50, copyFileToUsbButtonLeftY = 190, copyFileToUsbButtonWidth = 640,
copyFileToUsbButtonHeight = 30;
private PhaseListener phaseListener = new PhaseListener() {
@Override
public void start(String startInfo) {
resultInfo += startInfo;
result.setText("<html>" + resultInfo);
}
@Override
public void finish(String finishInfo) {
if (ftpDownload.isCopySuccess()) {
maskFlag |= copySuccess;
} else {
maskFlag &= ~copySuccess;
}
resultInfo += finishInfo;
result.setText("<html>" + resultInfo);
if ((maskFlag & copySuccess) != 0 &&
(maskFlag & deleteSuccess) != 0) {//复制删除成功,移除U盘
removeUsbButtonClick();
}
}
@Override
public void error(String errorInfo) {
resultInfo += errorInfo;
result.setText("<html>" + resultInfo);
}
@Override
public void progress(String progressInfo) {
result.setText("<html>" + resultInfo + progressInfo);
}
};
private UserConfig userConfig;
public UserGui(UserConfig userConfig) {
this.userConfig=userConfig;
//获取jar包所在路径
// String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
// System.out.println("ja包所在路径=" +
// this.getClass().getResource("/resource/USB_Disk_Eject.exe"));
this.setTitle("复制与删除apk文件");
//关闭时直接退出
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
container.setLayout(null);
copyFlieName.setEnabled(true);
copyFlieName.setEditable(true);
//设置字体,内容个位置
result.setFont(new Font("宋体", Font.PLAIN, 20));
result.setHorizontalAlignment(SwingConstants.LEFT);
result.setVerticalAlignment(SwingConstants.TOP);
getPath(copyFlieName);
//--在容器中左上角的坐标x,y,控件的宽度与高度
copyFlieInfo.setBounds(leftX, copyFlieInfoLeftY, explainWidth, explainHeight);
container.add(copyFlieInfo);
deleteFlieInfo.setBounds(leftX, deleteFlieInfoLeftY, explainWidth, explainHeight);
container.add(deleteFlieInfo);
copyFlieName.setBounds(explainWidth + leftX + gaps, copyFlieInfoLeftY, fieldWidth, fieldHeight);
container.add(copyFlieName);
// jpf.setBounds(80, 70, 180, 30);
// container.add(jpf);
deleteFileName.setBounds(explainWidth + leftX + gaps, deleteFlieInfoLeftY, fieldWidth, fieldHeight);
container.add(deleteFileName);
excuteButton.setBounds(excuteButtonLeftX, ButtonLeftY, excuteButtonWidth, excuteButtonHeight);
container.add(excuteButton);
resetButton.setBounds(resetButtonLeftX, ButtonLeftY, excuteButtonWidth, excuteButtonHeight);
container.add(resetButton);
removeUsbButton.setBounds(removeUsbButtonLeftX, ButtonLeftY, excuteButtonWidth, excuteButtonHeight);
container.add(removeUsbButton);
copyFileToUsbButton.setBounds(copyFileToUsbButtonLeftX, copyFileToUsbButtonLeftY, copyFileToUsbButtonWidth, copyFileToUsbButtonHeight);
container.add(copyFileToUsbButton);
result.setBounds(resultLeftX, resultLeftY, resultWidth, resultHeight);
JPanel rrr = new JPanel();
//设置子view居左显示
FlowLayout flowLayout = new FlowLayout();
flowLayout.setAlignment(FlowLayout.LEFT);
rrr.setLayout(flowLayout);
rrr.setBounds(resultLeftX, resultLeftY, resultWidth, resultHeight);
//设置JLable的上下左右边距
rrr.setBorder(new EmptyBorder(0, 10, 10, 10));
rrr.add(result);
//为子view添加滚动条
JScrollPane scroll = new JScrollPane(rrr);
scroll.setAutoscrolls(true);
//加快滚轮的滑动速度
scroll.getVerticalScrollBar().setUnitIncrement(20);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setBounds(resultLeftX, resultLeftY, resultWidth, resultHeight);
container.add(scroll);
excuteButton.addActionListener(this);
resetButton.addActionListener(this);
removeUsbButton.addActionListener(this);
copyFileToUsbButton.addActionListener(this);
this.add(container);
//设置整个界面的大小与在屏幕中的位置
this.setBounds(250, 150, 850, 600);
this.setVisible(true);
//禁止窗口放大缩小
this.setResizable(false);
//监听窗口右上角的关闭按钮
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
super.windowClosing(e);
System.out.println("执行了关闭点击事件");
System.exit(0);
}
});
}
/**
* 按钮点击事件监听
*/
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("不同的点击事件=" + e.getActionCommand() + "=");
String actionCommand = e.getActionCommand();
if ("复制ftp文件到U盘,删除指定U盘文件,弹出U盘".equals(actionCommand)) {
copyFileToUsb();
} else if ("开始执行".equals(actionCommand)) {
excuteButtonClick();
} else if ("重置文件名称".equals(actionCommand)) {
resetButtonClick();
} else if ("移除U盘".equals(actionCommand)) {
removeUsbButtonClick();
}
}
private FtpDownload ftpDownload;
/**
* 直接从ftp下载文件到U盘
*/
private void copyFileToUsb() {
maskFlag &= ~copySuccess;
maskFlag &= ~deleteSuccess;
resultInfo = "";
result.setText("");
new Thread(() -> {
String ftpFileName = copyFlieName.getText();
//下载文件到U盘
ftpDownload = new FtpDownload(userConfig.getFtpIp(), userConfig.getFtpPort(),
userConfig.getFtpUserName(), userConfig.getFtpPassword());
ftpDownload.setPhaseListener(phaseListener);
ftpDownload.downFileFromFtpToUDisk(ftpFileName);
result.setText("<html>" + resultInfo);
}).start();
new Thread(() -> {
String deleteUsbFileName = deleteFileName.getText();
resultInfo += "<br>开始删除U盘文件" + deleteUsbFileName + ".apk!<br>";
result.setText("<html>" + resultInfo);
deleteUsbFile();
result.setText("<html>" + resultInfo);
if ((maskFlag & copySuccess) != 0 &&
(maskFlag & deleteSuccess) != 0) {//复制删除成功,移除U盘
removeUsbButtonClick();
}
}).start();
}
/**
* 重置文件名称
*/
private void resetButtonClick() {
result.setText("");
String copyFileNameNew = copyFlieName.getText();
copyFlieName.setText(handleFileName(copyFileNameNew));
String deleteFileNameNew = deleteFileName.getText();
deleteFileName.setText(handleFileName(deleteFileNameNew));
//执行速度快
// System.exit(0);
//调用cmd命令杀死进程,执行速度较慢
// runtimeCommand("taskkill /pid " + getProcessID() + " -t -f");
}
private String handleFileName(String target) {
int copyFileNum;
try {
copyFileNum = Integer.parseInt(target);
copyFileNum++;
} catch (Exception e) {
int start = target.lastIndexOf("\\") + 1;
int end = target.indexOf(".apk");
copyFileNum = Integer.parseInt(target.substring(start, end));
copyFileNum++;
}
if (("" + copyFileNum).length() > 2) {
target = "" + copyFileNum;
} else if (("" + copyFileNum).length() == 1) {
target = "00" + copyFileNum;
} else if (("" + copyFileNum).length() == 2) {
target = "0" + copyFileNum;
}
return target;
}
/**
* 移除U盘点击事件,执行该命令需要首先下载USB_Disk_Eject.exe程序
*/
private void removeUsbButtonClick() {
new Thread(() -> {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
String s = Utils.runtimeCommand(userConfig.getEjectUsbPath()+" /REMOVELETTER "+Utils.getLocalDisk());
resultInfo += s;
result.setText("<html>" + resultInfo);
}).start();
}
/**
* 开始执行按钮点击事件
*/
private void excuteButtonClick() {
resultInfo = "";
result.setText("");
String s1 = copyFlieName.getText();
File sourceFile;
File targetFile;
sourceFile = new File(s1);
System.out.println("要复制的文件存在" + sourceFile.exists());
System.out.println("要复制的文件存在" + sourceFile.getName());
if (!sourceFile.exists()) {
sourceFile = new File("C:\\Users\\dingzhixin.ex\\Desktop\\" + s1 + ".apk");
targetFile = new File("H:\\" + s1 + ".apk");
} else {
targetFile = new File("H:\\" + sourceFile.getName());
}
if (!sourceFile.exists()) {
resultInfo = "要复制的文件不存在<br><br>";
result.setText("<html>" + resultInfo + "<br>当前要复制的文件路径是:<br>" + sourceFile.getAbsolutePath());
return;
}
try {
resultInfo = resultInfo + "文件复制成功:<br>" + copyFileUsingJava7Files(sourceFile, targetFile);
maskFlag |= copySuccess;
} catch (Exception ex) {
//---------------------获取完整的异常输出信息------------------------------
// StringWriter stringWriter= new StringWriter();
// PrintWriter writer= new PrintWriter(stringWriter);
// ex.printStackTrace(writer);
// StringBuffer buffer= stringWriter.getBuffer();
// System.out.println("文件复制异常"+buffer.toString());
//---------------------获取完整的异常输出信息------------------------------
maskFlag &= ~copySuccess;
resultInfo = resultInfo + "文件复制出错:<br><br>" + ex.toString();
System.out.println("复制文件出错----------------");
ex.printStackTrace();
}
deleteUsbFile();
result.setText("<html>" + resultInfo);
if ((maskFlag & copySuccess) != 0 &&
(maskFlag & deleteSuccess) != 0) {//复制删除成功,移除U盘
removeUsbButtonClick();
}
// String s2 = jpf.getText();
}
/**
* 删除U盘上的指定文件
*/
private void deleteUsbFile() {
String s2 = deleteFileName.getText();
File deleteFile = new File(Utils.getLocalDisk() + s2 + ".apk");
boolean deleteResult = delete(deleteFile);
if (deleteResult) {
maskFlag |= deleteSuccess;
resultInfo += "<br>U盘文件" + s2 + ".apk" + "删除成功!<br>";
} else {
maskFlag &= ~deleteSuccess;
resultInfo += "<br>文件" + s2 + "删除失败!<br>";
}
}
// private static void test() {
// System.out.println("======" + ((maskFlag & copySuccess) != 0));
// maskFlag |= copySuccess;//添加状态
// System.out.println("======" + ((maskFlag & copySuccess) != 0));//包含该状态
// maskFlag &= ~copySuccess;//移除状态
// System.out.println("======" + ((maskFlag & copySuccess) != 0));
// maskFlag &= copySuccess;//包含状态
// System.out.println("======" + ((maskFlag & copySuccess) != 0));
//
// }
private static String copyFileUsingJava7Files(File source, File dest)
throws IOException {
Path result = Files.copy(source.toPath(), dest.toPath());
System.out.println("复制文件成功!");
return result.toString() + "文件复制成功!";
}
private static boolean delete(File file) {
if (file.isFile()) {
boolean success = file.delete();
if (success) {
System.out.println("文件=" + file.getName() + "=删除成功!");
return true;
} else {
System.out.println("文件=" + file.getName() + "=删除失败!");
return false;
}
}
return false;
}
/**
* 拖曳文件到控件获取文件路径并显示
*/
private static void getPath(JTextField field) {
field.setTransferHandler(new TransferHandler() {
private static final long serialVersionUID = 1L;
@Override
public boolean importData(JComponent comp, Transferable t) {
try {
Object o = t.getTransferData(DataFlavor.javaFileListFlavor);
String filepath = o.toString();
if (filepath.startsWith("[")) {
filepath = filepath.substring(1);
}
if (filepath.endsWith("]")) {
filepath = filepath.substring(0, filepath.length() - 1);
}
System.out.println(filepath);
field.setText(filepath);
return true;
} catch (Exception e) {
e.printStackTrace();
resultInfo = resultInfo + "<br><br>拖曳获取文件路径失败:<br>" + e.toString();
}
return false;
}
@Override
public boolean canImport(JComponent comp, DataFlavor[] flavors) {
for (DataFlavor flavor : flavors) {
if (DataFlavor.javaFileListFlavor.equals(flavor)) {
return true;
}
}
return false;
}
});
}
/**
* 获取当前Java进程的pid号
*/
private static int getProcessID() {
RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
System.out.println(runtimeMXBean.getName());
return Integer.valueOf(runtimeMXBean.getName().split("@")[0]);
}
}
package com.dzx;
import org.apache.commons.net.ftp.FTPClient;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
/**
* ftp下载文件
*/
@SuppressWarnings({"WeakerAccess", "UnusedReturnValue", "FieldCanBeLocal", "unused"})
public class FtpDownload {
//ftp登录下载相关信息
private String errorInfo;
//ftp对象
private FTPClient ftp;
//需要连接到的ftp端的ip
private String ip;
//连接端口,默认21
private int port;
//要连接到的ftp端的名字
private String name;
//要连接到的ftp端的对应得密码
private String pwd;
private PhaseListener phaseListener;
public PhaseListener getPhaseListener() {
return phaseListener;
}
public void setPhaseListener(PhaseListener phaseListener) {
this.phaseListener = phaseListener;
}
//调用此方法,输入对应得ip,端口,要连接到的ftp端的名字,要连接到的ftp端的对应得密码。连接到ftp对象,并验证登录进入fto
public FtpDownload(String ip, int port, String name, String pwd) {
ftp = new FTPClient();
this.ip = ip;
this.port = port;
this.name = name;
this.pwd = pwd;
//验证登录
try {
ftp.connect(ip, port);
ftp.setCharset(Charset.forName("UTF-8"));
ftp.setControlEncoding("UTF-8");
//不加本行打jar包后会在ftp.retrieveFileStream(fileName + ".apk");阻塞,无法继续运行
ftp.enterLocalPassiveMode();
if (ftp.login(name, pwd)) {
System.out.println("Ftp登录成功!");
} else {
System.out.println("Ftp登录失败!");
}
} catch (IOException ex) {
System.out.println("登录FTP异常:<br>" + Utils.getExceptionInfo(ex));
}
}
// //下载文件
// public void getFile() {
// try {
// //将ftp根目录下的"jsoup-1.10.2.jar"文件下载到本地目录文件夹下面,并重命名为"1.jar"
// ftp.retrieveFile("jsoup-1.10.2.jar", new FileOutputStream(new File("D:/1.jar")));
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
private boolean copySuccess = false;
public boolean isCopySuccess() {
return copySuccess;
}
//下载文件的第二种方法,优化了传输速度
public String downFileFromFtpToUDisk(String fileName) {
if (phaseListener != null) {
phaseListener.start("<br>开始从ftp复制文件" + fileName + ".apk!<br>");
}
copySuccess = false;
String diskName = Utils.getLocalDisk();
if ("没有找到U盘,请先插入U盘!".equals(diskName)) {
System.out.println("没有找到U盘,请先插入U盘!");
if (phaseListener != null) {
phaseListener.error("<br>没有找到U盘,请先插入U盘!<br>");
}
return "没有找到U盘,请先插入U盘!";
}
InputStream is = null;
FileOutputStream fos = null;
try {
is = ftp.retrieveFileStream(fileName + ".apk");
fos = new FileOutputStream(new File(diskName + fileName + ".apk"));
System.out.println("is=" + is + ",fos=" + fos);
int count = 0;
long current = System.currentTimeMillis();
byte[] b = new byte[1024];
int len;
while ((len = is.read(b)) != -1) {
count++;
fos.write(b, 0, len);
if (phaseListener != null && System.currentTimeMillis() - current > 1000) {
current = System.currentTimeMillis();
phaseListener.progress("<br>已复制" + String.format("%.2f", count / 1024f) + "M");
}
}
System.out.println(fileName + ".apk 文件保存到 " + diskName + " 成功!");
copySuccess = true;
if (phaseListener != null) {
phaseListener.finish("<br>" + fileName + ".apk 文件保存到 " + diskName + " 成功!<br>");
}
return fileName + ".apk 文件保存到 " + diskName + " 成功!";
} catch (Exception e) {
System.out.println("下载文件到U盘出错:<br>" + Utils.getExceptionInfo(e));
if (phaseListener != null) {
for (int i = 0; i < 10; i++) {
phaseListener.error("<br>下载文件到U盘出错:<br>" + Utils.getExceptionInfo(e).replaceAll("\n", "<br>"));
}
}
return "下载文件到U盘出错:<br>" + Utils.getExceptionInfo(e);
} finally {
try {
if (is != null) {
is.close();
}
if (fos != null) {
fos.close();
}
ftp.logout();
if (ftp.isConnected()) {
ftp.disconnect();
}
System.out.println("finally块执行成功!");
} catch (IOException e) {
System.out.println("finally中异常:<br>" + Utils.getExceptionInfo(e));
}
}
}
}
package com.dzx;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* 导报资源文件需要在file-->project structure-->artifacts-->相应的jar包-->outputlayot-->+号
* --->directory content-->选中相应的资源文件夹-->然后打包才能将资源文件打进jar包
* 从jar包中复制文件到指定路径
*/
@SuppressWarnings({"SameParameterValue"})
class CopyFileFromJar {
private String savePath;
public CopyFileFromJar(String savePath) {
this.savePath = savePath;
}
/**
* 将jar包中的文件复制都指定目录
*/
void loadRecourseFromJar(String path) {
InputStream is = null;
FileOutputStream fileOutputStream = null;
try {
File file = new File(savePath);
if (file.exists()) {
System.out.println(savePath + "文件已存在!");
return;
}
//fileOutputStream new的时候如果文件不存在,则直接回创建文件
//如果要判断文件是否存在,需要在该方法前执行
fileOutputStream = new FileOutputStream(file);
is = this.getClass().getResourceAsStream(path);
// System.out.println("--------------?"+is.available());
//如果直接使用byte[] bytes = new byte[is.available()];
// fileOutputStream.write(bytes);
// byte[] bytes = new byte[is.available()];
// fileOutputStream.write(bytes,0,bytes.length);
//方法写文件会导致exe文件不可用,-1073741819异常,可能数据损坏
byte[] bytes = new byte[1024];
int len;
while ((len = is.read(bytes)) != -1) {
fileOutputStream.write(bytes, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package com.dzx;
import javax.swing.filechooser.FileSystemView;
import java.io.*;
/**工具类文件*/
@SuppressWarnings({"WeakerAccess", "ResultOfMethodCallIgnored"})
public class Utils {
/**
* 获取本地磁盘,可以获取U盘的盘符
*/
public static String getLocalDisk() {
File[] _files = File.listRoots();//全部盘符 临时变量
//过滤掉非"本地磁盘"类型的磁盘 by xdj 20121016
FileSystemView fileSystemView = FileSystemView.getFileSystemView();// 获取FileSystemView对象
for (File file : _files) {
// 获取磁盘的类型描述信息
String diskType = fileSystemView.getSystemTypeDescription(file);
// 本地磁盘||可移动磁盘
// System.out.println("系统盘符类型1="+diskType);
// ZHANGDAZHAO (H:)
// System.out.println("系统盘符类型2="+fileSystemView.getSystemDisplayName(file));
// C:\Users\dingzhixin.ex\Documents
// System.out.println("系统盘符类型3="+fileSystemView.getDefaultDirectory());
// C:\Users\dingzhixin.ex\Desktop
// System.out.println("系统盘符类型4="+fileSystemView.getHomeDirectory());
// 计算机
// System.out.println("系统盘符类型5="+fileSystemView.getParentDirectory(file));
//盘符类型包括:本地磁盘、可移动磁盘、CD 驱动器等
if (diskType.equals("可移动磁盘")) {
// H:\
System.out.println("获取U盘盘符=" + file.getAbsolutePath());
return file.getAbsolutePath();
}
}
return "没有找到U盘,请先插入U盘!";
}
/**
* 获取异常输出信息
*/
public static String getExceptionInfo(Exception ex) {
StringWriter stringWriter = new StringWriter();
PrintWriter writer = new PrintWriter(stringWriter);
ex.printStackTrace(writer);
StringBuffer buffer = stringWriter.getBuffer();
return buffer.toString();
}
/**
* Java执行cmd命令
*/
public static String runtimeCommand(String command) {
Process process;
try {// '/c'执行完后关闭cmd窗口,最后的cmd命令有异常时会出现问题
// '/k'执行完命令后不关闭窗口,手动exit则不会出现异常引发的问题
process = Runtime.getRuntime().exec("cmd.exe /c " + command);
int status = process.waitFor();
System.out.println(status);
InputStream in = process.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line = br.readLine();
while (line != null) {
System.out.println(line);
line = br.readLine();
}
return "<br>移除U盘成功";
} catch (Exception e) {
return "<br><br>执行cmd命令出错<br>" + getExceptionInfo(e);
}
}
/**
* 获取当前jar包所在路径
*/
public static String getJarPath(Class clz) {
String jarPath = clz.getProtectionDomain().getCodeSource().getLocation().getPath();
System.out.println("当前jar包所在的路径=" + jarPath);
return jarPath.substring(1, jarPath.lastIndexOf("/"));
}
/**
* 保存内容到文件
*/
public static void saveFile(String path, String content) {
System.out.println("当前文件的保存路径=" + path);
File file = new File(path);
if (file.isDirectory()) {
System.out.println("当前传递的文件路径是目录!");
return;
}
FileOutputStream fileOutputStream = null;
try {
if (file.isFile()) {
if (!file.exists()) {
System.out.println("当前文件不存在,创建新文件!");
file.createNewFile();
}
}
fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(content.getBytes());
fileOutputStream.flush();
System.out.println(path + "文件保存成功!");
} catch (Exception e) {
System.out.println("保存文件异常=" + getExceptionInfo(e));
} finally {
try {
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 判断字符串是否为空
*/
public static boolean strIsEmpty(String target) {
return target == null || "".equals(target);
}
/**
* 获取字符串int值,异常时返回0
*/
public static int getStrInt(String target) {
if (strIsEmpty(target)) {
return 0;
}
try {
return Integer.parseInt(target);
} catch (Exception e) {
return 0;
}
}
public static String readFile(String path) {
File file = new File(path);
if (file.isDirectory()) {
System.out.println("当前的文件路径是目录=" + path);
return "";
}
if (!file.exists()) {
System.out.println("当前的文件不存在=" + path);
return "";
}
try {
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuilder stringBuilder = new StringBuilder();
String temp;
while ((temp = bufferedReader.readLine()) != null) {
stringBuilder.append(temp);
}
System.out.println("当前读取的文件内容是=" + stringBuilder.toString());
return stringBuilder.toString();
} catch (Exception e) {
System.out.println("读取文件内容出错="+getExceptionInfo(e));
}
return "";
}
}
package com.dzx;
/**用户配置信息*/
public class UserConfig {
/**保存的配置文件名称*/
private String userConfigFileName="userConfig.json";
/**
* ftp Ip地址
*/
private String ftpIp = "10.18.205.60";
/**
* ftp 端口号
*/
private int ftpPort = 21;
/**
* ftp 用户名
*/
private String ftpUserName = "用户名";
/**
* ftp 密码
*/
private String ftpPassword = "密码";
/**
* 使用的U盘盘符
*/
private String usbDiskName = "H:/";
/**E:/USB_Disk_Eject.exe存储路径*/
private String ejectUsbPath="E:/USB_Disk_Eject.exe";
public String getEjectUsbPath() {
return ejectUsbPath;
}
public void setEjectUsbPath(String ejectUsbPath) {
this.ejectUsbPath = ejectUsbPath;
}
public String getUserConfigFileName() {
return userConfigFileName;
}
public String getFtpIp() {
return ftpIp;
}
public void setFtpIp(String ftpIp) {
if (!Utils.strIsEmpty(ftpIp)) {
this.ftpIp = ftpIp;
}
}
public int getFtpPort() {
return ftpPort;
}
public void setFtpPort(int ftpPort) {
if (ftpPort != 0) {
this.ftpPort = ftpPort;
}
}
public String getFtpUserName() {
return ftpUserName;
}
public void setFtpUserName(String ftpUserName) {
if (!Utils.strIsEmpty(ftpUserName)) {
this.ftpUserName = ftpUserName;
}
}
public String getFtpPassword() {
return ftpPassword;
}
public void setFtpPassword(String ftpPassword) {
if (!Utils.strIsEmpty(ftpPassword)) {
this.ftpPassword = ftpPassword;
}
}
public String getUsbDiskName() {
return usbDiskName;
}
public void setUsbDiskName(String usbDiskName) {
if (!Utils.strIsEmpty(usbDiskName)) {
this.usbDiskName = usbDiskName;
}
}
}
package com.dzx;
public interface PhaseListener {
void start(String startInfo);
void finish(String finishInfo);
void error(String errorInfo);
void progress(String progressInfo);
}
package com.dzx;
import org.apache.commons.net.ftp.FTPClient;
import java.io.*;
import java.nio.charset.Charset;
/**
* 上传文件到ftp
* 需要org.apache.commons.net包
* 在https://mvnrepository.com/search?q=javaws中搜索org.apache.commons net即可
* 当前使用版本3.6
*/
@SuppressWarnings({"Duplicates", "ResultOfMethodCallIgnored", "FieldCanBeLocal", "unused", "StatementWithEmptyBody"})
public class FtpUpload {
//ftp对象
private FTPClient ftp;
//需要连接到的ftp端的ip
private String ip;
//连接端口,默认21
private int port;
//要连接到的ftp端的名字
private String name;
//要连接到的ftp端的对应得密码
private String pwd;
//生成的apk的文件名称
//调用此方法,输入对应得ip,端口,要连接到的ftp端的名字,要连接到的ftp端的对应得密码。连接到ftp对象,并验证登录进入fto
private FtpUpload(String ip, int port, String name, String pwd) {
ftp = new FTPClient();
this.ip = ip;
this.port = port;
this.name = name;
this.pwd = pwd;
//验证登录
try {
ftp.connect(ip, port);
ftp.setCharset(Charset.forName("UTF-8"));
ftp.setControlEncoding("UTF-8");
ftp.enterLocalPassiveMode();
if (ftp.login(name, pwd)) {
System.out.println("Ftp登录成功!");
} else {
System.out.println("Ftp登录失败!");
}
//设置文件类型必须在ftp登录后设置,否则会导致上传的文件出现大小不一致的情况
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
// int reply;
// reply = ftp.getReplyCode();
System.out.println("ftp登录响应=" + ftp.getReplyString() + "=");
// if (!FTPReply.isPositiveCompletion(reply)) {
// ftp.disconnect();
// System.err.println("FTP server refused connection.");
// System.exit(1);
// }
} catch (IOException ex) {
System.out.println("登录FTP异常:<br>" + getExceptionInfo(ex));
}
}
//上传文件
public void putFile() {
try {
//将本地的"D:/1.zip"文件上传到ftp的根目录文件夹下面,并重命名为"aaa.zip"
System.out.println(ftp.storeFile("014.apk", new FileInputStream(new File("C:\\\\Users\\\\chennana\\\\Desktop\\\\014.apk"))));
} catch (IOException e) {
System.out.println("finally中异常:<br>" + getExceptionInfo(e));
}
}
/**
* 获取apk文件的名称
*/
private String getApkName() {
File file = new File("C:\\Users\\chennana\\work\\apk\\localv7" +
"\\aviview_v7\\app\\build\\outputs\\apk\\debug\\output.json");
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(file);
byte[] strbuf = new byte[(int) file.length()];
fileInputStream.read(strbuf);
fileInputStream.close();
String s = new String(strbuf);
int position = s.indexOf("outputFile");
int position1 = s.indexOf(".apk");
String currentNum = s.substring(position + 13, position1);
if (currentNum.length() > 2) {
// return currentNum;
} else if (currentNum.length() == 2) {
currentNum += "0";
} else if (currentNum.length() == 1) {
currentNum += "00";
}
System.out.println("当前要上传的文件名称是==" + currentNum + "==");
return currentNum;
} catch (Exception e) {
System.out.println("finally中异常:<br>" + getExceptionInfo(e));
} finally {
try {
if (fileInputStream != null) {
fileInputStream.close();
}
} catch (IOException e) {
System.out.println("finally中异常:<br>" + getExceptionInfo(e));
}
}
return "";
}
private String getApkNameByPath(String path) {
File file = new File(path + "output.json");
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(file);
byte[] strbuf = new byte[(int) file.length()];
fileInputStream.read(strbuf);
fileInputStream.close();
String s = new String(strbuf);
int position = s.indexOf("outputFile");
int position1 = s.indexOf(".apk");
String currentNum = s.substring(position + 13, position1);
if (currentNum.length() > 2) {
// return currentNum;
} else if (currentNum.length() == 2) {
currentNum += "0";
} else if (currentNum.length() == 1) {
currentNum += "00";
}
System.out.println("当前要上传的文件名称是==" + currentNum + "==");
return currentNum;
} catch (Exception e) {
System.out.println("finally中异常:<br>" + getExceptionInfo(e));
} finally {
try {
if (fileInputStream != null) {
fileInputStream.close();
}
} catch (IOException e) {
System.out.println("finally中异常:<br>" + getExceptionInfo(e));
}
}
return "";
}
//上传文件的第二种方法,优化了传输速度
private void putFileToFTpFast() {
OutputStream os = null;
FileInputStream fis = null;
try {
//权限问题可能会导致os=null,进而上传失败
//上传ftp文件需要扫描,扫描不成功禁止上传同样会导致os=null
//异常信息:java.net.SocketException: Connection reset
os = ftp.storeFileStream(getApkName() + ".apk");
System.out.println("获ftp的输出流的响应=" + ftp.getReplyString() + "=获ftp的输出流的响应");
System.out.println("获取到的ftp的输出流=" + os);
// fis = new FileInputStream(new File("E:\\008.apk"));
fis = new FileInputStream(new File("C:\\Users\\chennana\\work\\apk\\localv7\\aviview_v7" +
"\\app\\build\\outputs\\apk\\debug\\" +
getApkName() + ".apk"));
byte[] b = new byte[1024];
int len;
while ((len = fis.read(b)) != -1) {
os.write(b, 0, len);
}
System.out.println("上传文件到ftp成功!");
} catch (Exception ex) {
System.out.println("登录FTP异常:<br>" + getExceptionInfo(ex));
} finally {
try {
if (os != null) {
os.close();
}
if (fis != null) {
fis.close();
}
ftp.logout();
if (ftp.isConnected()) {
ftp.disconnect();
}
System.out.println("finally块执行成功!");
} catch (IOException e) {
System.out.println("finally中异常:<br>" + getExceptionInfo(e));
e.printStackTrace();
}
}
}
private void putFileToFTpFastByPath(String path) {
OutputStream os = null;
FileInputStream fis = null;
try {
os = ftp.storeFileStream(getApkNameByPath(path) + ".apk");
System.out.println("获ftp的输出流的响应=" + ftp.getReplyString() + "=");
System.out.println("获取到的ftp的输出流=" + os);
// fis = new FileInputStream(new File("E:\\008.apk"));
fis = new FileInputStream(new File(path +
getApkName() + ".apk"));
byte[] b = new byte[1024];
int len;
while ((len = fis.read(b)) != -1) {
os.write(b, 0, len);
}
System.out.println("上传文件到ftp成功!");
} catch (Exception ex) {
System.out.println("上传文件到ftp失败:<br>" + getExceptionInfo(ex));
} finally {
try {
if (os != null) {
os.close();
}
if (fis != null) {
fis.close();
}
ftp.logout();
if (ftp.isConnected()) {
ftp.disconnect();
}
} catch (IOException e) {
System.out.println("finally中异常:<br>" + getExceptionInfo(e));
}
}
}
/**
* 获取异常输出信息
*/
private String getExceptionInfo(Exception ex) {
StringWriter stringWriter = new StringWriter();
PrintWriter writer = new PrintWriter(stringWriter);
ex.printStackTrace(writer);
StringBuffer buffer = stringWriter.getBuffer();
return buffer.toString();
}
/**
* 通过命令行向主函数传递参数
* <p>
* java -jar PutFileToFtp.jar E:\ideademo\out\artifacts\PutFileToFtp_jar(需要传递的参数)
* <p>
* cmd命令行传递参数说明
* 第一个参数 output.json文件所在路径
* 第二个参数 ftp的ip地址
* 第三个参数 ftp端口号
* 第四个参数 用户名
* 第五个参数 密码
*/
public static void main(String[] args) {
FtpUpload ftpUpload;
String path = "";
if (args.length == 1) {
System.out.println("命令行传递的参数" + args[0]);
path = args[0];
System.out.println("传递的文件路径==" + path + "==");
ftpUpload = new FtpUpload("192.168.0.18", 21, "yintenglong", "yintenglong");
} else if (args.length == 5) {
path = args[0];
ftpUpload = new FtpUpload(args[1], Integer.parseInt(args[2]), args[3], args[4]);
System.out.println("ftp相关参数,ip=" + args[1] + ",port=" + args[2] + ",name=" + args[3] + ",pwd=" + args[4] + ",=");
} else {
System.out.println("命令行没有传递的参数");
ftpUpload = new FtpUpload("192.168.0.18", 21, "yintenglong", "yintenglong");
}
if (path.length() > 0) {
ftpUpload.putFileToFTpFastByPath(path);
} else {
System.out.println("未传递文件路径,使用默认路径");
ftpUpload.putFileToFTpFast();
}
}
}