[Tutorial] Different types of files

Discussion in 'Resources' started by LCastr0, Mar 2, 2014.

Thread Status:
Not open for further replies.
  1. Offline

    LCastr0

    Hello!
    After a lot of search, I couldn't find anything related here on the forums, so I decided to search outside the forums, and found some nice things.
    Today, I'll be showing you how to move files between folders, create files at a specific folder, and also, how to download files from other servers or websites.

    Moving Files
    To move a file, you just need to create a "void", with the String "from" path, the String "to" path, and the String "filename".
    Code:java
    1. public void move(String from, String to, String filename) throws IOException{
    2.  
    3. InputStream inStream = null;
    4. OutputStream outStream = null;
    5.  
    6. String f = null;
    7. if(from.endsWith("/")){
    8. f = from.replaceAll("/", "\\");
    9. } else if(from.endsWith("\\")){
    10. f = from;
    11. } else {
    12. f = from.replaceAll("/", "\\")+"\\";
    13. } //Checks if the last char of the path is a \ or a /, to replace it with the File separator
    14. String ff = f+filename;
    15.  
    16. String t = null;
    17. if(to.endsWith("/")){
    18. t = to.replaceAll("/", "\\");
    19. } else if(to.endsWith("\\")){
    20. t = to;
    21. } else {
    22. t = to.replaceAll("/", "\\")+"\\";
    23. }
    24. String tf = t+filename;
    25.  
    26. File fromFile = new File(ff); //File from
    27. File toFile = new File(tf); //File to
    28.  
    29. inStream = new FileInputStream(fromFile);
    30. outStream = new FileOutputStream(toFile);
    31.  
    32. byte[] buffer = new byte[1024];
    33.  
    34. int lenght;
    35.  
    36. while((lenght = inStream.read(buffer)) > 0){
    37. outStream.write(buffer, 0, lenght); //Writes the file in bytes
    38. }
    39.  
    40. inStream.close();
    41. outStream.close();
    42.  
    43. }


    Creating Files
    This tutorial is very simple.

    Code:java
    1. public void create(String file){ //The string is the directory+file name (Example: "C:/Users/LCastr0/Server/One/plugins/mypluginname/config2.yml")
    2.  
    3. File f = new File(file); //Get the file
    4. if(!f.exists()){
    5. try {
    6. f.createNewFile(); //Creates the file
    7. } catch (IOException e) {
    8. e.printStackTrace();
    9. }
    10. }
    11.  
    12. }


    Download File From Server/Website
    Code:java
    1. public void download(String url, String to) throws IOException{
    2.  
    3. URL website = new URL(url); //Gets the URL
    4. ReadableByteChannel rbc = Channels.newChannel(website.openStream()); //Opens the channel
    5. @SuppressWarnings("resource")
    6. fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); //Transfers the file
    7.  
    8. }


    Final Class with move, create and download:

    Code:
    package me.LCastr0.Files;
     
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.URL;
    import java.nio.channels.Channels;
    import java.nio.channels.ReadableByteChannel;
    import java.util.logging.Logger;
     
    import org.bukkit.plugin.java.JavaPlugin;
     
     
    public class Load extends JavaPlugin{
     
        public void onEnable(){
       
            try {
                move("C:\\Users\\Lucas Queiroz\\Downloads\\ButterCraft\\0.0\\Test Server\\testing", "C:\\Users\\Lucas Queiroz\\Downloads\\ButterCraft\\0.0\\Test Server\\plugins\\Testing", "abc.txt");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            Logger.getLogger("Minecraft").info("Moved!");
            create("C:\\Users\\Lucas Queiroz\\Downloads\\ButterCraft\\0.0\\Test Server\\testing\\123.yml");
            Logger.getLogger("Minecraft").info("Created!");
            try {
                download("http://sbuttercraft.com/plugin-requests/index.html", "C:\\Users\\Lucas Queiroz\\Downloads\\ButterCraft\\0.0\\Test Server\\testing\\index.html");
                Logger.getLogger("Minecraft").info("Downloaded!");
            } catch (IOException e) {
                e.printStackTrace();
            }
       
        }
     
        public void move(String from, String to, String filename) throws IOException{
       
            InputStream inStream = null;
            OutputStream outStream = null;
       
            String f = null;
            if(from.endsWith("/")){
                f = from.replaceAll("/", "\\");
            } else if(from.endsWith("\\")){
                f = from;
            } else {
                f = from.replaceAll("/", "\\")+"\\";
            }
            String ff = f+filename;
       
            String t = null;
            if(to.endsWith("/")){
                t = to.replaceAll("/", "\\");
            } else if(to.endsWith("\\")){
                t = to;
            } else {
                t = to.replaceAll("/", "\\")+"\\";
            }
            String tf = t+filename;
       
            File fromFile = new File(ff);
            File toFile = new File(tf);
       
            inStream = new FileInputStream(fromFile);
            outStream = new FileOutputStream(toFile);
       
            byte[] buffer = new byte[1024];
       
            int lenght;
       
            while((lenght = inStream.read(buffer)) > 0){
                outStream.write(buffer, 0, lenght);
            }
       
            inStream.close();
            outStream.close();
       
        }
     
        public void create(String file){
       
            File f = new File(file);
            if(!f.exists()){
                try {
                    f.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
       
        }
     
        public void download(String url, String to) throws IOException{
       
            URL website = new URL(url);
            ReadableByteChannel rbc = Channels.newChannel(website.openStream());
            @SuppressWarnings("resource")
            FileOutputStream fos = new FileOutputStream(to);
            fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
       
        }
     
    }
    
    ------------------------------------------------------------------------
    xTrollxDudex 's methods:
    Code:
    package me.LCastr0.Files;
     
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.URL;
    import java.nio.channels.Channels;
    import java.nio.channels.FileChannel;
    import java.nio.channels.ReadableByteChannel;
    import java.util.logging.Logger;
     
    import net.minecraft.util.org.apache.commons.io.FileUtils;
     
    import org.bukkit.plugin.java.JavaPlugin;
     
    import com.google.common.io.Files;
     
     
    public class Load extends JavaPlugin{
     
        long start = 0;
        long end = 0;
     
        public void onEnable(){
         
            start = System.nanoTime();
            try {
                move("C:\\Users\\Lucas Queiroz\\Downloads\\ButterCraft\\0.0\\Test Server\\testing", "C:\\Users\\Lucas Queiroz\\Downloads\\ButterCraft\\0.0\\Test Server\\plugins\\Testing", "abc.txt");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            end = System.nanoTime();
            long total = end - start;
            Logger.getLogger("Minecraft").info("Moved in "+total+" seconds!");
            start = 0;
            end = 0;
            start = System.nanoTime();
            create("C:\\Users\\Lucas Queiroz\\Downloads\\ButterCraft\\0.0\\Test Server\\testing\\123.yml");
            end = System.nanoTime();
            long total1 = end - start;
            Logger.getLogger("Minecraft").info("Created in "+total1+" seconds!");
            start = 0;
            end = 0;
            try {
                start = System.nanoTime();
                download("http://sbuttercraft.com/plugin-requests/index.html", "C:\\Users\\Lucas Queiroz\\Downloads\\ButterCraft\\0.0\\Test Server\\testing\\index.html");
                end = System.nanoTime();
                long total2 = end - start;
                Logger.getLogger("Minecraft").info("Downloaded in"+total2+" seconds!");
            } catch (IOException e) {
                e.printStackTrace();
            }
         
            File sourceNio = new File("C:\\Users\\Lucas Queiroz\\Downloads\\ButterCraft\\0.0\\Test Server\\testing\\nio.yml");
            File destNio = new File("C:\\Users\\Lucas Queiroz\\Downloads\\ButterCraft\\0.0\\Test Server\\plugins\\Testing\\nio.yml");
            try {
                start = System.nanoTime();
                copyUsingNIO(sourceNio, destNio);
                end = System.nanoTime();
                long total3 = end - start;
                Logger.getLogger("Minecraft").info("Moved in "+total3+" seconds!");
            } catch (IOException e) {
                e.printStackTrace();
            }
         
            File sourceApache = new File("C:\\Users\\Lucas Queiroz\\Downloads\\ButterCraft\\0.0\\Test Server\\testing\\apache.yml");
            File destApache = new File("C:\\Users\\Lucas Queiroz\\Downloads\\ButterCraft\\0.0\\Test Server\\plugins\\Testing\\apache.yml");
            start = System.nanoTime();
            try {
                copyUsingApache(sourceApache, destApache);
            } catch (IOException e) {
                e.printStackTrace();
            }
            end = System.nanoTime();
            long total4 = end-start;
            Logger.getLogger("Minecraft").info("Moved in "+total4+" seconds!");
         
            File sourceFiles = new File("C:\\Users\\Lucas Queiroz\\Downloads\\ButterCraft\\0.0\\Test Server\\testing\\files.yml");
            File destFiles = new File("C:\\Users\\Lucas Queiroz\\Downloads\\ButterCraft\\0.0\\Test Server\\plugins\\Testing\\files.yml");
            start = System.nanoTime();
            try {
                copyUsingFiles(sourceFiles, destFiles);
            } catch (IOException e) {
                e.printStackTrace();
            }
            end = System.nanoTime();
            long total5 = end-start;
            Logger.getLogger("Minecraft").info("Moved in "+total5+" seconds!");
         
        }
     
        //Using FileStreams
        public void move(String from, String to, String filename) throws IOException{
         
            InputStream inStream = null;
            OutputStream outStream = null;
         
            String f = null;
            if(from.endsWith("/")){
                f = from.replaceAll("/", "\\");
            } else if(from.endsWith("\\")){
                f = from;
            } else {
                f = from.replaceAll("/", "\\")+"\\";
            }
            String ff = f+filename;
         
            String t = null;
            if(to.endsWith("/")){
                t = to.replaceAll("/", "\\");
            } else if(to.endsWith("\\")){
                t = to;
            } else {
                t = to.replaceAll("/", "\\")+"\\";
            }
            String tf = t+filename;
         
            File fromFile = new File(ff);
            File toFile = new File(tf);
         
            inStream = new FileInputStream(fromFile);
            outStream = new FileOutputStream(toFile);
         
            byte[] buffer = new byte[1024];
         
            int lenght;
         
            while((lenght = inStream.read(buffer)) > 0){
                outStream.write(buffer, 0, lenght);
            }
         
            inStream.close();
            outStream.close();
         
        }
     
        public void create(String file){
         
            File f = new File(file);
            if(!f.exists()){
                try {
                    f.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
         
        }
     
        public void download(String url, String to) throws IOException{
         
            URL website = new URL(url);
            ReadableByteChannel rbc = Channels.newChannel(website.openStream());
            @SuppressWarnings("resource")
            FileOutputStream fos = new FileOutputStream(to);
            fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
         
        }
     
        //Using NIO
        public void copyUsingNIO(File source, File dest) throws IOException{
         
            FileChannel inputChannel = null;
            FileChannel outputChannel = null;
            try{
                inputChannel = new FileInputStream(source).getChannel();
                outputChannel = new FileOutputStream(dest).getChannel();
                outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
            } finally{
                inputChannel.close();
                outputChannel.close();
            }
         
        }
     
        //Using Apache
        public void copyUsingApache(File source, File dest) throws IOException{
            FileUtils.copyFile(source, dest);
        }
     
        //Using Files (Java 7)
        public void copyUsingFiles(File source, File dest) throws IOException{
            Files.copy(source, dest);
        }
     
    }
    
    Time using my source: 567127
    Time using NIO: 852877
    Time using Apache: 2255093
    Time using Files (Java 7): 3416463
     
  2. Offline

    xTrollxDudex

    LCastr0
    You could've simplified that with NIO...
     
    CaptainBern likes this.
  3. Offline

    LCastr0

    It was made to be a simple tutorial, not a "complex" one. Also, sorry, I didn't know there were more than 1 way to do it. If you have other ways, please, post, and I'll tag you on the first post.
     
  4. Offline

    xTrollxDudex

    CaptainBern likes this.
  5. Offline

    LCastr0

    I'll make a compilation with all the methods, thanks :)

    Added the source with all the methods. Thanks for sharing!

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: Jun 7, 2016
  6. Offline

    xTrollxDudex

    Wrong Files class
     
  7. Offline

    RawCode

    does not belong to bukkit forum.

    it's ok to "explain" articles from oracle, but there is no reason for this.

    you shoud explain how to read and write files from plugin's jar.
    assemble valid plugin jars at runtime (from other plugin)
    execute plugins from memory image

    and similar features not explained directly by oracle and about bukkit.
     
  8. Offline

    LCastr0

    I tested it in my plugin, and then copied and pasted here...

    It DOES belong to bukkit, since I had to make a plugin that transfers files.
     
  9. Offline

    xTrollxDudex

  10. Offline

    RawCode

    LCastr0
    your code have nothing with bukkit or plugins, there is no real application that will require moving arbitrary files around.
    you can move plugin related files, backups or logs, such code will belong to bukkit, your current is just generic java snipped with zero practical value.

    and your benchmark is joke, all "normal" developers use nanotime + 100 000 (or more) invocations, not single one to eliminate bytecode compilation and firstrun delay issues.
     
  11. Offline

    LCastr0

    My code is there to make some lifes simpler. I used it in my plugin to move stats files. Later, I will do a tutorial (in this same thread), about moving config files.
     
Thread Status:
Not open for further replies.

Share This Page