Passing parameter using the " String[] args" declared in main

Asked

Viewed 1,618 times

2

I’ve been searching the Oracle documentation, examples of copies of files, with their attributes in various ways... Within this research I came across a strange thing that was the parameter passage that was being done, which was the variable "args" declared as string in main

Follow the code to show... I would like to know what is happening and why it was used.

import java.nio.file.*;
import static java.nio.file.StandardCopyOption.*;
import java.nio.file.attribute.*;
import static java.nio.file.FileVisitResult.*;
import java.io.IOException;
import java.util.*;

/**
 * Sample code that copies files in a similar manner to the cp(1) program.
 */

public class Copy {

/**
 * Returns {@code true} if okay to overwrite a  file ("cp -i")
 */
static boolean okayToOverwrite(Path file) {
    String answer = System.console().readLine("overwrite %s (yes/no)? ", file);
    return (answer.equalsIgnoreCase("y") || answer.equalsIgnoreCase("yes"));
}

/**
 * Copy source file to target location. If {@code prompt} is true then
 * prompt user to overwrite target if it exists. The {@code preserve}
 * parameter determines if file attributes should be copied/preserved.
 */
static void copyFile(Path source, Path target, boolean prompt, boolean preserve) {
    CopyOption[] options = (preserve) ?
        new CopyOption[] { COPY_ATTRIBUTES, REPLACE_EXISTING } :
        new CopyOption[] { REPLACE_EXISTING };
    if (!prompt || Files.notExists(target) || okayToOverwrite(target)) {
        try {
            Files.copy(source, target, options);
        } catch (IOException x) {
            System.err.format("Unable to copy: %s: %s%n", source, x);
        }
    }
}

/**
 * A {@code FileVisitor} that copies a file-tree ("cp -r")
 */
static class TreeCopier implements FileVisitor<Path> {
    private final Path source;
    private final Path target;
    private final boolean prompt;
    private final boolean preserve;

    TreeCopier(Path source, Path target, boolean prompt, boolean preserve) {
        this.source = source;
        this.target = target;
        this.prompt = prompt;
        this.preserve = preserve;
    }

    @Override
    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
        // before visiting entries in a directory we copy the directory
        // (okay if directory already exists).
        CopyOption[] options = (preserve) ?
            new CopyOption[] { COPY_ATTRIBUTES } : new CopyOption[0];

        Path newdir = target.resolve(source.relativize(dir));
        try {
            Files.copy(dir, newdir, options);
        } catch (FileAlreadyExistsException x) {
            // ignore
        } catch (IOException x) {
            System.err.format("Unable to create: %s: %s%n", newdir, x);
            return SKIP_SUBTREE;
        }
        return CONTINUE;
    }

    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
        copyFile(file, target.resolve(source.relativize(file)),
                 prompt, preserve);
        return CONTINUE;
    }

    @Override
    public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
        // fix up modification time of directory when done
        if (exc == null && preserve) {
            Path newdir = target.resolve(source.relativize(dir));
            try {
                FileTime time = Files.getLastModifiedTime(dir);
                Files.setLastModifiedTime(newdir, time);
            } catch (IOException x) {
                System.err.format("Unable to copy all attributes to: %s: %s%n", newdir, x);
            }
        }
        return CONTINUE;
    }

    @Override
    public FileVisitResult visitFileFailed(Path file, IOException exc) {
        if (exc instanceof FileSystemLoopException) {
            System.err.println("cycle detected: " + file);
        } else {
            System.err.format("Unable to copy: %s: %s%n", file, exc);
        }
        return CONTINUE;
    }
}

static void usage() {
    System.err.println("java Copy [-ip] source... target");
    System.err.println("java Copy -r [-ip] source-dir... target");
    System.exit(-1);
}

public static void main(String[] args) throws IOException {
    boolean recursive = false;
    boolean prompt = false;
    boolean preserve = false;

    // process options
    int argi = 0;
    while (argi < args.length) {
        String arg = args[argi];
        if (!arg.startsWith("-"))
            break;
        if (arg.length() < 2)
            usage();
        for (int i=1; i<arg.length(); i++) {
            char c = arg.charAt(i);
            switch (c) {
                case 'r' : recursive = true; break;
                case 'i' : prompt = true; break;
                case 'p' : preserve = true; break;
                default : usage();
            }
        }
        argi++;
    }

    // remaining arguments are the source files(s) and the target location
    int remaining = args.length - argi;
    if (remaining < 2)
        usage();
    Path[] source = new Path[remaining-1];
    int i=0;
    while (remaining > 1) {
        source[i++] = Paths.get(args[argi++]);
        remaining--;
    }
    Path target = Paths.get(args[argi]);

    // check if target is a directory
    boolean isDir = Files.isDirectory(target);

    // copy each source file/directory to target
    for (i=0; i<source.length; i++) {
        Path dest = (isDir) ? target.resolve(source[i].getFileName()) : target;

        if (recursive) {
            // follow links when copying files
            EnumSet<FileVisitOption> opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS);
            TreeCopier tc = new TreeCopier(source[i], dest, prompt, preserve);
            Files.walkFileTree(source[i], opts, Integer.MAX_VALUE, tc);
        } else {
            // not recursive so source must not be a directory
            if (Files.isDirectory(source[i])) {
                System.err.format("%s: is a directory%n", source[i]);
                continue;
            }
            copyFile(source[i], dest, prompt, preserve);
        }
    }
}
}

If you notice in the section below shows the passage, which I am talking about, as it is the first time I see it, I would like a help to understand.

 public static void main(String[] args) throws IOException {
    boolean recursive = false;
    boolean prompt = false;
    boolean preserve = false;

    // process options
    int argi = 0;
    while (argi < args.length) {
        String arg = args[argi];
        if (!arg.startsWith("-"))
            break;
        if (arg.length() < 2)
            usage();
        for (int i=1; i<arg.length(); i++) {
            char c = arg.charAt(i);
            switch (c) {
                case 'r' : recursive = true; break;
                case 'i' : prompt = true; break;
                case 'p' : preserve = true; break;
                default : usage();
            }
        }
        argi++;
    }

Thank you

2 answers

2


A detail, String[] is not String, this symbol [] means that this is an "array" of the string type. That is, it carries one or strings.

For example this code:

public class Exemplo {
    public static void main (String[] args) {
        for (String s: args) {
            System.out.println(s);
        }
    }
}

If you call him that:

java Example Foo Bar Ola Mundo

He will return it:

Foo

Bar

Hello

World

Because to each space he added an item in the "array", ie:

  • String a = "ola mundo"; is a String.
  • String a[] = {"ola", "mundo"}; is a string vector, ie in this example are two arrays in a vector.

Note that there are also arrays with other types, such as int[] which is an array (array) of integers.

See that in the java documentation has this excerpt:

When an application is launched, the Runtime system passes the command-line Arguments to the application’s main method via an array of Strings

When an application is executed, the runtime system passes the command line arguments to the method main using a array of Strings.

  • It is forgotten to mention that it is a vector of String not just a... But since it is an example of copying files and directories, it was here that came the question of comparing with the vector of Strings ?

  • So it’s a question... My point is. If this code would copy a certain directory, subdirectories and files what was passed as parameter is impossible to compile... I tried to run here and it always falls in the Static void Usage() { System.err.println("java Copy [-ip] source... target"); System.err.println("java Copy -r [-ip] -source dir... target"); System.Exit(-1); } But it doesn’t even take a directory to copy...

  • @Valdecir How did you pass the arguments? I see that your doubt is not about string or string[], please edit the question and explain in it what you just told me to make it clearer :) I will try to compile here.

  • @Valdecir How you ran java? java Exemplo -r ...?

  • OK... is that this example is from javadoc, will help me a lot to understand what happens in each method. I will edit here

0

Good people found the answer to that question... Actually this String vector declared in main when passed as parameter, the "value" has to be predetermined before the execution of the program, as if it were only one . jar and would be compiled by command line, so the parameters have to be displayed along with the execution. To be able to use in Netbeans I followed the steps below.

inserir a descrição da imagem aqui

After clicking on Customize...

inserir a descrição da imagem aqui

I passed the parameters necessary for my program to work.

NOTE: I increased the memory of the java so that it gets a little faster the copy of the files, and with that he copied 26.2GB in 15 minutes 30 seconds.

I hope I’ve helped

  • 3

    Sorry Valdecir, but you really were the only one who could find the answer, since this is not mentioned in the question, at any time in the question it would be possible to understand that the problem was with copying the files, I recommend you to read this link: http://answall.com/help/how-to-ask

  • I don’t believe you... The truth was that I needed help to make this code work, and I was not understanding why the "Path/Copy Origin" parameter was being passed... As you can notice the copy of files was already ready just needed to execute the code.

  • So friend, it was just what I said, you wrote the "question" in a way that only you could answer, not on purpose, but who tries to help you when reading your question is not understanding or understand something else.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.