base64和文件互转小工具-Java界面版

良辰

共 11938字,需浏览 24分钟

 · 2021-03-21

前言

由于工作中经常需要base64和文件之间相互转换,于是想到开发一个小工具来快速转换,这样就不用每次打开写好的代码编译执行了。搞了两个版本,此为Java版。

可以选择开发JavaWeb版本和开发桌面应用版本,我这里选择使用Java Swing开发Java桌面应用,那样打包出来可以不用依赖浏览器了。

Java Swing的开发教程这里找了一篇网上的资料:

https://blog.csdn.net/xietansheng/article/details/72814492

官方文档也贴一下:

https://docs.oracle.com/javase/tutorial/uiswing/index.html


需求功能

Swing就不在说了,不了解的同学可以去看看教程,不难。先说一下实现的功能:

  1. 能将任何文件(例如zip,png,txt,xlsx等等格式)转换为base64字符串,并将转换出来的base64字符串保存在该文件的当前目录的一个同名txt文件中,同名文件会覆盖。

  2. 能将转换后的base64字符串还原为文件,这里需要指定文件的后缀名,也就是还原成什么格式的文件。选择保存了base64的字符串的txt,即可转换成原文件。

  3. 每次转换有弹窗提示,并且在下方的文本框中输出转换结果。

  4. 能记录上次选择的目录,第二次选择文件的时候会默认打开前一次打开的地方。


代码实现

代码结构

02ca449224402f00b6021b99d42e0e10.webp

Base64TransformFrame.java

//自定义窗口类
public class Base64TransformFrame extends JFrame {

   private JButton toBase64Button = new JButton("toBase64");
   private JButton toFileButton = new JButton("toFile");
   private JTextField suffixText = new JTextField("zip");
   private JTextArea textArea = new JTextArea();
   private String currentDirectoryPath = null;

   public Base64TransformFrame(String title){
       super(title);
       this.setIconImage(new ImageIcon(getClass().getResource("/images/base64Transform/transform.png")).getImage());

       //内容面板
       Container container = getContentPane();
       container.setLayout(new BorderLayout());
       toBase64Button.setPreferredSize(new Dimension(100,30));
       toFileButton.setPreferredSize(new Dimension(100,30));

       suffixText.setToolTipText("请填写文件后缀,如zip");
       suffixText.setPreferredSize(new Dimension(60,30));

       JPanel panel = new JPanel();
       panel.setLayout(new FlowLayout());
       panel.add(toBase64Button);
       panel.add(toFileButton);
       panel.add(suffixText);

       container.add(panel,BorderLayout.NORTH);
       container.add(textArea,BorderLayout.CENTER);
       textArea.setFont(new Font("微软雅黑",0,16));


       toBase64Button.addActionListener((e)->{
           JFileChooser jf = new JFileChooser(currentDirectoryPath);
           jf.showOpenDialog(this);//显示打开的文件对话框
           File file =  jf.getSelectedFile();//使用文件类获取选择器选择的文件
           if(file == null){
               JOptionPane.showMessageDialog(this,"请选择文件!","提示",JOptionPane.WARNING_MESSAGE);
               return;
          }
           currentDirectoryPath = file.getParent();
           String filePath = file.getAbsolutePath();//返回路径名
           String base64FilePath = null;
           try {
               base64FilePath = Base64TransformTool.fileToBase64Str(filePath,null);
          } catch (IOException ioException) {
               ioException.printStackTrace();
          }
           String message = "ToBase64成功,文件路径为:"+base64FilePath;
           textArea.append(message+"\n");
           //JOptionPane弹出对话框类,显示绝对路径名
           JOptionPane.showMessageDialog(this, message, "提示",JOptionPane.INFORMATION_MESSAGE);
      });

       toFileButton.addActionListener((e)->{
           JFileChooser jf = new JFileChooser(currentDirectoryPath);
           jf.showOpenDialog(this);//显示打开的文件对话框
           File file =  jf.getSelectedFile();//使用文件类获取选择器选择的文件
           if(file == null){
               JOptionPane.showMessageDialog(this,"请选择文件!","提示",JOptionPane.WARNING_MESSAGE);
               return;
          }
           currentDirectoryPath = file.getParent();
           String base64FilePath = file.getAbsolutePath();//返回路径名
           String fileSuffix = suffixText.getText();
           if(fileSuffix==null || "".equals(fileSuffix)){
               JOptionPane.showMessageDialog(this,"请输入文件后缀");
          }
           String filePath = null;
           try {
              filePath = Base64TransformTool.base64ToFile(base64FilePath,null,fileSuffix);
          } catch (IOException ioException) {
               ioException.printStackTrace();
          }
           String message = "ToFile成功,文件路径为:"+filePath;
           textArea.append(message+"\n");
           //JOptionPane弹出对话框类,显示绝对路径名
           JOptionPane.showMessageDialog(this, message , "提示",JOptionPane.INFORMATION_MESSAGE);
      });
  }
}


Base64TransformTool.java

//文件与base64字符相互转换的工具类
public class Base64TransformTool {

   /**
    * 将文件转换为base64字符串,并写入txt文本文件(由于base64字符可能会很长)
    * 返回保存base64字符串的路径
    *
    * @param filePath     需要转换的文件的路径
    * @param base64FileDir 保存base64字符串的路径,默认当前路径
    * @return 返回保存base64字符串的路径
    */
   public static String fileToBase64Str(String filePath, String base64FileDir) throws IOException {
       checkParamNotNull(filePath);
       Path path = Paths.get(filePath);
       byte[] fileBytes = Files.readAllBytes(path);
       byte[] base64Byte = Base64.getEncoder().encode(fileBytes);
       String fileName = path.getFileName().toString();
       String base64FileName = fileName.substring(0, fileName.lastIndexOf(".")) + ".txt";
       Files.write(Paths.get(path.getParent().toString(), base64FileName), base64Byte);
       return path.getParent().toString() + File.separator + base64FileName;
  }

   /**
    * 将base64字符串还原成文件
    * 返回文件路径
    * @param base64FilePath base64字符串的文件路径
    * @param filePath       还原的文件路径,默认当前ase64字符串的文件路径
    * @param suffix         文件后缀名
    * @return 返回文件路径
    */
   public static String base64ToFile(String base64FilePath, String filePath, String suffix) throws IOException {
       checkParamNotNull(base64FilePath,suffix);
       if(filePath == null){
           filePath = base64FilePath.substring(0,base64FilePath.lastIndexOf(".")+1)
                   + suffix;
      }
       byte[] base64Byte = Files.readAllBytes(Paths.get(base64FilePath));
       try {
           Files.write(Paths.get(filePath), Base64.getDecoder().decode(base64Byte), StandardOpenOption.CREATE);
      } catch (IOException e) {
           e.printStackTrace();
      }
       return filePath;
  }

   private static void checkParamNotNull(Object param,Object... others){
       if(param == null){
           throw new IllegalArgumentException("参数不能为空");
      }
       if(param instanceof String){
           if(((String) param).length() == 0){
               throw new IllegalArgumentException("参数不能为空");
          }
      }
       if(others!=null){
           Object[] params = others;
           for (Object o : params) {
               checkParamNotNull(o);
          }
      }
  }
}


Base64TransformUI.java

//UI启动类
public class Base64TransformUI {
   /**
    * 得到显示器屏幕的宽高
    */
   public static int windowsWidth = Toolkit.getDefaultToolkit().getScreenSize().width;
   public static int windowsHeight = Toolkit.getDefaultToolkit().getScreenSize().height;
   /**
    * 定义窗体的宽高
    */
   public static int frameWidth = 600;
   public static int frameHeight = 400;

   public static void createGUI(){
       //创建一个窗口
       Base64TransformFrame frame = new Base64TransformFrame("Base64<->File");
       //设置窗口关闭则退出程序
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

       //设置窗口大小
       frame.setSize(frameWidth,frameHeight);
       frame.setBounds((windowsWidth-frameWidth)/2,(windowsHeight-frameHeight)/2,frameWidth,frameHeight);

       //显示窗口
       frame.setVisible(true);
  }

   public static void main(String[] args) {
       SwingUtilities.invokeLater(()->createGUI());
  }
}


pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>

   <groupId>groupId</groupId>
   <artifactId>common-tools</artifactId>
   <version>1.0-SNAPSHOT</version>

   <properties>
       <java.version>1.8</java.version>
       <maven.compiler.source>1.8</maven.compiler.source>
       <maven.compiler.target>1.8</maven.compiler.target>
   </properties>


   <build>
       <finalName>common-tools</finalName>
       <plugins>
           <plugin>
               <groupId>org.apache.maven.plugins</groupId>
               <artifactId>maven-shade-plugin</artifactId>
               <version>3.2.1</version>
               <executions>
                   <execution>
                       <phase>package</phase>
                       <goals>
                           <goal>shade</goal>
                       </goals>
                       <configuration>
                           <transformers>
                               <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                   <!--这里写你的main函数所在的类的路径名,也就是Class.forName的那个字符串-->
                                   <mainClass>common.tools.base64transform.ui.Base64TransformUI</mainClass>
                               </transformer>
                           </transformers>
                       </configuration>
                   </execution>
               </executions>
           </plugin>
       </plugins>
   </build>
</project>

最终效果

a860d9595a2f0f907942bb5f9923cc59.webp

12515210f289e6fb74f899d9a99a4c72.webp

b747211074ffeaf5783f3ceb2aa37db6.webp

b530f6b55603bbc71880074e23da353e.webp

并不好看,但是上述功能还是实现了。但是这样每次都要打开自己的idea去执行还是有点麻烦,所以我想把它打成一个可执行文件exe。


安装包制作

打包代码为jar

点击maven->package或者到项目目录执行mvn package

8eaed6b333ea7421b33a25a8acd0dcbb.webp

得到common-tools.jar,在target目录可以找到。

exe4j将jar打包成exe

链接:https://pan.baidu.com/s/1HrnqjSGUZB2U_gqSCdvtrw

提取码:1mri 注册码:L-g782dn2d-1f1yqxx1rv1sqd

可参考这篇文章:https://blog.csdn.net/m0_37701381/article/details/104163877

只是有两个地方需要注意,一个是注册码的输入。

50a93dda5d5fce799508e476ad6c4289.webp

另一个是,如果不想要exe运行的时候出来一个cmd窗口就选择GUI application

e0a0a27f873724f80e594524a2c95efa.webp

其他的按照上面那位大佬写的进行操作即可。操作完成会得到一个exe程序,双击即可运行。


inno setup将exe和jre进行打包合并

操作到上面那步其实已经得到exe了,为什么还需要进行和jre合并呢?那是为了可以让咱们这个exe可以安装到任何的window电脑,那个电脑不需要安装java环境,安装我们这个即可运行。

链接:https://pan.baidu.com/s/1-yirBtvg1Ck16p4__BYYFw提取码:md7u

这个基本也可以按照上面那位大佬的教程进行操作即可,这里不在累赘,附上一下脚本配置:

; Script generated by the Inno Setup Script Wizard.
; SEE THE DOCUMENTATION FOR DETAILS ON CREATING INNO SETUP SCRIPT FILES!

#define MyAppName "Base64TransformTool"
#define MyAppVersion "1.5"
#define MyAppPublisher "My Company, Inc."
#define MyAppURL "http://www.example.com/"
#define MyAppExeName "Base64TransformTool1.1.exe"

#define MyJreName "jre"

[Setup]
; NOTE: The value of AppId uniquely identifies this application.
; Do not use the same AppId value in installers for other applications.
; (To generate a new GUID, click Tools | Generate GUID inside the IDE.)
AppId={{DF8BE89A-E1F5-4ABE-ACDC-5B079BB7C637}
AppName={#MyAppName}
AppVersion={#MyAppVersion}
;AppVerName={#MyAppName} {#MyAppVersion}
AppPublisher={#MyAppPublisher}
AppPublisherURL={#MyAppURL}
AppSupportURL={#MyAppURL}
AppUpdatesURL={#MyAppURL}
DefaultDirName={pf}\{#MyAppName}
DisableProgramGroupPage=yes
OutputDir=C:\Users\pc-luo\Desktop\exe
OutputBaseFilename=setup
Compression=lzma
SolidCompression=yes

[Languages]
Name: "english"; MessagesFile: "compiler:Default.isl"

[Tasks]
Name: "desktopicon"; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}"; Flags: unchecked

[Files]
Source: "C:\Users\pc-luo\Desktop\exe\Base64TransformTool1.1.exe"; DestDir: "{app}"; Flags: ignoreversion
Source: "D:\install\Java\jre1.8.0_201\*"; DestDir: "{app}\{#MyJreName}"; Flags: ignoreversion recursesubdirs createallsubdirs
; Source: "C:\Users\pc-luo\Desktop\Base64TransformTool.exe"; DestDir: "{app}"; Flags: ignoreversion
; NOTE: Don't use "Flags: ignoreversion" on any shared system files

[Icons]
Name: "{commonprograms}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"
Name: "{commondesktop}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"; Tasks: desktopicon

[Run]
Filename: "{app}\{#MyAppExeName}"; Description: "{cm:LaunchProgram,{#StringChange(MyAppName, '&', '&&')}}"; Flags: nowait postinstall skipifsilent

最终得到setup.exe安装包程序,下面截图里面的名字是我自己重命名了一下的。

a01453514ea3f8464cc60d031f0bf8c0.webp

双击它是会出来安装步骤的:

009c3d727d01291e2a461f4f01eb36c5.webp

一直下一步,安装完成之后的安装目录结构是这样的:

fde7c3286d29795b01f578689b8c9b9b.webp

双击Base64TransformTool1.1.exe即可运行,双击uninx000.exe即可卸载。至此,base64和文件互转小工具java版就结束了。


终于打破我的Flag了,一直都是在想却没有去做去实现,这是个好的开始。好了,本次内容就是这些,学无止境,关注我,我们一起学习进步。如果觉得内容还可以,帮忙点个赞,点个在看呗,谢谢~我们下期见。


浏览 87
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报