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:ASCII2NATIVE.java

public static void main(String[] args) {
    File f = new File("c:\\mydb.script");
    File f2 = new File("c:\\mydb3.script");
    if (f.exists() && f.isFile()) {
        // convert param-file
        BufferedReader br = null;
        StringBuffer sb = new StringBuffer();
        String line;/*w w  w . j a v  a  2s.c  o m*/

        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(f), "JISAutoDetect"));

            while ((line = br.readLine()) != null) {
                System.out.println(ascii2Native(line));
                sb.append(ascii2Native(line)).append(";\n");//.append(";\n\r")
            }

            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f2), "utf-8"));
            out.append(sb.toString());
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            System.err.println("file not found - " + f);
        } catch (IOException e) {
            System.err.println("read error - " + f);
        } finally {
            try {
                if (br != null)
                    br.close();
            } catch (Exception e) {
            }
        }
    } else {
        // // convert param-data
        // System.out.print(ascii2native(args[i]));
        // if (i + 1 < args.length)
        // System.out.print(' ');
    }
}

From source file:com.bright.utils.rmDuplicateLines.java

public static void main(String args) {
    File monfile = new File(args);

    Set<String> userIdSet = new LinkedHashSet<String>();

    if (monfile.isFile() && monfile.getName().endsWith(".txt")) {
        try {// w  ww  .  j  av  a  2s.  c o  m
            List<String> content = FileUtils.readLines(monfile, Charset.forName("UTF-8"));
            userIdSet.addAll(content);

            Iterator<String> itr = userIdSet.iterator();
            StringBuffer output = new StringBuffer();
            while (itr.hasNext()) {

                output.append(itr.next() + System.getProperty("line.separator"));

            }

            BufferedWriter out = new BufferedWriter(new FileWriter(monfile));
            String outText = output.toString();

            out.write(outText);

            out.close();
        } catch (IOException e) {
            e.printStackTrace();

        }
    }

}

From source file:TerminalMonitor.java

static public void main(String args[]) {
    DriverPropertyInfo[] required;
    StringBuffer buffer = new StringBuffer();
    Properties props = new Properties();
    boolean connected = false;
    Driver driver;//w w  w  . j  a va  2s. c o  m
    String url;
    int line = 1; // Mark current input line

    if (args.length < 1) {
        System.out.println("Syntax: <java -Djdbc.drivers=DRIVER_NAME " + "TerminalMonitor JDBC_URL>");
        return;
    }
    url = args[0];
    // We have to get a reference to the driver so we can
    // find out what values to prompt the user for in order
    // to make a connection.
    try {
        driver = DriverManager.getDriver(url);
    } catch (SQLException e) {
        e.printStackTrace();
        System.err.println("Unable to find a driver for the specified " + "URL.");
        System.err.println("Make sure you passed the jdbc.drivers " + "property on the command line to specify "
                + "the driver to be used.");
        return;
    }
    try {
        required = driver.getPropertyInfo(url, props);
    } catch (SQLException e) {
        e.printStackTrace();
        System.err.println("Unable to get driver property information.");
        return;
    }
    input = new BufferedReader(new InputStreamReader(System.in));
    // some drivers do not implement this properly
    // if that is the case, prompt for user name and password
    try {
        if (required.length < 1) {
            props.put("user", prompt("user: "));
            props.put("password", prompt("password: "));
        } else {
            // for each required attribute in the driver property info
            // prompt the user for the value
            for (int i = 0; i < required.length; i++) {
                if (!required[i].required) {
                    continue;
                }
                props.put(required[i].name, prompt(required[i].name + ": "));
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        System.err.println("Unable to read property info.");
        return;
    }
    // Make the connection.
    try {
        connection = DriverManager.getConnection(url, props);
    } catch (SQLException e) {
        e.printStackTrace();
        System.err.println("Unable to connect to the database.");
    }
    connected = true;
    System.out.println("Connected to " + url);
    // Enter into a user input loop
    while (connected) {
        String tmp, cmd;

        // Print a prompt
        if (line == 1) {
            System.out.print("TM > ");
        } else {
            System.out.print(line + " -> ");
        }
        System.out.flush();
        // Get the next line of input
        try {
            tmp = input.readLine();
        } catch (java.io.IOException e) {
            e.printStackTrace();
            return;
        }
        // Get rid of extra space in the command
        cmd = tmp.trim();
        // The user wants to commit pending transactions
        if (cmd.equals("commit")) {
            try {
                connection.commit();
                System.out.println("Commit successful.");
            } catch (SQLException e) {
                System.out.println("Error in commit: " + e.getMessage());
            }
            buffer = new StringBuffer();
            line = 1;
        }
        // The user wants to execute the current buffer
        else if (cmd.equals("go")) {
            if (!buffer.equals("")) {
                try {
                    executeStatement(buffer);
                } catch (SQLException e) {
                    System.out.println(e.getMessage());
                }
            }
            buffer = new StringBuffer();
            line = 1;
            continue;
        }
        // The user wants to quit
        else if (cmd.equals("quit")) {
            connected = false;
            continue;
        }
        // The user wants to clear the current buffer
        else if (cmd.equals("reset")) {
            buffer = new StringBuffer();
            line = 1;
            continue;
        }
        // The user wants to abort a pending transaction
        else if (cmd.equals("rollback")) {
            try {
                connection.rollback();
                System.out.println("Rollback successful.");
            } catch (SQLException e) {
                System.out.println("An error occurred during rollback: " + e.getMessage());
            }
            buffer = new StringBuffer();
            line = 1;
        }
        // The user wants version info
        else if (cmd.startsWith("show")) {
            DatabaseMetaData meta;

            try {
                meta = connection.getMetaData();
                cmd = cmd.substring(5, cmd.length()).trim();
                if (cmd.equals("version")) {
                    showVersion(meta);
                } else {
                    System.out.println("show version"); // Bad arg
                }
            } catch (SQLException e) {
                System.out.println("Failed to load meta data: " + e.getMessage());
            }
            buffer = new StringBuffer();
            line = 1;
        }
        // The input that is not a keyword should appended be to the buffer
        else {
            buffer.append(" " + tmp);
            line++;
            continue;
        }
    }
    try {
        connection.close();
    } catch (SQLException e) {
        System.out.println("Error closing connection: " + e.getMessage());
    }
    System.out.println("Connection closed.");
}

From source file:comparetopics.CompareTopics.java

/**
 * @param args the command line arguments
 *///from w ww . j av a 2  s. c  om
public static void main(String[] args) {
    try {
        File file1 = new File(
                "/Users/apple/Desktop/graduation-project/topic-modeling/output/jhotdraw-extracted-code/keys.txt");
        File file2 = new File(
                "/Users/apple/Desktop/graduation-project/topic-modeling/output/jhotdraw-extracted-code/keys.txt");

        CompareTopics compareTopics = new CompareTopics();
        String[] words1 = compareTopics.getWords(file1);
        String[] words2 = compareTopics.getWords(file2);
        StringBuffer words = new StringBuffer();

        File outputFile = new File("/Users/apple/Desktop/test.txt");
        if (outputFile.createNewFile()) {
            System.out.println("Create successful: " + outputFile.getName());
        }
        boolean hasSame = false;

        for (String w1 : words1) {
            if (!NumberUtils.isNumber(w1)) {
                for (String w2 : words2) {
                    if (w1.equals(w2)) {
                        words.append(w1);
                        //                            words.append("\r\n");
                        words.append(" ");
                        hasSame = true;
                        break;
                    }
                }
            }
        }
        if (!hasSame) {
            System.out.println("No same word.");
        } else {
            compareTopics.printToFile(words.toString(), outputFile);
        }

    } catch (IOException ex) {
        Logger.getLogger(CompareTopics.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:TheReplacements.java

public static void main(String[] args) throws Exception {
    String s = TextFile.read("TheReplacements.java");
    // Match the specially-commented block of text above:
    Matcher mInput = Pattern.compile("/\\*!(.*)!\\*/", Pattern.DOTALL).matcher(s);
    if (mInput.find())
        s = mInput.group(1); // Captured by parentheses
    // Replace two or more spaces with a single space:
    s = s.replaceAll(" {2,}", " ");
    // Replace one or more spaces at the beginning of each
    // line with no spaces. Must enable MULTILINE mode:
    s = s.replaceAll("(?m)^ +", "");
    System.out.println(s);/* ww w .j  a  v  a2s.c  om*/
    s = s.replaceFirst("[aeiou]", "(VOWEL1)");
    StringBuffer sbuf = new StringBuffer();
    Pattern p = Pattern.compile("[aeiou]");
    Matcher m = p.matcher(s);
    // Process the find information as you
    // perform the replacements:
    while (m.find())
        m.appendReplacement(sbuf, m.group().toUpperCase());
    // Put in the remainder of the text:
    m.appendTail(sbuf);
    System.out.println(sbuf);

}

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    URL url = new URL("http://www.java2s.com");
    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);/*  ww w. j a  v a 2 s.  co m*/

    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)) {
            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());
        }
    }
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    Document document = new Document(PageSize.A6);
    PdfWriter.getInstance(document, new FileOutputStream("2.pdf"));
    document.open();/* ww w . j a  v a2  s  .  c o  m*/
    document.add(new Paragraph("Hello World"));
    document.add(new Paragraph("Hello People"));
    document.close();

    PdfReader reader = new PdfReader("2.pdf");
    PdfDictionary page = reader.getPageN(1);
    PRIndirectReference objectReference = (PRIndirectReference) page.get(PdfName.CONTENTS);
    PRStream stream = (PRStream) PdfReader.getPdfObject(objectReference);
    byte[] streamBytes = PdfReader.getStreamBytes(stream);
    String contentStream = new String(streamBytes);
    System.out.println(contentStream);
    PRTokeniser tokenizer = new PRTokeniser(streamBytes);
    while (tokenizer.nextToken()) {
        if (tokenizer.getTokenType() == PRTokeniser.TK_STRING) {
            System.out.println(tokenizer.getStringValue());
        }
    }
    StringBuffer buf = new StringBuffer();
    int pos = contentStream.indexOf("Hello World") + 11;
    buf.append(contentStream.substring(0, pos));
    buf.append("Hello");
    buf.append(contentStream.substring(pos));
    String hackedContentStream = buf.toString();
    document = new Document(PageSize.A6);
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("HelloWorldStreamHacked.pdf"));
    document.open();
    PdfContentByte cb = writer.getDirectContent();
    cb.setLiteral(hackedContentStream);
    document.close();
}

From source file:MainClass.java

public static void main(String[] a) {

    final Display display = new Display();
    final Shell shell = new Shell(display);

    shell.setSize(250, 200);/*from  www  .j  a va  2  s .co m*/

    shell.setLayout(new FillLayout());

    Table table = new Table(shell, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);

    Transfer[] types = new Transfer[] { TextTransfer.getInstance() };

    DragSource source = new DragSource(table, DND.DROP_MOVE | DND.DROP_COPY);
    source.setTransfer(types);
    source.addDragListener(new DragSourceAdapter() {
        public void dragSetData(DragSourceEvent event) {
            DragSource ds = (DragSource) event.widget;
            Table table = (Table) ds.getControl();
            TableItem[] selection = table.getSelection();

            StringBuffer buff = new StringBuffer();
            for (int i = 0, n = selection.length; i < n; i++) {
                buff.append(selection[i].getText());
            }
            event.data = buff.toString();
        }
    });

    DropTarget target = new DropTarget(table, DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_DEFAULT);
    target.setTransfer(types);
    target.addDropListener(new DropTargetAdapter() {
        public void dragEnter(DropTargetEvent event) {
            if (event.detail == DND.DROP_DEFAULT) {
                event.detail = (event.operations & DND.DROP_COPY) != 0 ? DND.DROP_COPY : DND.DROP_NONE;
            }
            for (int i = 0, n = event.dataTypes.length; i < n; i++) {
                if (TextTransfer.getInstance().isSupportedType(event.dataTypes[i])) {
                    event.currentDataType = event.dataTypes[i];
                }
            }
        }

        public void dragOver(DropTargetEvent event) {
            event.feedback = DND.FEEDBACK_SELECT | DND.FEEDBACK_SCROLL;
        }

        public void drop(DropTargetEvent event) {
            if (TextTransfer.getInstance().isSupportedType(event.currentDataType)) {
                DropTarget target = (DropTarget) event.widget;
                Table table = (Table) target.getControl();
                String data = (String) event.data;

                TableItem item = new TableItem(table, SWT.NONE);
                item.setText(new String[] { data });
                table.redraw();
            }
        }
    });

    TableColumn column = new TableColumn(table, SWT.NONE);

    TableItem item = new TableItem(table, SWT.NONE);
    item.setText(new String[] { "A" });
    item = new TableItem(table, SWT.NONE);
    item.setText(new String[] { "B" });
    item = new TableItem(table, SWT.BORDER);
    item.setText(new String[] { "C" });

    column.pack();

    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:DragDropTable.java

public static void main(String[] args) {
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setLayout(new FillLayout());

    Table table = new Table(shell, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);

    Transfer[] types = new Transfer[] { TextTransfer.getInstance() };
    DragSource source = new DragSource(table, DND.DROP_MOVE | DND.DROP_COPY);
    source.setTransfer(types);//  w  w  w .j a  va 2 s. c o  m

    source.addDragListener(new DragSourceAdapter() {
        public void dragSetData(DragSourceEvent event) {
            // Get the selected items in the drag source
            DragSource ds = (DragSource) event.widget;
            Table table = (Table) ds.getControl();
            TableItem[] selection = table.getSelection();

            StringBuffer buff = new StringBuffer();
            for (int i = 0, n = selection.length; i < n; i++) {
                buff.append(selection[i].getText());
            }

            event.data = buff.toString();
        }
    });

    // Create the drop target
    DropTarget target = new DropTarget(table, DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_DEFAULT);
    target.setTransfer(types);
    target.addDropListener(new DropTargetAdapter() {
        public void dragEnter(DropTargetEvent event) {
            if (event.detail == DND.DROP_DEFAULT) {
                event.detail = (event.operations & DND.DROP_COPY) != 0 ? DND.DROP_COPY : DND.DROP_NONE;
            }

            // Allow dropping text only
            for (int i = 0, n = event.dataTypes.length; i < n; i++) {
                if (TextTransfer.getInstance().isSupportedType(event.dataTypes[i])) {
                    event.currentDataType = event.dataTypes[i];
                }
            }
        }

        public void dragOver(DropTargetEvent event) {
            event.feedback = DND.FEEDBACK_SELECT | DND.FEEDBACK_SCROLL;
        }

        public void drop(DropTargetEvent event) {
            if (TextTransfer.getInstance().isSupportedType(event.currentDataType)) {
                // Get the dropped data
                DropTarget target = (DropTarget) event.widget;
                Table table = (Table) target.getControl();
                String data = (String) event.data;

                // Create a new item in the table to hold the dropped data
                TableItem item = new TableItem(table, SWT.NONE);
                item.setText(new String[] { data });
                table.redraw();
            }
        }
    });
    TableColumn column = new TableColumn(table, SWT.NONE);

    // Seed the table
    TableItem item = new TableItem(table, SWT.NONE);
    item.setText(new String[] { "A" });
    item = new TableItem(table, SWT.NONE);
    item.setText(new String[] { "B" });
    item = new TableItem(table, SWT.BORDER);
    item.setText(new String[] { "C" });

    column.pack();
    shell.open();

    while (!shell.isDisposed()) {
        if (!display.readAndDispatch()) {
            display.sleep();
        }
    }
    display.dispose();
}

From source file:com.rest.samples.getTipoCambioBanxico.java

public static void main(String[] args) {
    String url = "http://www.banxico.org.mx/tipcamb/llenarTiposCambioAction.do?idioma=sp";
    try {//  www.  j a  v a2 s. c  o m
        HttpClient hc = HttpClientBuilder.create().build();
        HttpGet request = new HttpGet(url);
        request.setHeader("User-Agent", "Mozilla/5.0");
        request.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");

        HttpResponse res = hc.execute(request);
        if (res.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("Failed : HTTP eror code: " + res.getStatusLine().getStatusCode());
        }

        BufferedReader rd = new BufferedReader(new InputStreamReader(res.getEntity().getContent()));
        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        Document doc = Jsoup.parse(result.toString());
        Element tipoCambioFix = doc.getElementById("FIX_DATO");
        System.out.println(tipoCambioFix.text());

    } catch (IOException ex) {
        Logger.getLogger(SamplesUseHttpclient.class.getName()).log(Level.SEVERE, null, ex);
    }
}