65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 C# 打开 Jar 文件

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.88/5 (6投票s)

2008 年 7 月 8 日

CPOL

4分钟阅读

viewsIcon

61016

downloadIcon

1746

本文将介绍一种可用于提取 Jar 文件的方法。

引言

本文将介绍一种可用于提取 Jar 文件的方法。Jar 文件本质上是使用 zip 压缩的文件;标准 zip 压缩文件和 jar 文件的主要区别在于 jar 文件包含清单文件;真正的 jar 文件也可以在安装了 Java 运行时的机器上作为可执行文件运行。Jar 文件通常包含 Java 类文件;如果您需要提取 jar 文件并查看其内容,这并不比解压缩普通 zip 文件更难。

image001.png
图 1:提取 Jar 文件

由于提取 jar 文件的任务实际上与提取 zip 文件相同,因此演示应用程序将依赖于免费的 SharpZipLib 库来执行提取;这些库可以从以下位置下载: 用于 .NET 的 Zip、GZip、BZip2 和 Tar 实现

除了处理 jar 和 zip 文件外,该库还处理 tar、gzip 和 bzip2 压缩。

解决方案

该解决方案包含一个单独的项目(Jars)。该示例以单个 Windows Forms 项目的形式提供;该项目包含一个主窗体;所有引用都在默认配置中,但 SharpZipLib DLL 已被添加(引用列表中的第一项)。从 .NET 平台的开源项目 页面下载 DLL 后,下载文件已安装到本地文件系统,并使用“添加引用”对话框的“浏览”选项添加。驱动应用程序所需的所有代码都包含在主窗体的代码文件中。

image002.png
图 2:显示项目的解决方案资源管理器

代码:Jars – Form1

Jars 项目是一个包含单个窗体的 Windows Forms 项目。项目所需的所有 UI 和代码都包含在单个主窗体中。

除了默认值之外,添加到项目的唯一引用是支持在该项目中使用 SharpZipLib 所必需的引用。导入、命名空间和类声明如下

using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ICSharpCode.SharpZipLib.Zip;
using System.IO;

namespace Jars
{
    public partial class Form1 : Form
    {

在类声明之后,声明了两个私有变量;这些变量用于保留 jar 文件的路径和目标文件夹的路径(jar 将被解压缩到的位置)。

    // set variables to hold
    // the paths to the jar file and
    // to destination folder
    private string mSourceJar;
    private string mDestinationFolder;

下一个代码块是默认构造函数;没有添加任何内容

    // default constructor
    public Form1()
    {
        InitializeComponent();
    }

下一个代码块用于执行实际提取。ExtractJar 函数接受两个参数,一个字符串值定义 jar 文件的路径,一个字符串值定义目标文件夹的路径(jar 将被解压缩到的位置)。该方法使用 SharpZipLibrary 提取 jar 文件。代码经过注释以描述活动。

/// <summary>
/// Extracts the jar file to a specified
/// destination folder.  
/// </summary>
private void ExtractJar(string pathToJar, string saveFolderPath)
{
    string jarPath = pathToJar;
    string savePath = saveFolderPath;

    try
    {
        // verify the paths are set
        if (!String.IsNullOrEmpty(jarPath) &&
            !String.IsNullOrEmpty(saveFolderPath))
        {
            try
            {
                // use the SharpZip library FastZip
                // utilities ExtractZip method to 
                // extract the jar file
                FastZip fz = new FastZip();
                fz.ExtractZip(jarPath, saveFolderPath, "");

                // Success at this point, tell the user
                // we are done.
                MessageBox.Show("Jar File: " + jarPath + " was 
                    extracted to " +
                    saveFolderPath, "Finished");

                // open the destination folder in explorer
                System.Diagnostics.Process.Start("explorer", 
                    saveFolderPath);
            }
            catch (Exception ex)
            {
                // something went wrong
                MessageBox.Show(ex.Message, "Extraction Error");
            }
        }
        else
        {
            // the paths were not, tell the user to 
            // get with the program

            StringBuilder sb = new StringBuilder();
            sb.Append("Set the paths to both the jar file and " + 
                Environment.NewLine);

            sb.Append("destination folder before attempting to " + 
                Environment.NewLine);

            sb.Append("to extract a jar file.");

            MessageBox.Show(sb.ToString(), "Unable to Extract");
        }
    }
    catch (Exception ex)
    {
        // something else went wrong
        MessageBox.Show(ex.Message, "Extraction Method Error");
    }  
}

下一个代码块用于设置 jar 文件的路径。此按钮单击事件处理程序用于显示打开文件对话框;用户可以使用该对话框导航到 jar 文件的位置并选择它。所选文件名用于将 mSourceJar 字符串变量设置为 jar 文件的文件路径;文件路径也显示在按钮旁边的文本框中。

/// <summary>
/// Set the path to the Jar File
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSetJar_Click(object sender, EventArgs e)
{
    try
    {
        OpenFileDialog1.Title = "Extract JAR";
        OpenFileDialog1.DefaultExt = "jar";
        OpenFileDialog1.Filter = "Jar Files|*.jar";
        OpenFileDialog1.FileName = string.Empty;
        OpenFileDialog1.Multiselect = false;

        if (OpenFileDialog1.ShowDialog() == DialogResult.OK)
        {
            if (OpenFileDialog1.FileName == "")
            {
                return;
            }

            string strExt;
            strExt = 
                System.IO.Path.GetExtension(OpenFileDialog1.FileName);
            strExt = strExt.ToUpper();

            if (strExt == ".JAR")
            {
                mSourceJar = OpenFileDialog1.FileName;
                txtJarPath.Text = mSourceJar;
            }
            else
            {
                MessageBox.Show("The selected file is not a jar", 
                    "File Error");
            }

        }
        else
        {
            MessageBox.Show("File request cancelled by user.", 
                "Cancelled");
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message.ToString(), "Error");
    }
}

下一个代码段用于设置目标文件夹的路径。目标文件夹定义所选 jar 文件将被解压缩到的位置。按钮单击事件处理程序打开一个文件夹浏览器对话框,该对话框允许用户导航到和/或创建目标文件夹。设置完成后,文件夹浏览器对话框的所选路径属性用于 mDestinationFolder 变量,并且它也用于使用所选路径的值来显示所选目标文件夹路径。

        /// <summary>
        /// Set the path to the destination folder
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDestinationFolder_Click(object sender, EventArgs e)
        {
            try
            {
                folderBrowserDialog1.ShowNewFolderButton = true;

                DialogResult result = folderBrowserDialog1.ShowDialog();
                if (result == DialogResult.OK)
                {
                    mDestinationFolder = folderBrowserDialog1.SelectedPath;
                    txtDestinationFolder.Text = mDestinationFolder;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error Setting Destination 
                Folder");
            }
        }

最后一个按钮单击事件处理程序用于调用 ExtractJar 方法。单击事件处理程序仅调用 ExtractJar 方法,并将其传递给用于包含源 jar 文件和目标文件夹的两个变量。

/// <summary>
/// Use the ExtractJar function to
/// extract the source jar file into the
/// destination folder
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnExtract_Click(object sender, EventArgs e)
{
    ExtractJar(mSourceJar, mDestinationFolder);
}

这样就结束了对该项目中使用的代码的描述。

摘要

此示例演示了使用 SharpZipLib 提取 jar 文件;Jar 文件只不过是包含一些元数据以及(通常)Java 类文件的 zip 压缩存档;提取它们并不比提取普通 zip 存档更难;特别是借助 SharpZipLib 的帮助。

© . All rights reserved.