Войти или зарегистрироваться

Помогите Как удалить папку с помощью java6 ?

Asd1995sse

Активный участник
Пользователь
Баллы
88
Вот нашел лаунчер. Нужно сделать так что-бы перед извлечением client.zip удалялась папка mods ну или все файлы из нее. Пожалуйста помогите.
 
Или напишите как удалить саму папку, а код я сам вставлю.
 
Или напишите как удалить саму папку, а код я сам вставлю.
ну..ну :trf:


Java:
    public void delete(File file) {
        if(!file.exists()) return;
       
        if(file.isDirectory()) {
            for(File f : file.listFiles())
                delete(f);
            file.delete();
        }else{
            file.delete();
        }
    }
 
В java нельзя указывать пути с процентами?
Например "%AppData%/.minecraft/mods/", но как тогда указать эту папку?
Код удаления
Код:
import java.io.File;
import java.io.IOException;
 
public class DeleteDirectoryExample
{
    private static final String SRC_FOLDER = ".*\\mods";
 
    public static void main(String[] args)
    {   
 
        File directory = new File(SRC_FOLDER);
 
        //make sure directory exists
        if(!directory.exists()){
 
          System.out.println("Directory does not exist.");
          System.exit(0);
 
        }else{
 
          try{
 
              delete(directory);
 
          }catch(IOException e){
              e.printStackTrace();
              System.exit(0);
          }
        }
 
        System.out.println("Done");
    }
 
    public static void delete(File file)
        throws IOException{
 
        if(file.isDirectory()){
 
            //directory is empty, then delete it
            if(file.list().length==0){
 
              file.delete();
              System.out.println("Directory is deleted : "
                                                + file.getAbsolutePath());
 
            }else{
 
              //list all the directory contents
              String files[] = file.list();
 
              for (String temp : files) {
                  //construct the file structure
                  File fileDelete = new File(file, temp);
 
                  //recursive delete
                delete(fileDelete);
              }
 
              //check the directory again, if empty then delete it
              if(file.list().length==0){
                    file.delete();
                System.out.println("Directory is deleted : "
                                                  + file.getAbsolutePath());
              }
            }
 
        }else{
            //if file, then delete it
            file.delete();
            System.out.println("File is deleted : " + file.getAbsolutePath());
        }
    }
}
 
Если нужно удалить папку модс то вызывайте метод при помощи этого кода
Java:
deleteDirectory(new File(getMcDir()+File.separator+"mods"));
 
вот код извлечения файлов из client.zip
Код:
protected void UnZip() throws PrivilegedActionException
  {
    String szZipFilePath;
    String szExtractPath;
    String path = (String)AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
        public Object run() throws Exception {
          return Util.getWorkingDirectory() + File.separator;
        }
      });
    int i;
 
    szZipFilePath = path + "bin" + File.separator + "client.zip";
   
    File f = new File(szZipFilePath);
    if(!f.exists())
    {
      System.out.println(
    "\nNot found: " + szZipFilePath);
      //System.exit(0);
    }
   
    if(f.isDirectory())
    {
      System.out.println(
    "\nNot file: " + szZipFilePath);
      //System.exit(0);
    }
 
    System.out.println(
      "Enter path to extract files: ");
    szExtractPath = path;
 
    File f1 = new File(szExtractPath);
    if(!f1.exists())
    {
      System.out.println(
    "\nNot found: " + szExtractPath);
      //System.exit(0);
    }
   
    if(!f1.isDirectory())
    {
      System.out.println(
    "\nNot directory: " + szExtractPath);
      //System.exit(0);
    }
 
    ZipFile zf;
    Vector zipEntries = new Vector();
   
    try
    {
      zf = new ZipFile(szZipFilePath); 
      Enumeration en = zf.entries();
   
      while(en.hasMoreElements())
      {
        zipEntries.addElement(
      (ZipEntry)en.nextElement());
      }
   
      for (i = 0; i < zipEntries.size(); i++)
      {
        ZipEntry ze =
      (ZipEntry)zipEntries.elementAt(i);
   
        extractFromZip(szZipFilePath, szExtractPath,
      ze.getName(), zf, ze);
      }
   
      zf.close();
      f.delete();
      System.out.println("Done!");
    }
    catch(Exception ex)
    {
      System.out.println(ex.toString());
    }
  }
 
  // ============================================
  // extractFromZip
  // ============================================
  static void extractFromZip(
    String szZipFilePath, String szExtractPath,
    String szName,
    ZipFile zf, ZipEntry ze)
  {
    if(ze.isDirectory())
      return;
   
    String szDstName = slash2sep(szName);
 
    String szEntryDir;
 
    if(szDstName.lastIndexOf(File.separator) != -1)
    {
      szEntryDir =
        szDstName.substring(
      0, szDstName.lastIndexOf(File.separator));
    }
    else   
      szEntryDir = "";
 
    System.out.print(szDstName);
    long nSize = ze.getSize();
    long nCompressedSize =
      ze.getCompressedSize();
 
    System.out.println(" " + nSize + " (" +
      nCompressedSize + ")");
 
    try
    {
      File newDir = new File(szExtractPath +
    File.separator + szEntryDir);
 
      newDir.mkdirs(); 
   
      FileOutputStream fos =
    new FileOutputStream(szExtractPath +
    File.separator + szDstName);
 
      InputStream is = zf.getInputStream(ze);
      byte[] buf = new byte[1024];
 
      int nLength;
   
      while(true)
      {
        try
        {
      nLength = is.read(buf);
        } 
        catch (EOFException ex)
        {
      break;
    }
 
        if(nLength < 0)
      break;
        fos.write(buf, 0, nLength);
      }
   
      is.close();
      fos.close();
    }
    catch(Exception ex)
    {
      System.out.println(ex.toString());
      //System.exit(0);
    }
  }
 
  // ============================================
  // slash2sep
  // ============================================
  static String slash2sep(String src)
  {
    int i;
    char[] chDst = new char[src.length()];
    String dst;
 
    for(i = 0; i < src.length(); i++)
    {
      if(src.charAt(i) == '/')
        chDst[i] = File.separatorChar;
      else
        chDst[i] = src.charAt(i);
    }
    dst = new String(chDst);
    return dst;
  }
 
 
}
я так понимаю код удаления надо прописывать после строчки с int i;, но потом программа просит создать 2 метода (deleteDirectory(File)) и (getMcDir()) и что делать? Я пока не очень яву изучил.
 
Мой код удаляет папку mods, используйте его, когда всё уже будет сделано
 
А на создание методов забить? когда что будет сделано?
 
Лаунчер уже настроен и готов к компиляции, осталось только это доделать.
Код:
private String getMcDir() {
    // TODO Auto-generated method stub
    return null;
}
 
private void deleteDirectory(File file) {
    // TODO Auto-generated method stub
   
}
так?
 
Если нужно удалить папку модс то вызывайте метод при помощи этого кода
Java:
deleteDirectory(new File(getMcDir()+File.separator+"mods"));
ну..ну :trf:


Java:
    public void delete(File file) {
        if(!file.exists()) return;
     
        if(file.isDirectory()) {
            for(File f : file.listFiles())
                delete(f);
            file.delete();
        }else{
            file.delete();
        }
    }
 
Вот что получилось:
Код:
protected void UnZip() throws PrivilegedActionException
  {
    String szZipFilePath;
    String szExtractPath;
    String path = (String)AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
        public Object run() throws Exception {
          return Util.getWorkingDirectory() + File.separator;
        }
      });
    int i;
    deleteDirectory(new File(getMcDir()+File.separator+"mods"));
    szZipFilePath = path + "bin" + File.separator + "client.zip";
   
    File f = new File(szZipFilePath);
    if(!f.exists())
    {
      System.out.println(
    "\nNot found: " + szZipFilePath);
      //System.exit(0);
    }
   
    if(f.isDirectory())
    {
      System.out.println(
    "\nNot file: " + szZipFilePath);
      //System.exit(0);
    }
 
    System.out.println(
      "Enter path to extract files: ");
    szExtractPath = path;
 
    File f1 = new File(szExtractPath);
    if(!f1.exists())
    {
      System.out.println(
    "\nNot found: " + szExtractPath);
      //System.exit(0);
    }
   
    if(!f1.isDirectory())
    {
      System.out.println(
    "\nNot directory: " + szExtractPath);
      //System.exit(0);
    }
 
    ZipFile zf;
    Vector zipEntries = new Vector();
   
    try
    {
      zf = new ZipFile(szZipFilePath); 
      Enumeration en = zf.entries();
   
      while(en.hasMoreElements())
      {
        zipEntries.addElement(
      (ZipEntry)en.nextElement());
      }
   
      for (i = 0; i < zipEntries.size(); i++)
      {
        ZipEntry ze =
      (ZipEntry)zipEntries.elementAt(i);
   
        extractFromZip(szZipFilePath, szExtractPath,
      ze.getName(), zf, ze);
      }
   
      zf.close();
      f.delete();
      System.out.println("Done!");
    }
    catch(Exception ex)
    {
      System.out.println(ex.toString());
    }
  }
 
  private String getMcDir() {
 
    return null;
}
 
private void deleteDirectory(File file) {
    public void delete(File file) {
 
        if(!file.exists()) return;
 
 
 
        if(file.isDirectory()) {
 
            for(File f : file.listFiles())
 
                delete(f);
 
            file.delete();
 
        }else{
 
            file.delete();
 
        }
 
    }
}
Но я так и не знаю что писать в private String getMcDir().
И эклипс пишет ошибки на 97 и 87 строчках.
 
Назад
Верх