2010. 8. 23. 16:33 JAVA



한글로 된 파일도 압축 가능하게 한다
jazzlib.jar파일을 추가 해서 컴파일 한다

import java.awt.BorderLayout;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import javax.swing.SwingUtilities;


/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class NewJFrame extends javax.swing.JFrame {
 private JPanel jPanel1;
 public JButton jButton1;
 public JButton jButton2;
 public JTextField jTextField2;
 public JTextField jTextField1;
 public JTextField jTextField3;
 public JLabel jLabel1;
 /**
 * Auto-generated main method to display this JFrame
 */
 public static void main(String[] args) {
  SwingUtilities.invokeLater(new Runnable() {
   public void run() {
    NewJFrame inst = new NewJFrame();
    inst.setLocationRelativeTo(null);
    inst.setVisible(true);
   }
  });
 }
 boolean fFirst;
 String strdir[]= new String[3];
 public void CheckFirstFile() {
  fFirst = true;
  try {
   BufferedReader in = new BufferedReader(new FileReader(
     "c:\\dialogzip.txt"));
   strdir[0] = in.readLine();
   strdir[1] = in.readLine();
   strdir[2] = in.readLine();
   System.out.println(strdir[0]+" "+strdir[1]+" "+strdir[2]);
   in.close();
   fFirst = false;
  } catch (Exception e) {   
   System.out.println(e);
  }
 }
 public void SaveFile()
 {
  try {
   BufferedWriter in = new BufferedWriter(new FileWriter(
     "c:\\dialogzip.txt"));
   in.write(jTextField1.getText());
   in.newLine();
   in.write(jTextField2.getText());
   in.newLine();
   in.write(jTextField3.getText());

   in.close();
  } catch (Exception e) {
   
   System.out.println(e);
  }
 }

 public NewJFrame() {
  super();
  strdir[0]="D:\\project\\src";
  strdir[1]="D:\\project\\resource";
  strdir[2]="D:\\project\\backup";
  CheckFirstFile();
  initGUI();
 }
 
 private void initGUI() {
  try {
   setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
   {
    
    jPanel1 = new JPanel();
    jPanel1.setLayout(null);
    getContentPane().add(jPanel1, BorderLayout.CENTER);
    setTitle("소스압축하기,리소스압축하기");
    {
     jTextField1 = new JTextField();
     jPanel1.add(jTextField1);
     jTextField1.setBounds(34, 20, 280, 22);
     jTextField1.setText(strdir[0]);
    }
    {
     jButton1 = new JButton();
     jPanel1.add(jButton1);
     jButton1.setText("소스압축");
     jButton1.setBounds(34, 50, 112, 22);
    }
    {
     jTextField2 = new JTextField();
     jPanel1.add(jTextField2);
     jTextField2.setBounds(34, 80, 280, 22);
     jTextField2
       .setText(strdir[1]);
    }
    {
     jButton2 = new JButton();
     jPanel1.add(jButton2);
     jButton2.setText("리소스압축");
     jButton2.setBounds(34, 110, 112, 22);
    }
    {
     jTextField3 = new JTextField();
     jPanel1.add(jTextField3);
     jTextField3.setBounds(34, 140, 280, 22);
     jTextField3
       .setText(strdir[2]);
    }
    {
     jLabel1 = new JLabel();
     jPanel1.add(jLabel1);
     jLabel1.setBounds(34,170,280,22);
     
    }
   }
   FrameEventListener eventr = new FrameEventListener(this);
   jButton1.addActionListener(eventr);
   jButton2.addActionListener(eventr);
   
   
   pack();
   setSize(400, 300);
  } catch (Exception e) {
      //add your error handling code here
   e.printStackTrace();
  }
 }

}
////////////////////////////////////////////////////////////////////////////

import java.awt.FileDialog;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.util.Calendar;
import java.util.Vector;

import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;

public class FrameEventListener implements ActionListener {

 NewJFrame frame;

 public FrameEventListener(NewJFrame frame) {
  this.frame = frame;

 }

 public void LabelMessage(String str) {

 }

 public void actionPerformed(ActionEvent ae) {// 버튼 관련

  if (ae.getSource() == frame.jButton1) {// 테이블에 추가

   
   Compress compress = new Compress();
   Calendar cal = Calendar.getInstance();
   String target = frame.jTextField3.getText();
   String from = frame.jTextField1.getText();
   String fileName = "SRC" + "_" + (cal.get(Calendar.MONTH) + 1) + "_"
     + cal.get(Calendar.DAY_OF_MONTH) + "_"
     + cal.get(Calendar.HOUR_OF_DAY) + ".ZIP";

   System.out.println(from + " " + fileName);
   try {
    compress.zip(from, target+"\\"+fileName);
   } catch (Exception e) {
    System.out.println(e);
   }
   frame.SaveFile();
   System.out.println("success"+from + " " + fileName);
   //frame.jLabel1.setText("압축완료");
   //frame.jLabel1.updateUI();
  } else if (ae.getSource() == frame.jButton2) {// 테이블에 삭제
   Compress compress = new Compress();
   Calendar cal = Calendar.getInstance();
   String target = frame.jTextField3.getText();
   String from = frame.jTextField2.getText();
   String fileName = "resource" + "_" + (cal.get(Calendar.MONTH) + 1) + "_"
     + cal.get(Calendar.DAY_OF_MONTH) + "_"
     + cal.get(Calendar.HOUR_OF_DAY) + ".ZIP";

   System.out.println(from + " " + fileName);
   try {
    compress.zip(from, target+"\\"+fileName);
   } catch (Exception e) {
    System.out.println(e);
   }
   frame.SaveFile();
   System.out.println("success"+from + " " + fileName);
   //frame.jLabel1.setText("압축완료");
   //frame.jLabel1.updateUI();
  }

 }

 public void valueChanged(TreeSelectionEvent ae) {

 }

}

////////////////////////////////////////////////////////////////////////////

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import net.sf.jazzlib.ZipEntry;
import net.sf.jazzlib.ZipInputStream;
import net.sf.jazzlib.ZipOutputStream;


//import java.util.zip.ZipEntry;
//import java.util.zip.ZipInputStream;
///import java.util.zip.ZipOutputStream;

//import org.apache.commons.lang.StringUtils;

public class Compress {

    private static final int COMPRESSION_LEVEL = 8;

    private static final int BUFFER_SIZE = 1024 * 2;
 /*public static void main(String[] args) {
  compressTest utils = new compressTest();
  try
  {
   utils.zip("d:\\bb","d:\\bb\\bb.zip");
   System.out.println("11111111");
  }catch(Exception e)
  {
   System.out.println(e);
  }
 }*/
    /**
     * 지정된 폴더를 Zip 파일로 압축한다.
     * @param sourcePath - 압축 대상 디렉토리
     * @param output - 저장 zip 파일 이름
     * @throws Exception
     */
    public static void zip(String sourcePath, String output) throws Exception {

        // 압축 대상(sourcePath)이 디렉토리나 파일이 아니면 리턴한다.
        File sourceFile = new File(sourcePath);
        if (!sourceFile.isFile() && !sourceFile.isDirectory()) {
            throw new Exception("압축 대상의 파일을 찾을 수가 없습니다.");
        }

        // output 의 확장자가 zip이 아니면 리턴한다.
      //  if (!(StringUtils.substringAfterLast(output, ".")).equalsIgnoreCase("zip")) {
        //    throw new Exception("압축 후 저장 파일명의 확장자를 확인하세요");
        //}

        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        ZipOutputStream zos = null;

        try {
            fos = new FileOutputStream(output); // FileOutputStream
            bos = new BufferedOutputStream(fos); // BufferedStream
            zos = new ZipOutputStream(bos); // ZipOutputStream
            zos.setLevel(COMPRESSION_LEVEL); // 압축 레벨 - 최대 압축률은 9, 디폴트 8
            zipEntry(sourceFile, sourcePath, zos); // Zip 파일 생성
            zos.finish(); // ZipOutputStream finish
        } finally {
            if (zos != null) {
                zos.close();
            }
            if (bos != null) {
                bos.close();
            }
            if (fos != null) {
                fos.close();
            }
        }
    }

    /**
     * 압축
     * @param sourceFile
     * @param sourcePath
     * @param zos
     * @throws Exception
     */
    private static void zipEntry(File sourceFile, String sourcePath, ZipOutputStream zos) throws Exception {
        // sourceFile 이 디렉토리인 경우 하위 파일 리스트 가져와 재귀호출
        if (sourceFile.isDirectory()) {
            if (sourceFile.getName().equalsIgnoreCase(".metadata")) { // .metadata 디렉토리 return
                return;
            }
            File[] fileArray = sourceFile.listFiles(); // sourceFile 의 하위 파일 리스트
            for (int i = 0; i < fileArray.length; i++) {
                zipEntry(fileArray[i], sourcePath, zos); // 재귀 호출
            }
        } else { // sourcehFile 이 디렉토리가 아닌 경우
            BufferedInputStream bis = null;
            try {
                String sFilePath = sourceFile.getPath();
                String zipEntryName = sFilePath.substring(sourcePath.length() + 1, sFilePath.length());

                bis = new BufferedInputStream(new FileInputStream(sourceFile));
                ZipEntry zentry = new ZipEntry(zipEntryName);
                zentry.setTime(sourceFile.lastModified());
                zos.putNextEntry(zentry);

                byte[] buffer = new byte[BUFFER_SIZE];
                int cnt = 0;
                while ((cnt = bis.read(buffer, 0, BUFFER_SIZE)) != -1) {
                    zos.write(buffer, 0, cnt);
                }
                zos.closeEntry();
            } finally {
                if (bis != null) {
                    bis.close();
                }
            }
        }
    }

    /**
     * Zip 파일의 압축을 푼다.
     *
     * @param zipFile - 압축 풀 Zip 파일
     * @param targetDir - 압축 푼 파일이 들어간 디렉토리
     * @param fileNameToLowerCase - 파일명을 소문자로 바꿀지 여부
     * @throws Exception
     */
    /*
    public static void unzip(File zipFile, File targetDir, boolean fileNameToLowerCase) throws Exception {
        FileInputStream fis = null;
        ZipInputStream zis = null;
        ZipEntry zentry = null;

        try {
            fis = new FileInputStream(zipFile); // FileInputStream
            zis = new ZipInputStream(fis); // ZipInputStream

            while ((zentry = zis.getNextEntry()) != null) {
                String fileNameToUnzip = zentry.getName();
                if (fileNameToLowerCase) { // fileName toLowerCase
                    fileNameToUnzip = fileNameToUnzip.toLowerCase();
                }

                File targetFile = new File(targetDir, fileNameToUnzip);

                if (zentry.isDirectory()) {// Directory 인 경우
                 //   FileUtils.makeDir(targetFile.getAbsolutePath()); // 디렉토리 생성
                } else { // File 인 경우
                    // parent Directory 생성
                   // FileUtils.makeDir(targetFile.getParent());
                    unzipEntry(zis, targetFile);
                }
            }
        } finally {
            if (zis != null) {
                zis.close();
            }
            if (fis != null) {
                fis.close();
            }
        }
    }
*/
    /**
     * Zip 파일의 한 개 엔트리의 압축을 푼다.
     *
     * @param zis - Zip Input Stream
     * @param filePath - 압축 풀린 파일의 경로
     * @return
     * @throws Exception
     */
    /*
    protected static File unzipEntry(ZipInputStream zis, File targetFile) throws Exception {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(targetFile);

            byte[] buffer = new byte[BUFFER_SIZE];
            int len = 0;
            while ((len = zis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
        } finally {
            if (fos != null) {
                fos.close();
            }
        }
        return targetFile;
    }
    */
}

'JAVA' 카테고리의 다른 글

java 폴더 파일 명과 디렉토리 명 뽑아오기  (0) 2011.06.24
MFC CBUTTON에 단축키 설정하기  (0) 2011.01.21
에러 수정방법  (0) 2010.08.20
JAVA SAMPLE 사이트  (0) 2010.08.17
JAVA 로 GUI프로그램 만들기  (0) 2010.08.17
posted by 욱이다