Example usage for java.lang StringBuffer StringBuffer

List of usage examples for java.lang StringBuffer StringBuffer

Introduction

In this page you can find the example usage for java.lang StringBuffer StringBuffer.

Prototype

@HotSpotIntrinsicCandidate
public StringBuffer() 

Source Link

Document

Constructs a string buffer with no characters in it and an initial capacity of 16 characters.

Usage

From source file:ComputeInitials.java

public static void main(String[] args) {
    String myName = "Fred F. Flintstone";
    StringBuffer myInitials = new StringBuffer();
    int length = myName.length();

    for (int i = 0; i < length; i++) {
        if (Character.isUpperCase(myName.charAt(i))) {
            myInitials.append(myName.charAt(i));
        }/*ww  w  . j  a  va 2  s .  c o  m*/
    }
    System.out.println("My initials are: " + myInitials);
}

From source file:io.s4.util.AvroSchemaSupplementer.java

public static void main(String args[]) {
    if (args.length < 1) {
        System.err.println("No schema filename specified");
        System.exit(1);/*  w w w . j av a 2 s.  c  om*/
    }

    String filename = args[0];
    FileReader fr = null;
    BufferedReader br = null;
    InputStreamReader isr = null;
    try {
        if (filename == "-") {
            isr = new InputStreamReader(System.in);
            br = new BufferedReader(isr);
        } else {
            fr = new FileReader(filename);
            br = new BufferedReader(fr);
        }

        String inputLine = "";
        StringBuffer jsonBuffer = new StringBuffer();
        while ((inputLine = br.readLine()) != null) {
            jsonBuffer.append(inputLine);
        }

        JSONObject jsonRecord = new JSONObject(jsonBuffer.toString());

        JSONObject keyPathElementSchema = new JSONObject();
        keyPathElementSchema.put("name", "KeyPathElement");
        keyPathElementSchema.put("type", "record");

        JSONArray fieldsArray = new JSONArray();
        JSONObject fieldRecord = new JSONObject();
        fieldRecord.put("name", "index");
        JSONArray typeArray = new JSONArray("[\"int\", \"null\"]");
        fieldRecord.put("type", typeArray);
        fieldsArray.put(fieldRecord);
        fieldRecord = new JSONObject();
        fieldRecord.put("name", "keyName");
        typeArray = new JSONArray("[\"string\", \"null\"]");
        fieldRecord.put("type", typeArray);
        fieldsArray.put(fieldRecord);

        keyPathElementSchema.put("fields", fieldsArray);

        JSONObject keyInfoSchema = new JSONObject();
        keyInfoSchema.put("name", "KeyInfo");
        keyInfoSchema.put("type", "record");

        fieldsArray = new JSONArray();
        fieldRecord = new JSONObject();
        fieldRecord.put("name", "keyPath");
        typeArray = new JSONArray("[\"string\", \"null\"]");
        fieldRecord.put("type", typeArray);
        fieldsArray.put(fieldRecord);
        fieldRecord = new JSONObject();
        fieldRecord.put("name", "fullKeyPath");
        typeArray = new JSONArray("[\"string\", \"null\"]");
        fieldRecord.put("type", typeArray);
        fieldsArray.put(fieldRecord);
        fieldRecord = new JSONObject();
        fieldRecord.put("name", "keyPathElementList");
        JSONObject typeRecord = new JSONObject();
        typeRecord.put("type", "array");
        typeRecord.put("items", keyPathElementSchema);
        fieldRecord.put("type", typeRecord);
        fieldsArray.put(fieldRecord);

        keyInfoSchema.put("fields", fieldsArray);

        JSONObject partitionInfoSchema = new JSONObject();
        partitionInfoSchema.put("name", "PartitionInfo");
        partitionInfoSchema.put("type", "record");
        fieldsArray = new JSONArray();
        fieldRecord = new JSONObject();
        fieldRecord.put("name", "partitionId");
        typeArray = new JSONArray("[\"int\", \"null\"]");
        fieldRecord.put("type", typeArray);
        fieldsArray.put(fieldRecord);
        fieldRecord = new JSONObject();
        fieldRecord.put("name", "compoundKey");
        typeArray = new JSONArray("[\"string\", \"null\"]");
        fieldRecord.put("type", typeArray);
        fieldsArray.put(fieldRecord);
        fieldRecord = new JSONObject();
        fieldRecord.put("name", "compoundValue");
        typeArray = new JSONArray("[\"string\", \"null\"]");
        fieldRecord.put("type", typeArray);
        fieldsArray.put(fieldRecord);
        fieldRecord = new JSONObject();
        fieldRecord.put("name", "keyInfoList");
        typeRecord = new JSONObject();
        typeRecord.put("type", "array");
        typeRecord.put("items", keyInfoSchema);
        fieldRecord.put("type", typeRecord);
        fieldsArray.put(fieldRecord);

        partitionInfoSchema.put("fields", fieldsArray);

        fieldRecord = new JSONObject();
        fieldRecord.put("name", "S4__PartitionInfo");
        typeRecord = new JSONObject();
        typeRecord.put("type", "array");
        typeRecord.put("items", partitionInfoSchema);
        fieldRecord.put("type", typeRecord);

        fieldsArray = jsonRecord.getJSONArray("fields");
        fieldsArray.put(fieldRecord);

        System.out.println(jsonRecord.toString(3));
    } catch (Exception ioe) {
        throw new RuntimeException(ioe);
    } finally {
        if (br != null)
            try {
                br.close();
            } catch (Exception e) {
            }
        if (isr != null)
            try {
                isr.close();
            } catch (Exception e) {
            }
        if (fr != null)
            try {
                fr.close();
            } catch (Exception e) {
            }
    }
}

From source file:ThisHappens.java

public static void main(String[] args) {
    StringBuffer[] stringBuffers = new StringBuffer[10];

    for (int i = 0; i < stringBuffers.length; i++) {
        stringBuffers[i] = new StringBuffer();
        stringBuffers[i].append("StringBuffer at index " + i);
    }/*from w w w. j  a v a  2  s  .  c  o m*/
}

From source file:StyledTextBulletedList.java

public static void main(String[] args) {
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setText("StyledText Bullet Example");
    shell.setLayout(new FillLayout());
    final StyledText styledText = new StyledText(shell,
            SWT.FULL_SELECTION | SWT.BORDER | SWT.WRAP | SWT.V_SCROLL);
    StringBuffer text = new StringBuffer();
    text.append("Here is StyledText with some bulleted lists:\n\n");
    for (int i = 0; i < 4; i++)
        text.append("Red Bullet List Item " + i + "\n");
    text.append("\n");
    for (int i = 0; i < 2; i++)
        text.append("Numbered List Item " + i + "\n");
    for (int i = 0; i < 4; i++)
        text.append("Sub List Item " + i + "\n");
    for (int i = 0; i < 2; i++)
        text.append("Numbered List Item " + (2 + i) + "\n");
    text.append("\n");
    for (int i = 0; i < 4; i++)
        text.append("Custom Draw List Item " + i + "\n");
    styledText.setText(text.toString());

    StyleRange style0 = new StyleRange();
    style0.metrics = new GlyphMetrics(0, 0, 40);
    style0.foreground = display.getSystemColor(SWT.COLOR_RED);
    Bullet bullet0 = new Bullet(style0);
    StyleRange style1 = new StyleRange();
    style1.metrics = new GlyphMetrics(0, 0, 50);
    style1.foreground = display.getSystemColor(SWT.COLOR_BLUE);
    Bullet bullet1 = new Bullet(ST.BULLET_NUMBER | ST.BULLET_TEXT, style1);
    bullet1.text = ".";
    StyleRange style2 = new StyleRange();
    style2.metrics = new GlyphMetrics(0, 0, 80);
    style2.foreground = display.getSystemColor(SWT.COLOR_GREEN);
    Bullet bullet2 = new Bullet(ST.BULLET_TEXT, style2);
    bullet2.text = "\u2713";
    StyleRange style3 = new StyleRange();
    style3.metrics = new GlyphMetrics(0, 0, 50);
    Bullet bullet3 = new Bullet(ST.BULLET_CUSTOM, style2);

    styledText.setLineBullet(2, 4, bullet0);
    styledText.setLineBullet(7, 2, bullet1);
    styledText.setLineBullet(9, 4, bullet2);
    styledText.setLineBullet(13, 2, bullet1);
    styledText.setLineBullet(16, 4, bullet3);

    styledText.addPaintObjectListener(new PaintObjectListener() {
        public void paintObject(PaintObjectEvent event) {
            Display display = event.display;
            StyleRange style = event.style;
            Font font = style.font;
            if (font == null)
                font = styledText.getFont();
            TextLayout layout = new TextLayout(display);
            layout.setAscent(event.ascent);
            layout.setDescent(event.descent);
            layout.setFont(font);/*from  w w  w.  j  a v  a2 s.  c o m*/
            layout.setText("\u2023 1." + event.bulletIndex + ")");
            layout.draw(event.gc, event.x + 10, event.y);
            layout.dispose();
        }
    });
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:nz.co.jsrsolutions.ds3.DataScraper3.java

public static void main(String[] args) {

    logger.info("Starting application [ ds3 ] ...");

    ClassPathXmlApplicationContext context = null;

    try {//  w ww .ja  v  a2  s . c  om

        CommandLineParser parser = new GnuParser();

        CommandLine commandLine = parser.parse(CommandLineOptions.Options, args);

        if (commandLine.getOptions().length > 0 && !commandLine.hasOption(CommandLineOptions.HELP)) {

            StringBuffer environment = new StringBuffer();
            environment.append(SPRING_CONFIG_PREFIX);
            environment.append(commandLine.getOptionValue(CommandLineOptions.ENVIRONMENT));
            environment.append(SPRING_CONFIG_SUFFIX);

            context = new ClassPathXmlApplicationContext(environment.toString());
            context.registerShutdownHook();

            if (commandLine.hasOption(CommandLineOptions.SCHEDULED)) {

                Scheduler scheduler = context.getBean(SCHEDULER_BEAN_ID, Scheduler.class);
                scheduler.start();

                Object lock = new Object();
                synchronized (lock) {
                    lock.wait();
                }

            } else {
                DataScraper3Controller controller = context.getBean(CONTROLLER_BEAN_ID,
                        DataScraper3Controller.class);
                controller.executeCommandLine(commandLine);
            }

        } else {

            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("ds3", CommandLineOptions.Options);

        }

    } catch (DataScraper3Exception ds3e) {
        logger.error("Failed to execute command", ds3e);
    } catch (ParseException pe) {

        logger.error("Failed to parse command line", pe);

    } catch (Exception e) {

        logger.error("Failed to execute command", e);

    } finally {
        if (context != null) {
            context.close();
        }
    }

    logger.info("Exiting application [ ds3 ] ...");

}

From source file:ElementIteratorExample.java

public static void main(String args[]) throws Exception {

    if (args.length != 1) {
        System.err.println("Usage: java ElementIteratorExample input-URL");
    }//  ww w. j  av a 2 s.  co m

    // Load HTML file synchronously
    URL url = new URL(args[0]);
    URLConnection connection = url.openConnection();
    InputStream is = connection.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);

    HTMLEditorKit htmlKit = new HTMLEditorKit();
    HTMLDocument htmlDoc = (HTMLDocument) htmlKit.createDefaultDocument();
    HTMLEditorKit.Parser parser = new ParserDelegator();
    HTMLEditorKit.ParserCallback callback = htmlDoc.getReader(0);
    parser.parse(br, callback, true);

    // Parse
    ElementIterator iterator = new ElementIterator(htmlDoc);
    Element element;
    while ((element = iterator.next()) != null) {
        AttributeSet attributes = element.getAttributes();
        Object name = attributes.getAttribute(StyleConstants.NameAttribute);
        if ((name instanceof HTML.Tag)
                && ((name == HTML.Tag.H1) || (name == HTML.Tag.H2) || (name == HTML.Tag.H3))) {
            // Build up content text as it may be within multiple elements
            StringBuffer text = new StringBuffer();
            int count = element.getElementCount();
            for (int i = 0; i < count; i++) {
                Element child = element.getElement(i);
                AttributeSet childAttributes = child.getAttributes();
                if (childAttributes.getAttribute(StyleConstants.NameAttribute) == HTML.Tag.CONTENT) {
                    int startOffset = child.getStartOffset();
                    int endOffset = child.getEndOffset();
                    int length = endOffset - startOffset;
                    text.append(htmlDoc.getText(startOffset, length));
                }
            }
            System.out.println(name + ": " + text.toString());
        }
    }
    System.exit(0);
}

From source file:ZipDemo.java

public static void main(String[] args) throws Exception {
    for (int i = 0; i < args.length; ++i) {
        String uncompressed = "";
        File f = new File(args[i]);

        if (f.exists()) {
            BufferedReader br = new BufferedReader(new FileReader(f));

            String line = "";
            StringBuffer buffer = new StringBuffer();

            while ((line = br.readLine()) != null)
                buffer.append(line);//  w w w .ja  va 2  s  .  c o  m

            br.close();
            uncompressed = buffer.toString();
        } else {
            uncompressed = args[i];
        }

        byte[] compressed = ZipDemo.compress(uncompressed);

        String compressedAsString = new String(compressed);

        byte[] bytesFromCompressedAsString = compressedAsString.getBytes();

        bytesFromCompressedAsString.equals(compressed);
        System.out.println(ZipDemo.uncompress(compressed));
        System.out.println(ZipDemo.uncompress(compressedAsString));
    }
}

From source file:StringBufferCommaList.java

public static void main(String[] args) {
    StringTokenizer st = new StringTokenizer("Alpha Bravo Charlie");
    StringBuffer sb = new StringBuffer();
    while (st.hasMoreElements()) {
        sb.append(st.nextToken());/*from  www .j a  v a  2  s  .c  om*/
        if (st.hasMoreElements()) {
            sb.append(", ");
        }
    }
    System.out.println(sb);
}

From source file:net.java.sen.tools.MkCompoundTable.java

/**
 * Build compound word table./* w  w  w  .jav  a2 s  .  c  o m*/
 */
public static void main(String args[]) {
    ResourceBundle rb = ResourceBundle.getBundle("dictionary");
    int pos_start = Integer.parseInt(rb.getString("pos_start"));
    int pos_size = Integer.parseInt(rb.getString("pos_size"));

    try {
        log.info("reading compound word information ... ");
        HashMap compoundTable = new HashMap();

        log.info("load dic: " + rb.getString("compound_word_file"));
        BufferedReader dicStream = new BufferedReader(new InputStreamReader(
                new FileInputStream(rb.getString("compound_word_file")), rb.getString("dic.charset")));

        String t;
        int line = 0;

        StringBuffer pos_b = new StringBuffer();
        while ((t = dicStream.readLine()) != null) {
            CSVParser parser = new CSVParser(t);
            String csv[] = parser.nextTokens();
            if (csv.length < (pos_size + pos_start)) {
                throw new RuntimeException("format error:" + line);
            }

            pos_b.setLength(0);
            for (int i = pos_start; i < (pos_start + pos_size - 1); i++) {
                pos_b.append(csv[i]);
                pos_b.append(',');
            }

            pos_b.append(csv[pos_start + pos_size - 1]);
            pos_b.append(',');

            for (int i = pos_start + pos_size; i < (csv.length - 2); i++) {
                pos_b.append(csv[i]);
                pos_b.append(',');
            }
            pos_b.append(csv[csv.length - 2]);
            compoundTable.put(pos_b.toString(), csv[csv.length - 1]);
        }
        dicStream.close();
        log.info("done.");
        log.info("writing compound word table ... ");
        ObjectOutputStream os = new ObjectOutputStream(
                new FileOutputStream(rb.getString("compound_word_table")));
        os.writeObject(compoundTable);
        os.close();
        log.info("done.");
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:UnicodeChars.java

public static void main(String[] argv) {
    //+//from   w w  w  .  ja  v a 2  s.c o m
    StringBuffer b = new StringBuffer();
    for (char c = 'a'; c < 'd'; c++) {
        b.append(c);
    }
    b.append('\u00a5'); // Japanese Yen symbol
    b.append('\u01FC'); // Roman AE with acute accent
    b.append('\u0391'); // GREEK Capital Alpha
    b.append('\u03A9'); // GREEK Capital Omega

    for (int i = 0; i < b.length(); i++) {
        System.out.println("Character #" + i + " is " + b.charAt(i));
    }
    System.out.println("Accumulated characters are " + b);
    //-
}