1

I'm working on a Java robot that copies the information from an excel file and pastes it on a program to create a username. I get everything I need from the excel file, except an ID number.

I'm trying to generate a unique numeric-only ID (So UUID won't work). It has to be 6 digits long, thus, its range is between 100,000 and 999,999. This is what I've got so far:

public void genID() {
    ArrayList<Integer> casillero = new ArrayList<Integer>();
    for (int i = 100000; i < 1000000; i++) {
        casillero.add(new Integer(i));
    } Collections.shuffle(casillero);
    for (int i = 0; i < 1; i++) {
        System.out.println("El nuevo ID de casillero es: I" + casillero.get(i));
    }
}

This generates a 6 digit number and that's great. But how do I make sure that this number hasn't and won't be generated next time I run my java program? Thank you!

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
David Morales
  • 33
  • 1
  • 6
  • Where do you store these numbers or the objects that hold these numbers? casillero, right? Check if it already exists first. – Hovercraft Full Of Eels Dec 17 '17 at 22:31
  • You need to _persist_ the data somewhere (text file, database etc.). – Mick Mnemonic Dec 17 '17 at 22:32
  • Currently I'm not storing the existing numbers anywhere. I will try that, thank you. – David Morales Dec 17 '17 at 22:51
  • It depends on your specific env. For example, you would concatenate a part of IP address and process ID and some part of current time. But in general case, only 6 decimal num positions may lead to very possible collision. So, yes, think about some shared and persist counter like RMDBS's sequence/auto-increment or something like that – AnatolyG Dec 17 '17 at 23:36
  • Thank you everyone for the suggestions! Those are really smart solutions, I will try to work them out. – David Morales Dec 18 '17 at 04:43

1 Answers1

0

It is impossible for the JVM to remember any values from its previous run-time (excluding static values compiled in the code itself). Because if this, you have to write your program to save important data at run-time, otherwise it will be lost when the last thread terminates. Java supports a multitude of InputStreams and OutputStreams which make way for an entire world of possibilities, including file reading and writing.

The basic method of writing a file is using a FileOutputStream, which writes raw bytes to a given file. There are some objects like the PrintStream which automatically get the bytes of the given string (or parsed string if an object is passed) and write them to the output stream.


You need to save your IDs to a file before your program terminates, and read the file every time the genID() method is invoked. Once you have read the file, you can use a simple a loop to check the generated ID list for any existing values. Consider this example:

public void genID() {
    ArrayList<Integer> casillero = new ArrayList<Integer>();
    for (int i = 100000; i < 1000000; i++) {
        casillero.add(new Integer(i));
    } Collections.shuffle(casillero);
    for (int i = 0; i < 1; i++) {
        System.out.println("El nuevo ID de casillero es: I" + casillero.get(i));
    }

    try {
        getUsedIDS().forEach(i -> {
            /*
             * Iterate through the existing IDs
             * and make sure that casillero does
             * not contain any of them.
             */
            if(casillero.contains(i)) casillero.remove(i);
        });
    } catch (IOException e) {
        e.printStackTrace();
    }
}
public List<Integer> getUsedIDS() throws IOException {
    //The file which you saved the IDs to.
    File file = new File("IDs.txt");
    //Return all the values in the file.
    return Files.readAllLines(file.toPath()).stream().mapToInt(s -> Integer.parseInt(s)).boxed().collect(Collectors.toList());
}
public void saveIDs(List<Integer> IDs) throws FileNotFoundException {
    /*
     * Create a PrintStream that writes into a 
     * FileOutputStream which in turn writes to your file.
     * Because 'true' was passed to the constructor, this
     * stream will append to the file.
     */
    PrintStream s = new PrintStream(new FileOutputStream(new File("IDs.txt"), true));
    //Print every element in the IDs list.
    IDs.forEach(s::println);
    /*
     * Read more about flush here:
     * https://stackoverflow.com/a/2340125/5645656
     */
    s.flush();
    /*
     * Close the stream to prevent a resource leak.
     */
    s.close();
}
Cardinal System
  • 2,749
  • 3
  • 21
  • 42