Java Random String randomString(final int length)

Here you can find the source of randomString(final int length)

Description

random String

License

Apache License

Declaration

public static String randomString(final int length) 

Method Source Code


//package com.java2s;
/*//w  ww.j  a  v  a2s.  co  m
 * Copyright 2002-2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.util.*;

public class Main {
    public static String randomString(final int length) {
        Random random = new Random();
        final char[] chars = new char[length];
        for (int i = 0, x = chars.length; i < x;) {
            do {
                final int cp = random.nextInt(0x10FFFF + 1);
                if (!Character.isDefined(cp)) {
                    continue;
                }
                final char[] chs = Character.toChars(cp);
                if (chs.length > x - i) {
                    continue;
                }
                for (final char ch : chs) {
                    chars[i++] = ch;
                }
                break;
            } while (true);
        }
        return new String(chars);
    }
}

Related

  1. randomlyRecaseCodePoints(Random random, String str)
  2. randomNumberString(int in)
  3. randomRealisticUnicodeString(Random r)
  4. randomString()
  5. randomString()
  6. randomString(int len)
  7. randomString(int length)
  8. randomString(int length)
  9. randomString(int length)