Создание исполняемого файла JAR для моего приложения Java - PullRequest
2 голосов
/ 24 марта 2010
public class createExcel {

public  void write() throws IOException, WriteException {

        WorkbookSettings wbSettings = new WorkbookSettings();
        wbSettings.setLocale(new Locale("en", "EN"));
        WritableWorkbook workbook1 =Workbook.createWorkbook(new File(file), wbSettings);
        workbook1.createSheet("Niru ", 0);
        WritableSheet excelSheet = workbook1.getSheet(0);
        createLabel(excelSheet);
        createContent(excelSheet,list);
        workbook1.write();
        workbook1.close();
    }


 public void createLabel(WritableSheet sheet)throws WriteException {

WritableFont times10pt = new WritableFont(WritableFont.createFont("D:\font\trebuct"),8);

// Define the cell format

        times = new WritableCellFormat(times10pt);
        // Lets automatically wrap the cells
        times.setWrap(false);
        WritableFont times10ptBoldUnderline = new WritableFont(
        WritableFont.createFont("D:\font\trebuct"), 9, WritableFont.BOLD, false,
        UnderlineStyle.NO_UNDERLINE);
        timesBoldUnderline = new WritableCellFormat(times10ptBoldUnderline);

        sheet.setColumnView(0,15);
                sheet.setColumnView(1,13);

        // Write a few headers
        addCaption(sheet, 0, 0, "Business Date");
        addCaption(sheet, 1, 0, "Dealer ID");


    }
        private void createContent(WritableSheet sheet, ArrayList list) throws WriteException,RowsExceededException {
                // Write a few number
        for (int i = 1; i < 11; i++) {
                    for(int j=0;j<11;j++){
            // First column
            addNumber(sheet, i, j,1);
            // Second column
            addNumber(sheet, 1, i, i * i);
                    }
        }
            }
private void addCaption(WritableSheet sheet, int column, int row, String s)     throws RowsExceededException, WriteException {

        Label label;
        label = new Label(column, row, s, timesBoldUnderline);
                sheet.addCell(label);
    }

    private void addNumber(WritableSheet sheet,  int row,int column,
            Integer integer) throws WriteException, RowsExceededException {
        Number number;
        number = new Number(column,row, integer, times);
        sheet.addCell(number);
    }


public static void main(String[] args) {

        JButton myButton0 = new JButton("Advice_Report");
        JButton myButton1 = new JButton("Position_Report");
        JPanel bottomPanel = new JPanel();   
        bottomPanel.add(myButton0);
        bottomPanel.add(myButton1);  
        myButton0.addActionListener(this);
        myButton1.addActionListener(this);  
        createExcel obj=new  createExcel();
        obj.setOutputFile("c;\\temp\\swings\\jack.xls");
        try{
        obj.write();
        }catch(Exception e){}
}

и так далее. это работает нормально. У меня есть файлы jxl.jar и ojdbc14.jar (нужен этот файл jar для создания Excelsheet и подключения к БД) и файл createExcel.class (файл .class). как сделать этот код в виде исполняемого файла JAR.

Ответы [ 4 ]

2 голосов
/ 24 марта 2010

Есть несколько способов:

  1. Создайте JAR-файл и поместите туда свои классы (без зависимостей). Для этого используйте какой-нибудь инструмент (он есть в любой IDE) и укажите класс с функцией main. Вы также можете сделать это вручную из командной строки. Когда пользователь хочет запустить его, он должен указать classpath и все зависимости должны быть в этом classpath.

  2. Создайте тот же самый jar-файл и создайте файл .bat или .sh, в котором установите classpath и запустите ваш jar.

  3. Создание кроссплатформенного установщика с помощью специального инструмента (но хорошие инструменты не бесплатны).

1 голос
/ 24 марта 2010

Вы создаете JAR-файл, выполняя следующую команду:

jar -cvfm excel.jar MANIFEST.MF *.class

Файл MANIFEST.MF должен содержать следующую строку:

Main-Class: createExcel
1 голос
/ 24 марта 2010

Вам нужно создать банку, которая содержит ваш .class и файл манифеста. Я предлагаю вам прочитать http://java.sun.com/docs/books/tutorial/deployment/jar/manifestindex.html и опубликовать дополнительные вопросы.

0 голосов
/ 24 марта 2010

Если вам нужно создать файл .jar, то вы можете использовать инструмент командной строки «jar».Вот его описание и варианты / использование:

Usage: jar {ctxui}[vfm0Me] [jar-file] [manifest-file] [entry-point] [-C dir] files ...
Options:
    -c  create new archive
    -t  list table of contents for archive
    -x  extract named (or all) files from archive
    -u  update existing archive
    -v  generate verbose output on standard output
    -f  specify archive file name
    -m  include manifest information from specified manifest file
    -e  specify application entry point for stand-alone application
        bundled into an executable jar file
    -0  store only; use no ZIP compression
    -M  do not create a manifest file for the entries
    -i  generate index information for the specified jar files
    -C  change to the specified directory and include the following file
If any file is a directory then it is processed recursively.
The manifest file name, the archive file name and the entry point name are
specified in the same order as the 'm', 'f' and 'e' flags.

Example 1: to archive two class files into an archive called classes.jar:
       jar cvf classes.jar Foo.class Bar.class
Example 2: use an existing manifest file 'mymanifest' and archive all the
           files in the foo/ directory into 'classes.jar':
       jar cvfm classes.jar mymanifest -C foo/ .

Надеюсь, это поможет.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...