Pregunta

I am trying to create a directory in my current working directory with the title of a url. However, I am converting that url to a hash and then to a hexadecimal so the name of the directory I am trying to create is something like 273212b1. However whenever I execute the code it throws an IOException and cannot make the directory. I am not sure what I am doing wrong.

Even if I do something like File directory = new File ("Users/whatever/Documents" + dirname); it doesn't work.

¿Fue útil?

Solución

You aren't creating a directory using the hash or hex, you are trying to create a directory using the URL. Here's the relevant steps:

The method is called with s = some URL:

public static File mkdir(String s) throws IOException

You copy the URL into a variable called dirname:

String dirname = s;

You set s to be a hex of a hash (which does not change the value of dirname):

s = Integer.toHexString(dirname.hashCode());

You create a File object representing a directory that has a URL for a name:

File directory = new File(dirname);

When you try to create that directory, it isn't going to work because of all the characters in a URL that aren't valid for directory names.

You should be doing this:

File directory = new File(s);

Once you solve that problem, you are then going to want to handle the double creation of the directory as follows:

if (directory.exists()) {
    System.out.println("Directory already exists!");
} else {
    success = directory.mkdir();
    if (success) {
        System.out.println("Successful");
    } else {
        throw new IOException("can't make directory for " + s);
    }
}

Otros consejos

success = directory.mkdir();

and

if  (!directory.mkdir())

You're creating the directory twice, or trying to. The second time, it will fail, and throw the exception.

Check your logic. It is redundant. You could reduce most of it to

if (!directory.exists() && !directory.mkdir())
{
    throw new IOException(...);
}

You don't need all that output.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top