Printing unicode characters in Java - help

Hi there,
I want to print out unicode characters through java programming language in windows system. For example, I want to print Devanagari characters. I found out that '\u0900' to '\u0975' represent devanagari characters. So I tried following,
out = new PrintStream(System.out, true, "UTF-8");
out.println('\u0911');
but they print characters like ��� and not the actual devanagari characters. Just to be more clear, devanagari script is used by Hindi, Nepali and similar languages.
If you knew about it and could give any suggestions, that would be very helpful.
Thanks in advance!

priyankabhar wrote:
I am not sure, it is just a windows system and I am trying to print to the command line. Please suggest me how I can find out if my console supports it.Use the CHCP command to find out what code page your console uses. And as already suggested, Google is a good resource if you don't know what a "code page" is.

Similar Messages

  • Printing Unicode characters

    Hi all,
    I am trying to print certain unicode characters to a file using this code:
    import java.io.*;
    public class Unicode{
         public static void main(String args[]) throws IOException{
              char[] c = new char[1];
              char ch= '\u0ce6'; //starting character
              File f = new File("c:\\UC.txt");
              BufferedWriter bf = new BufferedWriter(new FileWriter(f));
              while( ch < '\u0cef'){
                   c[0] = ch++;
                   bf.write(c, 0, 1);//write the character to a file
              bf.flush();
    }All I can see in the file is '?????????'. I tried printing it to file as command prompt also showed the same thing. How can I see the Unicode characters of different languages? Do I need to set any char encoding using System properties?
    Thank you very much.

    Sigh there is no such thing as plain text.
    You create a file with the platform encoding (read the API docu of the FileWriter). That platform encoding is probably not even able to represent all unicode characters (it's likely to be ISO-8859-1 or one of it's variants).
    Then you open that file without specifying the character set (it's guessed, possibly wrong) and you don't see the expected output.
    Read http://www.joelonsoftware.com/articles/Unicode.html for an introduction into the beautiful world of unicode.

  • Reading sequence of characters in Java-----HELP!!!

    I need help with this program here..Im new to Java and struggling to get this to work..here's the problem..
    The program monitors a possibly infinite stream of characters from the keyboard (standard input). If it detects the sequence "www" it outputs a "0". If it detects the sequence "wow" it outputs a "1". DO NOT detect sequences within sequences. The program should exit cleanly when it detects an End Of Input. For example:
    The following sequence wwowowwwowww<End Of Input> would produce the following result: 100
    While the following sequence wwwowowwwwoowowow<End Of Input> would produce the following result: 0101

    If you want to catch each key input realtime, you should use KeyEvent in a Swing/AWT GUI program. Capture each triplet in a small char array and compare it against "www" or "wow".
    Here's a simple code that shows the principle:
    public class Exl5{
      public static void main(String[] args){
        String s1 = "wwowowwwowww";
        String s2 = "wwwowowwwwoowowow";
        System.out.println(convert(s1));
        System.out.println(convert(s2));
      static String convert(String s){
        StringBuffer sb = new StringBuffer();
        int p = 0;
        while (p < s.length() - 2){
          String ss = s.substring(p, p + 3);
          if (ss.equals("wow")){
            sb.append("1");
            p += 3;
          else if (ss.equals("www")){
            sb.append("0");
            p += 3;
          else{
            ++p;
        return new String(sb);
    }

  • UNICODE characters in JAVA

    i have a doubt about the following codes
    public class Attempt
    // char a='\u000A';
    this code is not compiling even i the line is commented in the code.
    it gives the following compile time error:
    ---------- javac ----------
    D:\saurabh\Attempt.java:4: unclosed character literal
    ^
    D:\saurabh\Attempt.java:4: <identifier> expected
    ^
    2 errors
    Normal Termination
    Output completed (1 sec consumed).
    IS this a bug in JAVA
    plz reply to this
    rajeev

    This happens because the unicode literals are translated prior to compilation;
    \u000a is the LF character, so what you actually get the compiler trying to
    handle is:
    char c = '    // the unicode has been replaced by the character it represents
    ';or something similar.
    It might have been nicer if these literals were preserved during compilation and
    substituted at run time, but that would probably cause all kinds of other
    technical problems.

  • How do I get unicode characters out of an oracle.xdb.XMLType in Java?

    The subject says it all. Something that should be simple and error free. Here's the code...
    String xml = new String("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<x>\u2026</x>\n");
    XMLType xmlType = new XMLType(conn, xml);
    conn is an oci8 connection.
    How do I get the original string back out of xmlType? I've tried xmlType.getClobVal() and xmlType.getString() but these change my \u2026 to 191 (question mark). I've tried xmlType.getBlobVal(CharacterSet.UNICODE_2_CHARSET).getBytes() (and substituted CharacterSet.UNICODE_2_CHARSET with a number of different CharacterSet values), but while the unicode characters are encoded correctly the blob returned has two bytes cut off the end for every unicode character contained in the original string.
    I just need one method that actually works.
    I'm using Oracle release 11.1.0.7.0. I'd mention NLS_LANG and file.encoding, but I'm setting the PrintStream I'm using for output explicitly to UTF-8 so these shouldn't, I think, have any bearing on the question.
    Thanks for your time.
    Stryder, aka Ralph

    I created analogic test case, and executed it with DB 11.1.0.7 (Linux x86), which seems to work fine.
    Please refer to the execution procedure below:
    * I used AL32UTF8 database.
    1. Create simple test case by executing the following SQL script from SQL*Plus:
    connect / as sysdba
    create user testxml identified by testxml;
    grant connect, resource to testxml;
    connect testxml/testxml
    create table testtab (xml xmltype) ;
    insert into testtab values (xmltype('<?xml version="1.0" encoding="UTF-8"?>'||chr(10)||'<x>'||unistr('\2026')||'</x>'||chr(10)));
    -- chr(10) is a linefeed code.
    commit;
    2. Create QueryXMLType.java as follows:
    import java.sql.*;
    import oracle.sql.*;
    import oracle.jdbc.*;
    import oracle.xdb.XMLType;
    import java.util.*;
    public class QueryXMLType
         public static void main(String[] args) throws Exception, SQLException
              DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
              OracleConnection conn = (OracleConnection) DriverManager.getConnection("jdbc:oracle:oci8:@localhost:1521:orcl", "testxml", "testxml");
              OraclePreparedStatement stmt = (OraclePreparedStatement)conn.prepareStatement("select xml from testtab");
              ResultSet rs = stmt.executeQuery();
              OracleResultSet orset = (OracleResultSet) rs;
              while (rs.next())
                   XMLType xml = XMLType.createXML(orset.getOPAQUE(1));
                   System.out.println(xml.getStringVal());
              rs.close();
              stmt.close();
    3. Compile QueryXMLType.java and execute QueryXMLType.class as follows:
    export PATH=$ORACLE_HOME/jdk/bin:$PATH
    export LD_LIBRARY_PATH=$ORACLE_HOME/lib
    export CLASSPATH=.:$ORACLE_HOME/jdbc/lib/ojdbc5.jar:$ORACLE_HOME/jlib/orai18n.jar:$ORACLE_HOME/rdbms/jlib/xdb.jar:$ORACLE_HOME/lib/xmlparserv2.jar
    javac QueryXMLType.java
    java QueryXMLType
    -> Then you will see U+2026 character (horizontal ellipsis) is properly output.
    My Java code came from "Oracle XML DB Developer's Guide 11g Release 1 (11.1) Part Number B28369-04" with some modification of:
    - Example 14-1 XMLType Java: Using JDBC to Query an XMLType Table
    http://download.oracle.com/docs/cd/B28359_01/appdev.111/b28369/xdb11jav.htm#i1033914
    and
    - Example 18-23 Using XQuery with JDBC
    http://download.oracle.com/docs/cd/B28359_01/appdev.111/b28369/xdb_xquery.htm#CBAEEJDE

  • Java class names which contain unicode characters

    I need to create, compile and load java classes which have class names that contain unicode characters.
    I am using Win2k but will neet to support unix* in future.
    When I try to create a fooXbar.jar where X is a unicode character which is not ascii I get an error when creating the file.
    My question is: how do I map java class names and package names which contain non ascii characters into
    names that the files systems will like AND that the java VM will use when trying to load .class file from the class path.
    for example what would the .java and .class file be for the following class?
    class \u6587\u66f8 {

    You could make names for .java and .class that is understandable by the filesystem. E.g. you could prepend with % and then digits for the unicode character. The problem is then how to compile the class, and how to load the class.
    You can load the class with a custom classloader, which will translate the unicode class name to the escaped file name (using %).
    The problem is then reduced to how you can compile your code (you have to map the file name to the class name somehow). I think it can be done, but I don't know the solution to that.
    Alternatively you can use meaningful names for the classes, and then make an obfuscator that can change the bytecodes so the classnames are changed to some obscure unicode names. Perhaps there is already obfuscators out there you can use that will use unicode characters.

  • Java Editor and Unicode Characters

    I'm trying to use unicode characters in strings with the Java Editor.
    String myOption = "\u2666 " + myDirName;
    This works nicely, displaying a diamond in my web application. Source HTML contains a &9830;
    However, if I make changes in the Visual Designer (e.g., add a button), the \u2666 in my Java code changes to a diamond symbol. When that happens, I get a "?" in my web application.
    How do I prevent Java Editor from switching to the display character?

    Thanks for your response.
    After more research, I found that the .java file is corrupted. These means the problem is not related to the browser.
    When I have "\u2666" in the Java Editor window, I see "\u2666" in the .java file in Word Pad. This is properly compiled and the entity &#9830; appears in the HTML.
    When the diamond symbol is in the Java Editor window, I see and ascii ? (character #3F). I get a ? in the browser. It is really a question mark (#3F) not an unknown character.
    So, it appears that when the JSP is changed by adding a button, the .java code is rewritten to disk but unicode characters are not translated properly. Or - something like that. If I could keep the ascii string "\u2666" from converting to the diamond, I would be all set.
    I can edit the Java Code, close, save and reopen all I want and the unicode character doesn't translate to the symbol. This ONLY happens when the JSP is modified.
    Any ideas?

  • Error Message:"Cannot find or create the font 'WP-MathA'. Some characters may not display or print correctly."  Who can help me solve this problem?

    Some of the pdf files I work with (receive) come up with a comment: “Cannot find or create the font ‘WP-MathA’. Some characters may not display or print correctly.”  Who can help me solve this problem?
    Thank you in advance for  your time.
    Marlen

    Hello Anubha,
    I am having a similar problem on my machine.  I was using Word 2008 and I created a PDF inside Word.
    I am opening the file on the system itself and I am running Windows 8.1.  I am using Version 11 of Reader.
    When the PDF I created (my resume) attempts to open, it says:  cannot find or create the file Times, Bold.  Some characters may not display or print correctly. 
    However, the entire Reader keeps freezing and will not allow me to open or test print the document.  Also, it is not displaying any of the Bold Times New Roman Print.  Can you please help?  Thanks.

  • Do java supports all unicode characters including telugu..??

    Hello to Everybody..!
    Iam rather new to java technologies and I want to know whether java supports telugu language and if it supports it ,how can we implement it? and is there any system requirements for it.?
    Please Kindly consider this query and Thankks in advance.

    Yes, Java supports all Unicode characters. If you want to know more about Unicode, have a look at its website:
    http://www.unicode.org/
    Telugu characters are in their code charts here:
    http://www.unicode.org/charts/PDF/U0C00.pdf
    You don't have to "implement" anything. System requirements would include a font that can render those characters. I don't know about keyboards.

  • Printing Unicode By Java

    how can i Print out Bengali in java
    Programming???????
    how can i use Bengali?????

    priyankabhar wrote:
    I am not sure, it is just a windows system and I am trying to print to the command line. Please suggest me how I can find out if my console supports it.Use the CHCP command to find out what code page your console uses. And as already suggested, Google is a good resource if you don't know what a "code page" is.

  • Printing Khmer characters correctly, with ligature substitutions

    I'm trying to implement printing of characters from the Khmer writing system. The characters and the font are both Unicode and using the font in other applications works fine. However in Java, using the Java 2D printing, the characters are not printed correctly. It appears that the ligatures are not placed in the proper location. I have a sample application that shows the problem. I'm looking for help to either found out if this is a bug in Java or if I'm missing the obvious.
    I've search the Java forums and can't find much on this topic. Please point me.
    PS. I can't see away to attach my sample. If you think that would be helpful say so and I'll paste it inline to this thread.

    I found that my problem can be solved by using a different font. In my tests I had used the Khmer OS * fonts and if I replaced the font with [Kh System.ttf|http://sourceforge.net/projects/khmer/files/Fonts%20-%20KhmerOS/Kh%20Uni%20fonts%20for%20design%20pro./ ] and ran my test program and I get the expected results.

  • Additional CR when printing unicode character

    Hello,
    the following code prints two lines on a printer. The second line contains an escaped unicode character. When running the example code I can't even see the unicode character on the paper; but in my original application it is visible. So this is not the problem. But always an additional carriage return is inserted after the unicode character, thus overprinting the beginning of the line with the remaining text. This did not occur in java 6 if I remember correctly. Is there any workaround for this?
    Regards
    J.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.print.*;
    import javax.swing.*;
    public class HelloWorldPrinter implements Printable, ActionListener {
        public int print(Graphics g, PageFormat pf, int page) throws
                                                            PrinterException {
            if (page > 0) return NO_SUCH_PAGE;
            Graphics2D g2d = (Graphics2D)g;
            g2d.translate(pf.getImageableX(), pf.getImageableY());
            g.drawString("Hello world!", 100, 100);
            g.drawString("Now the line with a unicode \u2259 character.", 100, 120);
            return PAGE_EXISTS;
        public void actionPerformed(ActionEvent e) {
             PrinterJob job = PrinterJob.getPrinterJob();
             job.setPrintable(this);
             boolean ok = job.printDialog();
             if (ok) {
                 try {
                      job.print();
                 } catch (PrinterException ex) {
                      System.out.println(ex);
        public static void main(String args[]) {
    //        UIManager.put("swing.boldMetal", Boolean.FALSE);
            JFrame f = new JFrame("Hello World Printer");
            f.addWindowListener(new WindowAdapter() {
               public void windowClosing(WindowEvent e) {
               System.exit(0);
            JButton printButton = new JButton("Print");
            printButton.addActionListener(new HelloWorldPrinter());
            f.add("Center", printButton);
            f.pack();
            f.setVisible(true);
    }

    Hello Sabre,
    thank you for testing. Of course it's good news that you don't see any overprinting, but unfortunately that doesn't help me on my site (Win7 64-Bit, java 1.7.0_09).
    Since I can see the character in my original application as I wrote, I made up the following test case and met a strange behaviour. I can make my desired unicode character appear without any overprinting as long as I don't use any other character in the string below 2000(16).
    Kindly run the following code. It prints a line of unicode characters starting with my desired one.
    Then change iConstant in makeTextLine() to any value below 0x2000. At my site this results in overprinting.
    Does it also happen at yours?
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.print.*;
    import javax.swing.*;
    public class UnicodeTest extends JFrame implements Printable {
      String text= "Test line with unicode \u2259 character.";
      public UnicodeTest() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(350, 200);
        text= makeTextLine();
        JLabel lb= new JLabel("<html>Printing started...<br>"+text);
        add(lb);
        setVisible(true);
        PrinterJob printerJob= PrinterJob.getPrinterJob();
        printerJob.setPrintable(this);
        try {
          printerJob.print();
        catch (PrinterException e) {
          System.out.println("PrinterException: "+e);
      public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
          public void run() {
         new UnicodeTest();
      public String makeTextLine() {
        StringBuilder sb= new StringBuilder();
        int iStartValue= 0x2259;
        int iConstant= 0x2020; // Tested with 0x100, 200, 400, 800, 1000, 2000.
        for (int i=iStartValue; i<iStartValue+30; i++) {
          sb.append((char)i);
          sb.append((char)iConstant);
        return sb.toString();
      public int print(Graphics g, PageFormat pf, int page) throws
                                                            PrinterException {
        if (page > 0) return NO_SUCH_PAGE;
        Graphics2D g2d = (Graphics2D)g;
        g2d.translate(pf.getImageableX(), pf.getImageableY());
        g2d.setFont(new Font("Dialog", Font.PLAIN, 12));
        g.drawString(text, 50, 40);
        return PAGE_EXISTS;
    }

  • Problems reading unicode characters with BufferedReader or PrintWriter

    I am creating a pretty standard chat server and client with the exception that I want to be able to send special math symbols back and forth to aid in helping people with math homework. The unicode characters will appear on the buttons, in the textField (where users type in their messages), in the messageArea (where users see all of the messages) correctly. However, as soon as the server reads it, it is converted to a ? character by either the BufferedReader or the PrintWriter, but I am fairly certain it is the BufferedReader. All of the Sun examples I have read recommend doing exactly what I have done to be able to support unicode characters so I am somewhat at a loss. Any help would be appreciated. I will include all of the source code (which is rather large) but the main problem is the with the BufferedReader or PrintWriter when the servers reads the string in and then broadcasts it to all the clients (at least I'm pretty sure it is).
    // ChatServer.java
    import java.net.Socket;
    import java.net.ServerSocket;
    import java.io.InputStreamReader;
    import java.io.BufferedReader;
    import java.io.PrintWriter;
    import java.io.IOException;
    import java.util.Set;
    import java.util.HashSet;
    import java.util.HashMap;
    import java.util.Iterator;
    * A multithreaded chat room server. When a client connects the
    * server requests a screen name by sending the client the
    * text "SUBMITNAME", and keeps requesting a name until
    * a unique one is received. After a client submits a unique
    * name, the server acknowledges with "NAMEACCEPTED". Then
    * all messages from that client will be broadcast to all other
    * clients that have submitted a unique screen name. The
    * broadcast messages are prefixed with "MESSAGE ".
    * Because this is just a teaching example to illustrate a simple
    * chat server, there are a few features that have been left out.
    * Two are very useful and belong in production code:
    * 1. The protocol should be enhanced so that the client can
    * send clean disconnect messages to the server.
    * 2. The server should do some logging.
    public class ChatServer {
    * The port that the server listens on.
    private static final int PORT = 9001;
    * The set of all names of clients in the chat room. Maintained
    * so that we can check that new clients are not registering name
    * already in use.
    private static HashSet names = new HashSet();
    * The set of all the print writers for all the clients. This
    * set is kept so we can easily broadcast messages.
    private static HashMap writers = new HashMap();
    private static HashMap userSockets = new HashMap();
    private static Set keys;
    * The appplication main method, which just listens on a port and
    * spawns handler threads.
    public static void main(String[] args) throws Exception {
    System.out.println("The chat server is running.");
    ServerSocket listener = new ServerSocket(PORT);
    try {
    while (true) {
    new Handler(listener.accept()).start();
         } catch (Exception e) {
    } finally {
    listener.close();
    * A handler thread class. Handlers are spawned from the listening
    * loop and are responsible for a dealing with a single client
    * and broadcasting its messages.
    private static class Handler extends Thread {
    private String name;
    private Socket socket;
    private BufferedReader in;
    private PrintWriter out;
    * Constructs a handler thread, squirreling away the socket.
    * All the interesting work is done in the run method.
    public Handler(Socket socket) {
    this.socket = socket;
    public void disconnect(String userName) {
    if (userName != null) {
    names.remove(userName);
    if (writers.get(userName) != null) {
    writers.remove(userName);
    try {
    ((Socket)userSockets.get(userName)).close();
    } catch (IOException e) {
    e.printStackTrace();
    System.out.println(userName +" has disconnected from the Chat Server.");
    keys = writers.keySet();
    for (Iterator i = keys.iterator(); i.hasNext(); ) {
    ((PrintWriter)writers.get(i.next())).println(
    "USERQUIT" +name);
    public void disconnectAll() {
    for (Iterator i = names.iterator(); i.hasNext();) {
    String userName = i.next().toString();
    if (!userName.equals("administrator")) {
    names.remove(userName);
    keys = writers.keySet();
    for (Iterator it = keys.iterator(); it.hasNext(); ) {
    ((PrintWriter)writers.get(it.next())).println(
    "USERQUIT" +name);
    writers.remove(userName);
    userSockets.remove(userName);
    * Services this thread's client by repeatedly requesting a
    * screen name until a unique one has been submitted, then
    * acknowledges the name and registers the output stream for
    * the client in a global set, then repeatedly gets inputs and
    * broadcasts them.
    public void run() {
    try {
    // Create character streams for the socket.
    in = new BufferedReader(new InputStreamReader(
    socket.getInputStream()));
    out = new PrintWriter(socket.getOutputStream(), true);
    // Request a name from this client. Keep requesting until
    // a name is submitted that is not already used. Note that
    // checking for the existence of a name and adding the name
    // must be done while locking the set of names.
    while (true) {
    out.println("SUBMITNAME");
    name = in.readLine();
    if (name == null) {
    return;
    synchronized (names) {
    if (!names.contains(name) && name.equalsIgnoreCase("administrator")) {
    out.println("SUBMITPASSWORD");
    String password = in.readLine();
    if (password.equals("s3cure")) {
    out.println("GRANTEDADMIN");
    if (!names.contains(name)) {
    names.add(name);
    break;
    // Now that a successful name has been chosen, add the
    // socket's print writer to the set of all writers so
    // this client can receive broadcast messages.
    out.println("NAMEACCEPTED");
    keys = writers.keySet();
    for (Iterator i = keys.iterator(); i.hasNext(); ) {
    ((PrintWriter)writers.get(i.next())).println(
    "USERJOIN" +name);
    writers.put(name, out);
    userSockets.put(name, socket);
    System.out.println(name +" has successfully connected to the Chat Server.");
    // Accept messages from this client and broadcast them.
    // Ignore other clients that cannot be broadcasted to.
    while (true) {
    String input = in.readLine();
    if (input == null) {
    return;
              else if (input.startsWith("LISTUSERS")) {
                   Iterator i = names.iterator();
                   String namesString = new String();
                   while (i.hasNext()) {
                   namesString += " " +i.next();
                   out.println("USERLIST " +namesString);
         catch (Exception e) {
         finally {
              disconnect(name);
    // ChatClient.java
    import java.util.HashSet;
    import java.util.StringTokenizer;
    import java.util.Iterator;
    import java.util.LinkedList;
    import java.util.ListIterator;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowAdapter;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.KeyListener;
    import java.awt.event.KeyEvent;
    import java.awt.Point;
    import java.awt.Button;
    import java.awt.Font;
    import java.awt.BorderLayout;
    import java.awt.FlowLayout;
    import java.awt.Dimension;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    import javax.swing.JTextArea;
    //import javax.swing.JTextPane;
    import javax.swing.JScrollPane;
    import javax.swing.JOptionPane;
    import javax.swing.JList;
    import javax.swing.DefaultListModel;
    import javax.swing.JMenuBar;
    import javax.swing.JMenu;
    import javax.swing.JMenuItem;
    import javax.swing.JPopupMenu;
    import java.net.Socket;
    import java.io.InputStreamReader;
    import java.io.BufferedReader;
    import java.io.PrintWriter;
    import java.io.IOException;
    * A simple Swing-based client for the chat server. Graphically
    * it is a frame with a text field for entering messages and a
    * textarea to see the whole dialog.
    * The client follows the Chat Protocol which is as follows.
    * When the server sends "SUBMITNAME" the client replies with the
    * desired screen name. The server will keep sending "SUBMITNAME"
    * requests as long as the client submits screen names that are
    * already in use. When the server sends a line beginning
    * with "NAMEACCEPTED" the client is now allowed to start
    * sending the server arbitrary strings to be broadcast to all
    * chatters connected to the server. When the server sends a
    * line beginning with "MESSAGE " then all characters following
    * this string should be displayed in its message area.
    public class ChatClient {
    BufferedReader in;
    PrintWriter out;
    JFrame frame = new JFrame("Math Chatter version 0.3");
    JTextField textField = new JTextField(40);
    JTextArea messageArea = new JTextArea(25, 40);
    //JTextPane messageArea = new JTextPane();
    // Menu
    JMenuBar menuBar = new JMenuBar();
    // File Menu and MenuItems
    JMenu fileMenu = new JMenu();
    JMenuItem connectMenuItem = new JMenuItem();
    JMenuItem disconnectMenuItem = new JMenuItem();
    JMenuItem exitMenuItem = new JMenuItem();
    // Help Menu and MenuItems
    JMenu helpMenu = new JMenu();
    JMenuItem aboutMenuItem = new JMenuItem();
    JOptionPane aboutDialog = new JOptionPane();
    // Message Area Popup Menu and MenuItems
    JPopupMenu messageAreaPopupMenu = new JPopupMenu();
    JMenuItem connectPopupMenuItem = new JMenuItem();
    JMenuItem disconnectPopupMenuItem = new JMenuItem();
    JMenuItem clearTextMenuItem = new JMenuItem();
    JMenuItem exitPopupMenuItem = new JMenuItem();
    MouseListener messageAreaPopupListener = new messageAreaPopupListener();
    // User Area Popup Menu and MenuItems
    JPopupMenu userAreaPopupMenu = new JPopupMenu();
    JMenuItem pingPopupMenuItem = new JMenuItem();
    JMenuItem disconnectUserPopupMenuItem = new JMenuItem();
    JMenuItem disconnectAllUsersPopupMenuItem = new JMenuItem();
    MouseListener userAreaPopupListener = new userAreaPopupListener();
    // Panel with textfield, send, and clear buttons
    JPanel sendTextPanel = new JPanel();
    // Panel that has all the math buttons
    JPanel buttonPanel = new JPanel();
    // Panel that has messageArea and users panell
    JPanel displayPanel = new JPanel();
    DefaultListModel listModel = new DefaultListModel();
    JList userNamesList = new JList(listModel);
    //JTextArea userNamesTextArea = new JTextArea(25, 10);
    // buttonPanel stuff
    Button sendButton = new Button();
    Button clearButton = new Button();
    Button infinityButton = new Button();
    Button thetaButton = new Button();
    Button limitButton = new Button();
    Button thereforeButton = new Button();
    JLabel buttonLabel = new JLabel("Useful math stuff: ");
    HashSet usersHashSet = new HashSet();
    LinkedList sentMessageList = new LinkedList();
    ListIterator sentMessageIterator;
    boolean isAdmin = false;
    * Constructs the client by laying out the GUI and registering a
    * listener with the textfield so that pressing Return in the
    * listener sends the textfield contents to the server. Note
    * however that the textfield is initially NOT editable, and
    * only becomes editable AFTER the client receives the NAMEACCEPTED
    * message from the server.
    public ChatClient() {
    // -----------------> Layout MenuBar
    frame.setJMenuBar(menuBar);
    fileMenu.setText("File");
    connectMenuItem.setText("Connect");
    connectMenuItem.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    showWhoopsDialog();
    /*out.println("CONNECT");
    try {
    run();
    catch (Exception ex) {
    ex.printStackTrace();
    fileMenu.add(connectMenuItem);
    disconnectMenuItem.setText("Disconnect");
    disconnectMenuItem.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    chatDisconnect();
    fileMenu.add(disconnectMenuItem);
    exitMenuItem.setText("Exit");
    exitMenuItem.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    frame.dispose();
    System.exit(0);
    return;
    fileMenu.add(exitMenuItem);
    menuBar.add(fileMenu);
    helpMenu.setText("Help");
    aboutMenuItem.setText("About");
    aboutMenuItem.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    aboutDialog.setDoubleBuffered(true);
    aboutDialog.showMessageDialog(frame,
    "Chat Server and Client were originally written by Ray Toal and were found at \n http://www.technocage.com/~ray/viewsource.jsp?java/networking/ChatServer.java and \n http://www.technocage.com/~ray/viewsource.jsp?java/networking/ChatClient.java. \n\n Math Chatter and all revisions have been done by William Ready.",
    "About Math Chatter Server and Client version 0.3",
    JOptionPane.INFORMATION_MESSAGE);
    helpMenu.add(aboutMenuItem);
    menuBar.add(helpMenu);
    // -----------> End Menu
    // -----------> Popup Menus
    // -----------> Message Area Popup Menu
    connectPopupMenuItem.setText("Connect");
    connectPopupMenuItem.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    showWhoopsDialog();
    disconnectPopupMenuItem.setText("Disconnect");
    disconnectPopupMenuItem.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    chatDisconnect();
    clearTextMenuItem.setText("Clear text");
    clearTextMenuItem.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    messageArea.setText("");
    exitPopupMenuItem.setText("Exit");
    exitPopupMenuItem.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    frame.dispose();
    System.exit(0);
    messageAreaPopupMenu.add(connectPopupMenuItem);
    messageAreaPopupMenu.add(disconnectPopupMenuItem);
    messageAreaPopupMenu.add(clearTextMenuItem);
    messageAreaPopupMenu.add(exitPopupMenuItem);
    messageArea.addMouseListener(messageAreaPopupListener);
    // -----------> End Message Area Popup Menu
    // -----------> User Area Popup Menu
    pingPopupMenuItem.setText("Ping User");
    pingPopupMenuItem.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    //System.out.println("Yo yo yo");
    disconnectUserPopupMenuItem.setText("Disconnect User");
    disconnectUserPopupMenuItem.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    if (userNamesList.getSelectedValue() != null) {
    //System.out.println("Yo yo yo");
    out.println("DISCONNECTUSER " +userNamesList.getSelectedValue().toString());
    //disconnectUserPopupMenuItem.setEnabled(false);
    disconnectUserPopupMenuItem.setVisible(false);
    disconnectAllUsersPopupMenuItem.setText("Disconnect All Users");
    disconnectUserPopupMenuItem.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    if (userNamesList.getSelectedValue() != null) {
    //System.out.println("Yo yo yo");
    out.println("DISCONNECTALLUSERS");
    //disconnectUserPopupMenuItem.setEnabled(false);
    disconnectAllUsersPopupMenuItem.setVisible(false);
    userAreaPopupMenu.add(pingPopupMenuItem);
    userAreaPopupMenu.add(disconnectUserPopupMenuItem);
    userAreaPopupMenu.add(disconnectAllUsersPopupMenuItem);
    userNamesList.addMouseListener(userAreaPopupListener);
    // -----------> End User Area Popup Menu
    // -----------> End Popup Menus
    // -----------> Layout GUI
    textField.setEditable(false);
    textField.requestDefaultFocus();
    messageArea.setEditable(false);
    sendTextPanel.setLayout(new FlowLayout());
    sendTextPanel.add(textField);
    sendButton.setLabel("Send");
    sendButton.setEnabled(false);
    sendTextPanel.add(sendButton);
    clearButton.setLabel("Clear");
    sendTextPanel.add(clearButton);
    buttonPanel.setLayout(new FlowLayout());
    buttonPanel.add(buttonLabel);
    infinityButton.setLabel("\u221e");
    buttonPanel.add(infinityButton);
         thetaButton.setLabel("\u03b8");
    buttonPanel.add(thetaButton);
    limitButton.setLabel("lim");
    buttonPanel.add(limitButton);
    thereforeButton.setLabel("\u2234");
    buttonPanel.add(thereforeButton);
    userNamesList.setVisibleRowCount(26);
    userNamesList.setFixedCellWidth(110);
    JScrollPane nameTextScrollPane = new JScrollPane(userNamesList);
    JScrollPane messageAreaScrollPane = new JScrollPane(messageArea);
    displayPanel.setLayout(new FlowLayout());
    displayPanel.add(messageAreaScrollPane);
    displayPanel.add(nameTextScrollPane);
    frame.getContentPane().add(sendTextPanel, "North");
    frame.getContentPane().add(displayPanel, "Center");
    frame.getContentPane().add(buttonPanel, "South");
    frame.pack();
    // ---------------> Add Listeners
    textField.addKeyListener(new KeyListener() {
    public void keyPressed(KeyEvent e){ }
    public void keyTyped(KeyEvent e){
    if (e.getKeyChar() == KeyEvent.VK_UP) {
    if (sentMessageIterator.hasNext()) {
    textField.setText((String)sentMessageIterator.next());
    if (e.getKeyChar() == KeyEvent.VK_DOWN) {
    if (sentMessageIterator.hasPrevious()) {
    textField.setText((String)sentMessageIterator.previous());
    if (e.getKeyChar() == KeyEvent.VK_ENTER) {
    String text = textField.getText();
    if (text != null && !(text.equals(""))) {
    sentMessageList.addFirst(textField.getText());
    sentMessageIterator = sentMessageList.listIterator();
    out.println(textField.getText());
    textField.setText("");
    public void keyReleased(KeyEvent e){}
    sendButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    out.println(textField.getText());
    textField.setText("");
    textField.requestFocus();
    clearButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    textField.setText("");
    textField.requestFocus();
    infinityButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    textField.setText(textField.getText() +"\u221e");
    textField.requestFocus();
    thetaButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    textField.setText(textField.getText() +"\u03b8");
    textField.requestFocus();
    limitButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    String limit = JOptionPane.showInputDialog(frame,
    "Enter the value that the variable approaches. \n If the value is infinity, type in inf. \n (Note: the variable name is irrelevant)",
    "Value that variable approaches",
    JOptionPane.QUESTION_MESSAGE);
    if (limit != null && limit.equalsIgnoreCase("inf"))
    textField.setText(textField.getText() +"lim [x->\u221e] ");
    else if (limit != null)
    textField.setText(textField.getText() +"lim [x->" +limit +"] ");
    textField.requestFocus();
    thereforeButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    textField.setText(textField.getText() +"\u2234");
    textField.requestFocus();
    // -------------> End Listeners
    // -------------> End GUI
    * Prompt for and return the address of the server.
    private String getServerAddress() {
    return JOptionPane.showInputDialog(
    frame,
    "Enter IP Address of the Server:",
    "Welcome to the Chatter",
    JOptionPane.QUESTION_MESSAGE);
    private void showWhoopsDialog() {
    JOptionPane.showMessageDialog(frame,
    "Unfortunately this feature has not been implemented yet. \n The only way to connect currently is to exit the program \n and start it again",
    "Whoops!",
    JOptionPane.ERROR_MESSAGE);
    private void chatDisconnect() {
    messageArea.append("You have disconnected from the Chat Server\n");
    textField.setEditable(false);
    messageArea.setEnabled(false);
    userNamesList.setEnabled(false);
    fileMenu.requestFocus();
    out.println("DISCONNECT");
    * Prompt for and return the desired screen name.
    private String getName() {
    return JOptionPane.showInputDialog(
    frame,
    "Choose a screen name:",
    "Screen name selection",
    JOptionPane.PLAIN_MESSAGE);
    private String getPassword() {
    return JOptionPane.showInputDialog(
    frame,
    "Type in your password:",
    "Password Input",
    JOptionPane.PLAIN_MESSAGE);
    * Connects to the server then enters the processing loop.
    private void run() throws IOException {
    // Make connection and initialize streams
    String serverAddress = getServerAddress();
    if (serverAddress != null && !(serverAddress.equals(""))) {
    Socket socket = new Socket(serverAddress, 9001);
    in = new BufferedReader(new InputStreamReader(
    socket.getInputStream()));
    out = new PrintWriter(socket.getOutputStream(), true);
    // Process all messages from server, according to the protocol.
    while (true) {
    try {
    String line = in.readLine();
    if (line.startsWith("SUBMITNAME")) {
    out.println(getName());
              } else if (line.startsWith("NAMEACCEPTED")) {
    textField.setEditable(true);
              out.println("LISTUSERS");
    sendButton.setEnabled(true);
    //messageArea.setEnabled(true);
    } else if (line.startsWith("SUBMITPASSWORD")) {
    out.println(getPassword());
    } else if (line.startsWith("GRANTEDADMIN")) {
    isAdmin = true;
    //disconnectUserPopupMenuItem.setEnabled(true);
    disconnectUserPopupMenuItem.setVisible(true);
    disconnectAllUsersPopupMenuItem.setVisible(true);
    } else if (line.startsWith("DISCONNECT")) {
    sendButton.setEnabled(false);
    return;
    } else if (line.startsWith("USERLIST")) {
              StringTokenizer st = new StringTokenizer(line.substring(8), " ");
              while (st.hasMoreTokens()) {
              usersHashSet.add(st.nextToken());
    listModel.removeAllElements();
    for (Iterator i = usersHashSet.iterator(); i.hasNext(); ) {
              listModel.addElement(i.next());
    } else if (line.startsWith("USERJOIN")) {
              String userJoinName = line.substring(8).trim();
              usersHashSet.add(userJoinName);
              listModel.addElement(userJoinName);
    } else if (line.startsWith("USERQUIT")) {
              String userQuitName = line.substring(8).trim();
              usersHashSet.remove(userQuitName);
    listModel.removeElement(userQuitName);
    } else if (line.startsWith("MESSAGE")) {
    messageArea.setFont(new Font("Lucida Sans", Font.PLAIN, 12));
    messageArea.append(line.substring(8) + "\n");
    catch (Exception e) {
    //e.printStackTrace();
    return;
    * Runs the client as an application with a closeable frame.
    public static void main(String[] args) throws Exception {
    ChatClient client = new ChatClient();
    client.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    client.frame.setLocation(200, 100);
    client.frame.show();
    client.run();
    class messageAreaPopupListener extends MouseAdapter {
    public void mousePressed(MouseEvent e) {
    maybeShowPopup(e);
    public void mouseReleased(MouseEvent e) {
    maybeShowPopup(e);
    private void maybeShowPopup(MouseEvent e) {
    if (e.isPopupTrigger()) {
    messageAreaPopupMenu.show(e.getComponent(),
    e.getX(), e.getY());
    class userAreaPopupListener extends MouseAdapter {
    public void mousePressed(MouseEvent e) {
    maybeShowPopup(e);
    public void mouseReleased(MouseEvent e) {
    maybeShowPopup(e);
    private void maybeShowPopup(MouseEvent e) {
    if (e.isPopupTrigger()) {
    userAreaPopupMenu.show(e.getComponent(),
    e.getX(), e.getY());

    Yes, the code is large, isn't it. It is a good idea, when you have a problem you can't solve, to remove unnecessary code. When the problem disappears, then you know the code you just removed was probably the source of the problem.
    But in your case, I think that none of the 1000 lines of code you posted are the problem. You appear to be using Lucida Sans, which is a positive sign; it can render many of the characters you have hard-coded in your program. But apparently the problem is with characters that are coming from somewhere else? And you are using a PrintWriter to send them there and a BufferedReader to get them back? These convert your data from characters to bytes and back again using the default encoding for your system. Chances are that this encoding is some "extended ASCII" encoding that doesn't know how to map anything above \u00ff. You need to get an InputStreamReader and an OutputStreamWriter into your transmission. (Wrap your socket.getInputStream() in an InputStreamReader and wrap that in a BufferedReader, etc.) These objects can take an encoding name as their second parameter; try "UTF-8" or "UTF8" for the encoding. Their API documentation has a link to a page about encodings; follow that if you need more info.

  • How to print Chinese character in java

    Hi All,
    I have a problem .
    I am trying to read a file which contains chinese characters and the print the content of this file to the printer.
    But when the content of the file is being printed, it is printing weird characters and not chinese characters. Can anyone please help.
    Plese find below, my code.
    import java.io.*;
    import java.lang.*;
    import java.io.BufferedInputStream;
    class FileRead{
    //--------------------------------------------------< main >--------//
    public static void main (String[] args) {
    FileRead t = new FileRead();
    t.readMyFile();
    //--------------------------------------------< readMyFile >--------//
    void readMyFile() {
    String record = null;
    int recCount = 0;
    try {
         FileReader fr = new FileReader("amaebisushi.GB.TXT");
         FileOutputStream os = new FileOutputStream("\\\\ps_apex_1\\ps_lpt1");
    BufferedReader br = new BufferedReader(fr);
    PrintStream ps2 = new PrintStream(os);
    record = new String();
    while ((record = br.readLine()) != null) {
    recCount++;
    System.out.println(recCount + ": " + record);
    ps2.println(recCount + ": " + record);
    } catch (IOException e) {
    // catch possible io errors from readLine()
    System.out.println("Uh oh, got an IOException error!");
    e.printStackTrace();
    } // end of readMyFile()
    } // end of class

    Try not to rely upon the default encoding, but define it explicitly.

  • Insert Unicode Characters Into Oracle 8.1.5

    Hello,
    First off, here are the specs:
    Oracle 8.1.5
    JDK 1.2.1
    Oracle8i 8.1.6.2.0 JDBC Drivers for use with JDK 1.2.x for Solaris
    I'm running into a problem with insert Unicode characters into Oracle via the JDBC driver. As you can see above, I am using the Oracle 8.1.6.2.0 JDBC driver because it is the first driver with supports the JDK 1.2.x. So I think I should be okay.
    I can retrieve data with special characters from Oracle by calling the getBytes() method from the ResultSet with all special characters being intact. I am using getBytes because calling getString() would throw the following exception: "java.sql.SQLException(): Fail to convert between UTF8 and UCS2: failUTF8Conv". However, with that value that I just retrieved, or any other data with special characters (unicode) in which I try to insert into Oracle does not get converted properly.
    What appears to be happening is that data with special characters (unicode), are not being treated as a single double byte character, but rather two single byte characters. Thus, R|ckschlagventil becomes RC<ckschlagventil once it is inserted. (Hopefully, my example will be rendered properly).
    According to all documentation that I have found, the JDBC driver should not have any problem with converting UCS2 Java Strings to Oracle's UTF8 character set.
    I have set Oracle's NLS_NCHAR_CHARACTERSET to UTF8. I am also setting the environment variable NLS_LANG to AMERICAN_AMERICA.UTF8. Perhaps there is some other environment setting in which I am missing?
    Any help would be appreciated,
    Christian
    null

    Import has a lot of options, so it depends on what you want to do.
    C:\> imp help=y
    will show you all possible options. An example of full import :
    C:\> imp <username>/<password>@<TNS alias> file=<DMP file> full=y log=<LOG file>
    Message was edited by:
    Paul M.
    ...and there is always [url http://download-uk.oracle.com/docs/cd/F49540_01/DOC/index.htm]The documentation

Maybe you are looking for

  • Change font of a portion of text in ring menu

    Hi, I would like to change the font of a portion of a text in a ring menu but it seems that it's more complicated than expected. I tried to adapt this (http://digital.ni.com/public.nsf/allkb/6BD344ACA4D​EE20A8625692700737E16) to my purpose. Here is m

  • Encoding Problem in solaris

    I generated a document in a solaris machine which follows the encoding scheme "ISO-8859-1". This document contains symbols such as British currency pound symbols. Now, I am passing this document as an input to my application. My application runs on a

  • Having trouble compiling netmap kernel module

    Hey everyone, First time poster here. Hopefully this question isn't too stupid but I've been having a hard time figuring this out. I'm trying to install the netmap drivers for Arch. I've downloaded the header files through pacman, but the configure s

  • 2 timelines  2 fps   how to combine ?

    I've got one timeline at 29.97 and one at 23.98 I need to cut in the 30fps footage into the 24p timeline, whats the best workflow? can I use cinetools to convert it to 24 and it will look fine? I'm afraid it will look all jumpy after the conversion.

  • Russian pdf file

    Im using Adobe Reader X ver. 10.1.0 running on a windows xp sp3 - and have now discovered a problem, which actually has started a long tim ago, but only have com to my attention now.´ When opening a Russian pdf file - I can not read some of the conte