Java的檔案操作--1

來源:互聯網
上載者:User
前兩天看了《java核心編程》中對於java中的IO輸入輸出講解,收穫良多,下面的程式是我讀完書以後自己寫的一個將zip檔案集中的檔案內容讀取出來然後顯示(只限於文本,其他檔案將會產生亂碼),此程式也可通過改進可以得到一個和winzip功能一樣的類(但是沒有介面,主要是awt不會:--(  ),過兩天就把源碼貼出來。很簡單的一個類,希望對大家有用。
這是本人第一次發文章,不足之處請多多指教!!!
/**
 *功能:Zip檔案釋放,Zip檔案目錄、選擇目錄後顯示檔案內容
 *  首先使用者輸入zip檔案路徑及名稱,讀取zip檔案將檔案集中的檔案清單顯示出來,
 *  使用者選擇需要顯示的檔案,之後通過DataInputStream類將檔案內容讀取出來並
 *  顯示在標準輸出端
 *日期:2005-06-27
 *作者:Pcera
 */
import java.util.*;
import java.util.zip.*;
import java.io.*;

class ZipFileHandle{
 private String[] FileNameArray;            //真實檔案名稱存放數組
 private String[] FileNameArrayShow;        //需要顯示的檔案名稱存放數組
 private ZipInputStream zipFile;            //zip輸入資料流對象
 private ZipEntry entry;                    //zip檔案入口對象
 private int zipFileCount = 0;              //zip中的檔案總數
 
 /**
  *初始化各個參數
  *通過類的套嵌來訪問檔案
  *將得到檔案的清單附值給數組,以便在後面使用者選擇時從數組中獲得檔案名稱
  */
 public ZipFileHandle(File file){
  try{ 
   while (!(file.exists())) {
    System.out.println("Plase input right path again: "); 
    BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
    String filepath = userInput.readLine();
    file = new File(filepath); 
   }  
   zipFile = new ZipInputStream(new FileInputStream(file));
   while ((zipFile.getNextEntry()) != null){
    zipFileCount++;
   }   
   FileNameArray = new String[zipFileCount];
   FileNameArrayShow = new String[zipFileCount];
  }catch(IOException e){
   System.out.println("初始化錯誤!!!");
   e.printStackTrace();
  } 
 }
 /**
  *組建檔案目錄
  *根據show的值來確定傳回值
  *如果show的值為"sh"則返回在螢幕上顯示的名稱
  *如果show的值為"gr"則返回實際名稱
  */
 public String[] getFileNameList(String show,File file){
  try{
   int i = 0;
   String FileName;
   zipFile = new ZipInputStream(new FileInputStream(file));
   while ((entry = zipFile.getNextEntry()) != null){
    FileName = entry.getName();
    //真實檔案名稱附值
    FileNameArray[i] = FileName;
    //顯示檔案名稱附值
    if (FileName.equals("")) FileName = "...";
    FileName = Integer.toString(i) + "-|" + FileName;
    FileNameArrayShow[i] = FileName;
    i++;
   }
   zipFile.close();
   //根據條件返迴文件數組
   if(show == "sh"){
    return FileNameArrayShow;
   }else{
    return FileNameArray;
   }   
  }catch(IOException e){
   System.out.println("讀取zip檔案內的檔案名稱出錯!!!");
   e.printStackTrace();
   return null;
  }
 }
 
 /**
  *讀取檔案內容
  *根據傳遞進來的zip檔案對象和
  *zip中所要顯示的檔案
  *使用者根據type來選擇返回的是unicode資訊還位元組資訊
  *如果type是"Str"則返回字串資訊,"Byte"則返回通過位元組獲得的檔案內容
  */
 public String loadFileCon(String fileName,File file,String type){
  String fileContent = "",conTemp = "";
  byte[] fileConfByte;
  try{
   //找到要顯示的檔案入口,然後讀取通過文字格式設定讀取檔案內容             
   zipFile = new ZipInputStream(new FileInputStream(file));
   //讀取檔案內容
   while ((entry = zipFile.getNextEntry()) != null){
    if (entry.getName().equals(fileName)){
     //通過位元組讀取檔案內容 
     if (type.equals("Byte")){ 
      fileConfByte = new byte[(int)entry.getSize()]; 
      DataInputStream reader = new DataInputStream(zipFile);
      reader.readFully(fileConfByte,0,(int)entry.getSize());
      fileContent = new String(fileConfByte);     
     }else if ((type.equals("Str"))){
      //通過unicode字元讀取檔案內容
      BufferedReader in = new BufferedReader(new InputStreamReader(zipFile));
      while ((conTemp = in.readLine()) != null){
       fileContent = fileContent + conTemp + "\n\r";
      }
     }
    } 
   }
   //關閉檔案zip流
   zipFile.closeEntry();
   zipFile.close();
   //返回
   return fileContent;

  }catch(IOException e){
   System.out.println("讀取檔案內容失敗!!!");   
   e.printStackTrace();
   return null;
  }  
  
 }
 
 /**
  *示範方法
  */
 public static void main(String args[]){
  String filePath;
  String[] showFileArr;
  String[] realFileArr;
  String fileContent;
  int choose;
  //通過使用者獲得檔案路徑和檔案名稱
  try{
   BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
   System.out.println("Plase zip file path and name !!!");
   filePath = userInput.readLine();
   File file = new File(filePath);
   while (!(file.exists())) {
    System.out.println("Plase input right path again: "); 
    filePath = userInput.readLine();
    file = new File(filePath); 
   }
   //顯示檔案目錄,顯示選擇的檔案的內容
   //獲得真實檔案名稱和顯示檔案名稱數組
   ZipFileHandle zipFile = new ZipFileHandle(file);
   showFileArr = zipFile.getFileNameList("sh",file);
   realFileArr = zipFile.getFileNameList("gr",file);
   //列印顯示檔案名稱數組
   int i = 0;
   while (i < showFileArr.length){
    System.out.println(showFileArr[i]);
    i++;
   }
   //通過使用者輸入獲得需要顯示的檔案
   System.out.println("Plase choose file num!!!");
   choose = Integer.parseInt(userInput.readLine());
   if ((choose <0)||(choose >  showFileArr.length)){
    System.out.println("Plase choose file num retry!!!");
    choose = Integer.parseInt(userInput.readLine());
   }
   //獲得使用者選擇的檔案的內容
   fileContent = zipFile.loadFileCon(realFileArr[choose],file,"Byte");
   System.out.println(fileContent);
   
  }catch(Exception e){
   System.out.println("測試程式出錯!!!");
   e.printStackTrace();
  }  
 }  
}



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.