Invalid File

Discussion in 'Plugin Development' started by The Gaming Grunts, Mar 2, 2014.

Thread Status:
Not open for further replies.
  1. Hey everyone! So I'm trying to get this backup system to work and it does, to some extent. It copies all the files and puts them into a zip folder, however if I click on the file, there's nothing in it (even though I know there is because it shows the file size next to it) and when I try to unzip it, windows gives me an error stating that the file is invalid. Any ideas why? Thanks :)

    Code:java
    1. public class Backup extends Thread{
    2.  
    3. private static Backup instance;
    4.  
    5. public static Backup getInstance(){
    6. return instance;
    7. }
    8.  
    9. public static void newRef(){
    10. instance = new Backup();
    11. }
    12.  
    13. public void backup() {
    14. new Thread() {
    15. public void run() {
    16. Backup.this.startBackup();
    17. }
    18. }.start();
    19. }
    20.  
    21. public void zipDir(String dir2zip, ZipOutputStream zos){
    22. try{
    23. File zipDir = new File(dir2zip);
    24. String[] dirList = zipDir.list();
    25.  
    26. byte[] readBuffer = new byte[2156];
    27. int bytesIn = 0;
    28.  
    29. for (String file : dirList) {
    30.  
    31. File f = new File(zipDir, file);
    32. if (f.isDirectory()) {
    33. String filePath = f.getPath();
    34. zipDir(filePath, zos);
    35. }else{
    36. ZipEntry anEntry = new ZipEntry(f.getPath());
    37. zos.putNextEntry(anEntry);
    38.  
    39. while ((bytesIn = fis.read(readBuffer)) != -1) {
    40. zos.write(readBuffer, 0, bytesIn);
    41. }
    42.  
    43. fis.close();
    44. }
    45.  
    46. }
    47. }catch(Exception e){
    48.  
    49. }}
    50.  
    51. public void startBackup(){
    52. try {
    53. File root = new File(".");
    54.  
    55. File bfolder = new File(root.getAbsolutePath() + "/backup/");
    56.  
    57. if (!bfolder.exists())
    58. bfolder.mkdir();
    59.  
    60. File backup = new File(bfolder.getAbsolutePath() + "/backup.zip");
    61.  
    62. if (!backup.exists())
    63. backup.createNewFile();
    64.  
    65. try{
    66. System.out.println(MessageManager.getConsolePrefix() + "Zipping files...");
    67. zipDir(root.getAbsolutePath(), zs);
    68. zs.close();
    69. System.out.println(MessageManager.getConsolePrefix() +"Done!");
    70. }catch (Exception e){}
    71.  
    72. }catch(Exception e){
    73. e.printStackTrace();
    74. }
    75.  
    76. DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
    77. java.util.Date dateTime = new java.util.Date();
    78. String date = dateFormat.format(dateTime);
    79.  
    80. List<World> worlds = Bukkit.getWorlds();
    81. Object[] theWorlds = worlds.toArray();
    82. String path = new File("").getAbsolutePath();
    83.  
    84. for(int i=0; i<theWorlds.length; i++){
    85. World w = (World) theWorlds[i];
    86. try {
    87. w.save();
    88. } catch (Exception e1) {}
    89.  
    90. String wNam = w.getName();
    91. File srcFolder = new File(path + File.separator + wNam);
    92. File destFolder = new File(Main.getInstance().getDataFolder().getAbsolutePath() + File.separator + "World Backups" + File.separator + date + File.separator + wNam);
    93. destFolder.mkdirs();
    94. if(srcFolder.exists()){
    95. try{
    96. Copier.copyFolder(srcFolder,destFolder);
    97. }catch(IOException e){}
    98. }
    99. }
    100. }
    101. }
    102. class Copier{
    103. public static void copyFolder(File src, File dest) throws IOException{
    104. if(src.isDirectory()){
    105. if(!dest.exists())
    106. dest.mkdir();
    107.  
    108. String files[] = src.list();
    109. for (String file : files) {
    110. File srcFile = new File(src, file);
    111. File destFile = new File(dest, file);
    112.  
    113. copyFolder(srcFile,destFile);
    114. }
    115. }else{
    116. OutputStream out = new FileOutputStream(dest);
    117. byte[] buffer = new byte[1024];
    118. int length;
    119.  
    120. while ((length = in.read(buffer)) > 0)
    121. out.write(buffer, 0, length);
    122. in.close();
    123. out.close();
    124. }
    125. }
    126. }[/i]
     
  2. I still can't figure it out. I even posted on stackoverflow, but their answers have left me even more confused :(
     
  3. Offline

    mazentheamazin

  4. Offline

    ZekeMo

    Download the Zip4j library from http://www.lingala.net/zip4j/download.php it's the first binary jar file. copy that into your eclipse project and add it to the build path. Then copy the code below and that should be enough to get you started. If anything is unclear or my code below doesn't work or something else goes wrong let me know.
    ps. if you want a description of what the methods in zip4j do when you hover over them download the source for Zip4j. It's the last link on the page. copy it somewhere in your eclipse project and then expand "Referenced Libraries" -> right click on the zip4j jar -> properites -> Java Source Attachment -> External File. and then navigate to the source zip.

    Code:java
    1. import java.io.File;
    2.  
    3. import net.lingala.zip4j.core.ZipFile;
    4. import net.lingala.zip4j.exception.ZipException;
    5. import net.lingala.zip4j.model.ZipParameters;
    6. import net.lingala.zip4j.util.Zip4jConstants;
    7.  
    8. public class Zip {
    9. public static void main(String[] args) {
    10. zip(new File("C:/games/Minecraft/MCWorld"));
    11. //unzip(new File("C:/games/Minecraft/MCWorld.zip"));
    12. }
    13.  
    14. public static void zip(File directoryContainingMCWorld) {
    15. try {
    16. String dest = null;
    17. if (directoryContainingMCWorld.isDirectory()) {
    18. dest = directoryContainingMCWorld.getAbsolutePath()+".zip";
    19. }
    20.  
    21. // Initiate ZipFile object with the path/name of the zip file.
    22. ZipFile zipFile = new ZipFile(dest);
    23.  
    24. // Initiate Zip Parameters which define various properties such
    25. // as compression method, etc.
    26. ZipParameters parameters = new ZipParameters();
    27.  
    28. // set compression method to store compression
    29. parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
    30.  
    31. // Set the compression level
    32. parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
    33.  
    34. // Add folder to the zip file
    35. zipFile.addFolder(directoryContainingMCWorld, parameters);
    36.  
    37.  
    38. } catch (Exception e) {
    39. e.printStackTrace();
    40. }
    41. }
    42.  
    43. public static void unzip(File zippedMCWorld) {
    44. unzip(zippedMCWorld, null);
    45. }
    46.  
    47. public static void unzip(File zippedMCWorld, String password) {
    48. try {
    49. ZipFile zipFile = new ZipFile(zippedMCWorld);
    50. if (!zipFile.isValidZipFile()) {
    51. System.err.println("invalid archive");
    52. }
    53. if (zipFile.isEncrypted()) {
    54. zipFile.setPassword(password);
    55. }
    56. String MCWorld = zippedMCWorld.getAbsolutePath();
    57. String name = zippedMCWorld.getName();
    58. String dest = MCWorld.substring(0, MCWorld.length()-name.length()-1);
    59. zipFile.extractAll(dest);
    60. } catch (ZipException e) {
    61. e.printStackTrace();
    62. }
    63. }
    64. }
     
  5. ZekeMo
    I'd rather not rely on a library
     
  6. Offline

    ZekeMo

    @The Gaming Grunts
    Ok I finally rewrote my entire zip class using ONLY the standard libraries. Here is the code.

    Code:
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.Enumeration;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipException;
    import java.util.zip.ZipFile;
    import java.util.zip.ZipOutputStream;
     
    public class Zip {
        public static void main(String[] args) throws Exception {
            String base =  "C:\\prog\\java\\testing\\Zip4j\\";
            //
            // - you don't have to use full paths and it doesn't matter if you use a / or a \
            //
            // zip(base+"mc", base+"backup\\");
            // - or
            // zip(base+"mc", base+"backup\\mc.zip");
            // - are the same thing
            //
            // zip(base+"mc");
            // - for simplicity this will create the zip in the same directory
            //
            //
            //
            // unzip(base+"backup/mc.zip", base);
            // - unzips to the specified directory
            //
            // unzip(base+"backup/mc.zip");
            // - unzips to the same directory
            //
            // - The destination folder must exist or an exception will be thrown
            //
            //
        }
     
        public static void zip(String MCWorld) {
            String src = new File(MCWorld).getAbsolutePath();
            String dest = src+".zip";
            zip(src, dest);
        }
     
        public static void zip(String MCWorld, String dest) {
            String base = getParent(new File(MCWorld).getAbsoluteFile());
            String zipName = null;
            if (dest.endsWith("\\") || dest.endsWith("/")) {
                String name = new File(MCWorld).getName()+".zip";
                zipName =  dest+name;
            } else {
                zipName = dest;
            }
            byte[] buffer = new byte[8192];
            try{
                ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipName));
                File[] binaryFile = list(MCWorld);
                for (int i=0; i<binaryFile.length; i++) {
                    if (binaryFile[i].isDirectory()) continue;
                    String fullPath = binaryFile[i].getAbsolutePath();
                    String relative = fullPath.substring(base.length(), fullPath.length());
                    ZipEntry ze = new ZipEntry(relative);
                    ze.setTime(binaryFile[i].lastModified());
                    zos.putNextEntry(ze);
                    FileInputStream in = new FileInputStream(fullPath);
     
                    int read = 0;
                    while ((read = in.read(buffer, 0, 8192)) > 0) {
                        zos.write(buffer, 0, read);
                    }
     
                    in.close();
                    zos.closeEntry();
                }
                zos.close();
            }catch(IOException ex){
                ex.printStackTrace();
            }
        }
     
        public static void unzip(String MCWorldzip) {
            String src = new File(MCWorldzip).getAbsolutePath();
            String dest = getParent(new File(MCWorldzip));
            unzip(src, dest);
        }
     
        public static void unzip(String MCWorldzip, String dest) {
            dest = new File(dest).getAbsolutePath()+"\\";
            try {
                ZipFile zipFile = new ZipFile(MCWorldzip);
                Enumeration<? extends ZipEntry> list = zipFile.entries();
     
                while (list.hasMoreElements()) {
                    ZipEntry tmp = list.nextElement();
                    BufferedReader br = new BufferedReader(new InputStreamReader(zipFile.getInputStream(tmp)));
                    String tree = getTree(dest+tmp.toString());
                    if (!new File(tree).exists())
                        new File(tree).mkdirs();
                    if (tmp.isDirectory()) continue;
     
                    File outputFile = new File(dest+tmp.toString());
                    BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
     
                    int read = 0;
                    char[] buffer = new char[8192];
                    while ((read = br.read(buffer, 0, 8192)) > 0) {
                        bw.write(buffer, 0, read);
                    }
                    br.close();
                    bw.close();
                    outputFile.setLastModified(tmp.getTime());
                }
            } catch (ZipException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
     
        public static String getTree(String dir) {
            if (dir.endsWith("/") || dir.endsWith("\\")) return dir;
            int end = dir.length();
            for (int i=dir.length()-1; i>=0; i--) {
                if (dir.charAt(i) == '\\' || dir.charAt(i) == '/') {
                    end = i+1;
                    break;
                }
            }
            return dir.substring(0, end);
        }
     
        public static String getParent(File dir) {
            String name = dir.getName();
            String fullPath = dir.getAbsolutePath();
            return fullPath.substring(0, fullPath.length()-name.length());
        }
     
     
        public static File[] list(String dir) {
            ArrayList<File> y = new ArrayList<File>();
            listr(new File(dir), y);
            Collections.sort(y, new fileDepth());
            File[] x = new File[y.size()];
            y.toArray(x);
            return x;
        }
     
        private static File[] listr(File file, ArrayList<File> y) {
            File[] children = file.listFiles();
            for (int i=0; i<children.length; i++) {
                if (children[i].isDirectory()) {
                    listr(children[i], y);
                }
                y.add(children[i]);
            }
            return null;
        }
     
        public static class fileDepth implements Comparator<File> {
            public int compare(File o1, File o2) {
                String tmp1 = o1.getAbsolutePath();
                String tmp2 = o2.getAbsolutePath();
                int fo1 = 0;
                int fo2 = 0;
                for (int i=0; i<tmp1.length(); i++) {
                    if (tmp1.charAt(i) == File.separatorChar) fo1++;
                }
                for (int i=0; i<tmp2.length(); i++) {
                    if (tmp2.charAt(i) == File.separatorChar) fo2++;
                }
                if (fo1 < fo2) {
                    return 1;
                } else if (fo2 < fo1) {
                    return -1;
                }
                return 0;
            }
        }
    }
     
Thread Status:
Not open for further replies.

Share This Page