Generate a string with given length containing random upper case characters ([A-Z]). - Java java.lang

Java examples for java.lang:String Random

Description

Generate a string with given length containing random upper case characters ([A-Z]).

Demo Code

//package com.java2s;

import java.io.ByteArrayInputStream;

import java.io.InputStream;

import java.io.UnsupportedEncodingException;

import java.util.Random;

public class Main {
    public static void main(String[] argv) {
        int len = 42;
        System.out.println(generateDataStream(len));
    }/* w ww  . ja  v  a2 s.  c om*/

    public static final String DEFAULT_ENCODING = "UTF-8";

    /**
     * Generate a string with given length containing random upper case characters ([A-Z]).
     * 
     * @param len length of to generated string
     * @return random upper case characters ([A-Z]).
     */
    public static InputStream generateDataStream(final int len) {
        return encapsulate(generateData(len));
    }

    /**
     * Encapsulate given content in an {@link InputStream} with charset <code>UTF-8</code>.
     *
     * @param content to encapsulate content
     * @return content as stream
     */
    public static InputStream encapsulate(final String content) {
        try {
            return encapsulate(content, DEFAULT_ENCODING);
        } catch (UnsupportedEncodingException e) {
            // we know that UTF-8 is supported
            throw new RuntimeException("UTF-8 MUST be supported.", e);
        }
    }

    /**
     * Encapsulate given content in an {@link InputStream} with given charset.
     * 
     * @param content to encapsulate content
     * @param charset to be used charset
     * @return content as stream
     * @throws UnsupportedEncodingException if charset is not supported
     */
    public static InputStream encapsulate(final String content,
            final String charset) throws UnsupportedEncodingException {
        return new ByteArrayInputStream(content.getBytes(charset));
    }

    /**
     * Generates a string with given length containing random upper case characters ([A-Z]).
     * @param len length of the generated string
     * @return random upper case characters ([A-Z])
     */
    public static String generateData(final int len) {
        Random random = new Random();
        StringBuilder b = new StringBuilder(len);
        for (int j = 0; j < len; j++) {
            final char c = (char) ('A' + random.nextInt('Z' - 'A' + 1));
            b.append(c);
        }
        return b.toString();
    }
}

Related Tutorials