Encoding chars

I have a basic question about Internationalization.
We are using 1.3.1. I am writing an xml file. However there will be international characters. Instead of writing, for instance, the "A" with the 2 dots, I would like to write Ä. I see that 1.4.1 has some nice classes in the packages java.nio.*. I am assuming I would use CharsetEncoder if I could use 1.4.1. However we have to use 1.3.1. Does anyone have any suggestions on how to write encoded chars?
thanks in advance

(in the java source code)
=========================
You have two choices to type non-ascii char.
1) Use unicode-encoded(\udddd) notation for non ascii char.
You can find \u notation from unicode.org. If you have a native file that contains non-ascii, please use native2ascii tool that comes with J2SE. It's under [jdk]/bin dirrectory. You can find usage doc from,
http://java.sun.com/j2se/1.3/docs/tooldocs/tools.html
2) If your java source code editor can support non-ascii chars, just type the non-ascii and save it as native encoding. When you compile the code you should use -encoding option to correctly compile the native encoded file.
(print out non ascii chars)
===========================
Java uses "unicode" internally. When a char is printed out from the jvm, the char is converted to the underlaying platform's default enclloding. There are only few java methodes that can override this default behavior. One of them is OutputStreamWriter(OutputStream out, String encode) in jdk1.3.0. You can print out data as the encoding you passed. Since you are printing out to xml, "utf-8" would be ideal.
thanks,
baechul

Similar Messages

  • How Aperture encodes non-ascii chars

    It looks like Aperture uses a way of encode chars as UTF that seem to be bit unusual, many application (especially web apps) expects another way of encoding Unicode chars. The end result is that non-ascii chars comes out really strange.
    When I use applescript to read the IPTC info I need to do something like this before using the data:
    set c_title to normalize unicode p_title without decomposition
    Is there some way of telling Aperture to do this automatically when exporting photos?
    (sorry about the bad use of Unicode terminology but I don't know the area very well)

    I've spent quite a bit of time on this topic - I'm the author of Phoshare http://code.google.com/p/phoshare/, an open-source tool to export images and metadata from iPhoto and Aperture. Storing non-ASCII characters in image metadata is a messy business. If you want to get a taste of it, have a look at the Exiftool FAQ at http://www.sno.phy.queensu.ca/~phil/exiftool/faq.html#Q10 . A quote: "Most textual information in EXIF is stored in ASCII format, ... However *it is not uncommon for applications to write UTF‑8 or other encodings where ASCII is expected*". This leads to all sorts of problems, because the reader will have to make assumptions about the encoding used by the writer.
    In the case of Aperture, I have found that it writes metadata encoded in a way consistent with what most other applications and on-line services expect. Most of the encoding problems I've debugged where caused by bad input data. E.g. the characters were encoded improperly to begin with, but in a way that they still display as expected in some places (like Aperture). Can you try erasing some of the meta data in Aperture, and retype them from scratch (e.g. not copy-paste, which would paste the same stuff right back). Also make sure that you force-updated the preview images, so that the new meta data get written into the files.

  • XML parser fails to convert html encoded text nodes

    Under the strain of large documents this defect rears its ugly head more often. While parsing a text node containing html encoded chars i.e. < > &; etc...
    The parser will seemingly forget to change the chars at random, 99.9% of the time everything is ok and the proper conversions take place:
    < -> &#60;
    > -> >
    &; -> &#38;
    Once an error occurs it is reproducible until the text node is changed ( values and/or order ) then it is a crapshoot again.
    These tests were done using the default UTF-8 encoding, here is the exception thrown by the parser along with a portion of the text node before and after the first parsing.
    Let me be clear, the parser actually succeeds the first time but the transformation of the HTML encoded pieces possibly fails. It is on the parsing of the text node value as its own document that the parser fails.
    Error 0 : Error parsing XML string! Line :: 1, Column :: 65674
    Error 1 : End tag does not match start tag 'Project'.
    End tag does not match start tag 'Project'.
    at oracle/xml/parser/v2/XMLError.flushErrors (XMLError.java:233)
    at oracle/xml/parser/v2/NonValidatingParser.parseDocument (NonValidatingParser.java:248)
    at oracle/xml/parser/v2/XMLParser.parse (XMLParser.java:117)
    at pacificedge/xml/XMLUtilities.loadParserFromString (XMLUtilities.java:104)
    Preprocessing ::
    <Project stuff0="0" stuff1="0" stuff2="0" stuff3="1" stuff4="100167" stuff5="100213">
    <StuffA>100213</StuffA>
    <Name>I am a Name</Name>
    <StartDate>1998-08-10</StartDate>
    <FinishDate>2000-06-30</FinishDate>
    <Path>Folder1\Folder2</Path>
    </Project>
    Post processing:
    <Project stuff0="0" stuff1="0" stuff2="0" stuff3="1" stuff4="100167" stuff5="100213">
    <StuffA>100213</StuffA>
    <Name>I am a Name</Name>
    <StartDate>1998-08-10</StartDate> <-- Error is raised here when the value of the text node is used as an xml document
    <FinishDate>2000-06-30</FinishDate>
    <Path>Folder1\Folder2</Path>
    </Project>
    Please investigate this. It is a chronic problem for us and possibly many others.
    null

    Sorry for the encoding issues in the message before here are the pertinent pieces hope this shows up correctly.
    &;lt; -> &;#60;
    &;gt; -> >
    &;amp; -> &;#38;
    Preprocessing ::
    &;lt;Project stuff0="0" stuff1="0" stuff2="0" stuff3="1" stuff4="100167" stuff5="100213"&;gt;
    &;lt;StuffA&;gt;100213&;lt;/StuffA&;gt;
    &;lt;Name&;gt;I am a Name&;lt;/Name&;gt;
    &;lt;StartDate&;gt;1998-08-10&;lt;/StartDate&;gt;
    &;lt;FinishDate&;gt;2000-06-30&;lt;/FinishDate&;gt;
    &;lt;Path&;gt;Folder1\Folder2&;lt;/Path&;gt;
    &;lt;/Project&;gt;
    Post processing:
    <Project stuff0="0" stuff1="0" stuff2="0" stuff3="1" stuff4="100167" stuff5="100213">
    <StuffA>100213</StuffA>
    <Name>I am a Name</Name>
    &;lt;StartDate>1998-08-10</StartDate> <-- Error is raised here when the value of the text node is used as an xml document
    <FinishDate>2000-06-30</FinishDate>
    <Path>Folder1\Folder2</Path>
    </Project>
    null

  • Detect encoding type from server?

    We are writing an RFC server using the JCO API and we started with code similar to example5.  However, we need to support unicode, so we are using the addInfo method that includes specifying the byte length.  The number of bytes can be calculated, in most cases, by multiplying the char length by the encoding char byte length.  ie. a field that is 10 chars in length, would be 20 bytes in length in a UTF-16 system.  But we need to know if our customer's SAP system supports unicode.  Is it possible from the JCO.server object to know the encoding type of the SAP system?  Or is there another object I can use other than the JCO.client object?
    We only need this info for registering our functions with the gateway.  We figured we could get around not knowing the encoding type by using JCO to find out the structure of a table and using that info to set up the function objects.  I know I can create a JCO.client object, connect to the gateway and query the repository for the structure of a table using getStructureDefinition, but is it possible to do this without a client object?  We are figuring our customers will not like our server requiring a client connection, so we are trying to avoid obtaining this information that way, but we are not sure how to get it any other way.
    Also, it is our understanding that either the customers SAP system will be unicode enabled or it won't be.  And if it is unicode enabled, the field lengths expected in addInfo would be UTF-16 lengths - ie. 2 bytes per char.  Is this assumption correct?  Or should we be supporting other encodings like UTF-8 where our calculations noted above would not work?
    Thanks

    Hi Karl,
    try to turn of the proxy settings (No proxy)
    in the preferences of Java Web Start.
    CU,
    Mathias

  • Unable to encode CAPWAP Control Address

    Hi All:
    My WLC already firmware already update to latest version 6.0 and the management ip and ap manager ip in the same subnet, DNS record already have the CISCO-LWAPP-CONTROLLER and CISCO-CAPWAP-CONTROLLER A record.But Some lightweight AP cannot join the WLC and the error message in WLC as below :
    debug capwap*Aug 11 20:01:01.289: Join resp: Unable to encode CAPWAP Control IPV4 Address
    *Aug 11 20:01:01.289: 00:21:d8:44:29:b0 Failed to encode Join response to 172.16
    .73.54:29282
    *Aug 11 20:01:01.290: 00:21:d8:44:29:b0 Config Response Failure: Unable to send
    Join response to 172.16.73.54:29282
    The Error code is :
    %CAPWAP-3-ENCODE_ERR
    %CAPWAP-3-DECODE_ERR
    Any one can tell me what's happen by these log from WLC ?

    Error Message %CAPWAP-3-ENCODE_ERR: Failed to encode [chars] to AP
    [hex]:[hex]:[hex]:[hex]:[hex]:[hex]
    Explanation Due to an internal error, a CAPWAP message could not be transmitted.

  • Cp855 encoding

    I have Oracle 8.0 database and following situation: Only one column in a table contains cp855 encoded chars. I need to read that column in my selects. When I use select statement i get meaningless results. The database should not be changed in any way. May I have your advise please!
    PS
    I'm new guy here. Please have a patience if this is something trivial or already solved.

    It's me again. I want to describe my solution of this problem. First of all I tried to use translate function but without meaningfull results. Not to mention bulky sintax of this function. I'm C# developer so finally I tried to solve this problem in C#. After I have found some table describing mapping of characters in cp899 codepage it seemed it would be trivial to solve this problem. Problem arises when I noticed that mentioned table contains only mappings for upper case letters. I have slowly identified all the needed letters (Numerous Debugging sessions). Now I have class library which translates cp899 to cyrillic or latin unicode form. The only problem lies in fact that creators of cp899 have used char 45 for Cyrillic letter G, but char 45 is also - (dash). So i have results with - (dash) translated to Cyrillic G. Greetings

  • Convert utf8 char in a NSString

    Hi to all! I recieve from my server a XML file. I use NSXMLParser to retrieve attributes and values. The problem is this: i've many utf8 encoded char in many attributes, and i recieve them in NSStrings.
    //in - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict DELEGATE
    NSString *myAttribute = [[NSString alloc] initWithString:[attributeDict valueForKey:@"attribute"]];
    The NSString at key "attribute" can contain UTF8 char as ò and similar.
    How can i decode them to obtain a NSString with ò instead of ò and so on?

    I understood that you helped me, I will need to use
    parseInt to convert the string to number...No.
    Assuming you've got the "15:00" part, say in a String called timeStr, you'd just pass that to dateFormat.parse(timeStr)
    but I
    need to know where in the String are my numbers...
    isn't it? How may I do this? Well, that depends.
    What's your logic for finding it manually? Is it the first occurrence of any numerical digit in the string? Is it at a known, fixed character index? Some other logic?

  • What kind of encoding is this?

    I have tried to url-encode some odd characters like ���� and so on. They are getting the format like %A3 or %A4%C3 and so on.
    But somehow in a later step they look like �� �� ��
    What kind of encoding is this?

    I am not sure how relevant this is anymore, since you are worried about the log files, while this is all about the JSP display. I used this code as a test case:
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%
      //This block of code is used to simulate the beginning of the app.  When there is no
      //characters requested, it generates a new URL, encodes in UTF-8 and redirects the page
      String chars = request.getParameter("characters");
      if (chars == null) {
           String url = "http://localhost:8080/WebTests/SpecialCharTester.jsp?characters=";
           chars = "����";
           url = url+java.net.URLEncoder.encode(chars,"UTF-8");
           System.out.println(url);
           response.sendRedirect(url);
    %>
    <! DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Special Character Tester</title>
      </head>
      <body>
        <!--  Display the incoming, decoded characters -->
        <h2>Characters: ${param.characters}</h2>
        <!--  Make a test that submits characters to this page to test outward-encoding -->
        <form action="SpecialCharTester.jsp">
          <input type="text" name="characters"/>
          <input type="submit"/>
        </form>
      </body>
    </html>And it seems to work both when I manually do a URLEncoder.encode(chars, "UTF-8") to make a request and when I fill out the form. I did not change the server.xml's HTTP Connector, or any web.xml setting. Actually, doing so caused problems.
    The key change appears to be the content-type in the page encoding. Change that and the page breaks, change the pageEncoding piece or the meta tag and it still works. The encoding markup pushed by the form and the URLEncoder operation are the same values.
    I did have to make sure IE7 had Encoding > Auto Detect set (for some reason it had Encoding fixed at Western Windows). FF3 had no problems as it defaults to auto-detect.
    This has nothing to do with how you save to the logs though... just how you display on screen.

  • How to get the number of lines of a FileReader

    I need to calculate the number of lines of a FileReader object. How can I do that ?

    I wrote the following some while ago. It assumes that a line is terminated by '\n' but it should be easy to adapt.
    import java.io.*;
    public class LineCounter
        public static int countLines(File file, String encoding) throws IOException
            int lineCount = 0;
            Reader reader = new InputStreamReader(new FileInputStream(file), encoding);
            char[] buffer = new char[4096];
            for (int charsRead = 0; (charsRead = reader.read(buffer)) >= 0;)
                for (int charIndex = 0; charIndex < charsRead ; charIndex++)
                    if (buffer[charIndex] == '\n')
                        lineCount++;
            reader.close();
            return lineCount;
        public static void main(String[] args)
            try
                File file = new File("/home/sabre/work/dev/maps/EUROPE.RIV");
                long startTime = System.currentTimeMillis();
                int lineCount = countLines(file, "UTF-8");
                double time =  (System.currentTimeMillis() - startTime) / 1000.0;
                System.out.println("File size = " + file.length() + " contains " + lineCount + " lines taking " + time);
            catch (Exception e)
                e.printStackTrace();
    }

  • How to set attributes in new connection url request

    Hi, I'm an italian programer and I'm sorry for my english. Using the follow java code, I include an jsp page in to other jsp page. I use struts framework too. The problem is that the page includes do not has on the request object the same attributes of the calling page. for example the page authentication.jsp page has on self request object the attributes "org.apache.struts.message", but the page includes drop this attribute on the request object. In other words the page includes does not inherit the request attributes of the calling page.
    How to do to resolve this problem.
    Many thanks to your availability to my problem.
    By
    Antonio (Italy)
    String urlString = null;
    URL url = null;
    ServletContext sctx = null;
    HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
    try {
    if(strContextRoot==null) strContextRoot = "";
    // Set up a URLConnection to read the requested resource
    Map params = request.getParameterMap();
    params = updateParametersMap(newParam,params);
    if (!strContextRoot.equals(""))
    sctx = pageContext.getServletContext().getContext(strContextRoot);
    else
    sctx = pageContext.getServletContext();
    urlString = NewcomputeURL_old(strContextRoot,pageContext, forward, href, page, params, anchor, false);
    url = new URL(RequestUtils.requestURL(request), urlString);
    } catch (MalformedURLException e) {
    RequestUtils.saveException(pageContext, e);
    throw new JspException(messages.getMessage("ServletInclude: include.url", e.toString()));
    URLConnection conn = null;
    try {
    // Set up the basic connection
    conn = url.openConnection();
    //pageContext.
    conn.setUseCaches(true);
    conn.setRequestProperty("method","POST");
    conn.setAllowUserInteraction(true);
    conn.setDoInput(true);
    conn.setDoOutput(true);
    if ((conn instanceof HttpURLConnection)
    && urlString.startsWith(strContextRoot)
    && (request.getRequestedSessionId() != null)
    && request.isRequestedSessionIdFromCookie()) {
    StringBuffer sb = new StringBuffer("JSESSIONID=");
    sb.append(request.getRequestedSessionId());
    conn.setRequestProperty("Cookie", sb.toString());
    // Connect to the requested resource
    conn.connect();
    } catch (Exception e) {
    RequestUtils.saveException(pageContext, e);
    throw new JspException(
    messages.getMessage("ServletInclude: include.open", url.toString(), e.toString()));
    // Copy the contents of this URL
    StringBuffer sb = new StringBuffer();
    try {
    BufferedInputStream is = new BufferedInputStream(conn.getInputStream());
    InputStreamReader in = new InputStreamReader(is); // FIXME - encoding
    char buffer[] = new char[BUFFER_SIZE];
    int n = 0;
    while (true) {
    n = in.read(buffer);
    if (n < 1) break;
    sb.append(buffer, 0, n);
    in.close();
    out.write(sb.toString());
    } catch (Exception e) {
    RequestUtils.saveException(pageContext, e);
    throw new JspException(
    messages.getMessage("ServletInclude: include.read", url.toString(), e.toString()));

    Please have a look at this.
    What you are doing is creating a new http request using a url connection!! That's why the request attributes does not show up, it's not the same request!
    If you want to include the response of another resource, use a request dispatcher to include it. Eg.
    // in servlet
    request.getRequestDispatcher("/index.jsp").include(request, response);
    // or in jsp
    <jsp:include page="/index.jsp" />

  • Little problem with Strings.

              I have an little problem with Strings, i make one comparision like this.
              String nombre="Javier";
              if( nombre.equalsIgnoreCase(output.getStringValue("CN_NOMBRESf",null)) )
              Wich output.getStringValue("CN_NOMBRESf",null) is "Javier" too, because I display
              this before and are equals.
              What I do wrong?.
              

    You are actually making your users key in things like
    "\026"? Not very user-friendly, I would say. But
    assuming that is the best way for you to get your
    input, or if it's just you doing the input, the way to
    change that 4-character string into the single
    character that Java represents by '\026', you would
    use a bit of code like this:char encoded =
    (char)Integer.parseInt(substring(inputString, 1),
    16);
    DrClap has the right idea, except '\026' is octal, not hex. So change the radix from 16 to 8. Unicode is usually represented like '\u002A'. So it looks like you want:String s = "\\077";
    System.out.println((char)Integer.parseInt(s.substring(1), 8));Now all you have to do is parse through the String and replace them, which I think shouldn't be too hard for you now :)

  • Strange problem (Korean language in jsp page) - Urgent Please

    Dear friends,
    I have a strange problem.
    in my jsp page, i have to add hangul words also using korean language. (hangul).
    After adding hangul language in jsp page, in browser, it is displaying in some other format.
    how can i display hangul script on browser using a jsp page.
    please help me.
    Thanks in advance
    Yours
    Rajesh

    Dear noahlau,
    Thank you very much.
    I got the solution for this problem
    I used korean encoding char set like this in my jsp program.
    <%@page contentType="text/html;charset=ks_c_5601-1987"%>
    Now it is working fine.
    Thanks once again.
    if you need any help please ask me.
    Yours
    Rajesh

  • Logical error 2nd Edition... :~(

    here is the 2nd edition of the program.
    it runs wired, i can't exactly tell how, but the way it does just like lost-control.
    copy it and give it a try see if you have any idea what's going on.
    p.s. all called methods are sticked after the main program.
    class DecodeDriver
         public static void main(String[] args)
              char keyin;
              do
                   sop("**********************************************");
                   sop("**********************************************");
                   sop("**            M A I N   M E N U             **");
                   sop("**        ~~~~~~~~~~~~~~~~~~~~~~~~          **");
                   sop("** ======================================== **");
                   sop("** M) Morse Code                            **");
                   sop("** C) Caesar Cipher                         **");
                   sop("** V) Vignere Cipher                        **");
                   sop("** P) Playfair Cipher                       **");
                   sop("** ---------------------------------------- **");
                   sop("** X) Exit Program                          **");
                   sop("**                                          **");
                   sop("**********************************************");
                   sop("**********************************************");
                   sop(" ");
                   sop("Please select an encoding scheme: ");
                   keyin = SavitchIn.readNonwhiteChar();
                   switch(keyin)
                   case'M':
                   case'm': Morse();
                        break;
                        case'C':
                   case'c': Caesar();
                        break;
                        case'V':
                   case'v': Vignere();
                        break;
                        case'P':
                   case'p': Playfair();
                        break;
                        case'X':
                        case'x': sop("Thanks for using! Bye!");
                        break;
                        default: sop("Invalid Key Entered. Please select one from the menu.");
                        break;
                   } //switch
              } // do
              while(keyin != 'X' && keyin != 'x');
              System.exit(0);
         } // main
              public static void Morse()
                   char subKeyin;
                   sop("**********************************************");
                   sop("**********************************************");
                   sop("**            Morse Code Menu               **");
                   sop("**        ~~~~~~~~~~~~~~~~~~~~~~~~          **");
                   sop("** ======================================== **");
                   sop("** E) Encode                                **");
                   sop("** D) Decode                                **");
                   sop("** ---------------------------------------- **");
                   sop("** X) Return to Main Program                **");
                   sop("**                                          **");
                   sop("**********************************************");
                   sop("**********************************************");
                   sop(" ");
                   sop("Please select to encoding / decoding: ");
                   subKeyin = SavitchIn.readNonwhiteChar();
                   switch(subKeyin)
                        case'E':
                        case'e': MorseCode.encode();
                        break;
                        case'D':
                        case'd': MorseCode.decode();
                        break;
                        case'X':
                        case'x': sop("Returning to main menu...");
                                   break;
                        default: sop("Invalid Key Entered. Please select one from the menu.");
                                       break;
                   } // switch
              } //Morse
              private static void Caesar()
                   char subKeyin = SavitchIn.readNonwhiteChar();
                   sop("**********************************************");
                   sop("**********************************************");
                   sop("**           Caesar Cipher Menu             **");
                   sop("**        ~~~~~~~~~~~~~~~~~~~~~~~~          **");
                   sop("** ======================================== **");
                   sop("** E) Encode                                **");
                   sop("** D) Decode                                **");
                   sop("** ---------------------------------------- **");
                   sop("** X) Return to Main Program                **");
                   sop("**                                          **");
                   sop("**********************************************");
                   sop("**********************************************");
                   sop(" ");
                   sop("Please select to encoding / decoding: ");
                   switch(subKeyin)
                        case'E':
                        case'e': CaesarCipher.encode();
                        case'D':
                        case'd': CaesarCipher.decode();
                        case'X':
                        case'x': sop("Returning to main menu...");
                                   break;
                        default: sop("Invalid Key Entered. Please select one from the menu.");
                   } // switch
              } //CaesarCipher
              private static void Vignere()
                   char subKeyin = SavitchIn.readNonwhiteChar();
                   sop("**********************************************");
                   sop("**********************************************");
                   sop("**           Vignere Cipher Menu             **");
                   sop("**        ~~~~~~~~~~~~~~~~~~~~~~~~          **");
                   sop("** ======================================== **");
                   sop("** E) Encode                                **");
                   sop("** D) Decode                                **");
                   sop("** ---------------------------------------- **");
                   sop("** X) Return to Main Program                **");
                   sop("**                                          **");
                   sop("**********************************************");
                   sop("**********************************************");
                   sop(" ");
                   sop("Please select to encoding / decoding: ");
                   switch(subKeyin)
                        case'E':
                        case'e': VignereCipher.encode();
                        case'D':
                        case'd': VignereCipher.decode();
                        case'X':
                        case'x': sop("Returning to main menu...");
                                   break;
                        default: sop("Invalid Key Entered. Please select one from the menu.");
                   } // switch
              } //VignereCipher          
              private static void Playfair()
                   char subKeyin = SavitchIn.readNonwhiteChar();
                   sop("**********************************************");
                   sop("**********************************************");
                   sop("**          Playfair Cipher Menu            **");
                   sop("**        ~~~~~~~~~~~~~~~~~~~~~~~~          **");
                   sop("** ======================================== **");
                   sop("** E) Encode                                **");
                   sop("** D) Decode                                **");
                   sop("** ---------------------------------------- **");
                   sop("** X) Return to Main Program                **");
                   sop("**                                          **");
                   sop("**********************************************");
                   sop("**********************************************");
                   sop(" ");
                   sop("Please select to encoding / decoding: ");
                   switch(subKeyin)
                        case'E':
                        case'e': PlayfairCipher.encode();
                        case'D':
                        case'd': PlayfairCipher.decode();
                        case'X':
                        case'x': sop("Returning to main menu...");
                                   break;
                        default: sop("Invalid Key Entered. Please select one from the menu.");
                   } // switch
              } //PlayfairCipher     
              private static void sop(String newString)
                   System.out.println(newString);
              } // sop
    } //class
    (part of)the SavitchIn input stuff:
        public static char readNonwhiteChar( )
          char next;
          next = readChar( );
          while (Character.isWhitespace(next))
              next = readChar( );
          return next;
         The following methods are not used in the text, except
         for a brief reference in Chapter 2. No program code uses
         them. However, some programmers may want to use them.
         Precondition: The next input in the stream consists of
         an int value, possibly preceded by whitespace, but
         definitely followed by whitespace.
         Action: Reads the first string of nonwhitespace characters
         and returns the int value it represents. Discards the
         first whitespace character after the word. The next read
         takes place immediately after the discarded whitespace.
         In particular, if the word is at the end of a line, the
         next read will take place starting on the next line.
         If the next word does not represent an int value,
         a NumberFormatException is thrown.
    MorseCode.java - for debugin' propose.
    class MorseCode
       public MorseCode()
          sop("unfinished - const.");
         }//const.
         public static void encode()
              sop("unfinished - encode");
              char newchar;
              newchar = SavitchIn.readChar();
              System.out.println(newchar);
         public static void decode()
              sop("unfinished - decode");
         private static void sop(String newString)
              System.out.println(newString);
         } // sop
    }//class

    aside from the missing breaks?
    encode OR decode
    case'E':
    case'e': CaesarCipher.encode();
    break;
    case'D':
    case'd': CaesarCipher.decode();
    break;looks better this time?
    class DecodeDriver
         public static void main(String[] args)
              char keyin;
              do
                   sop("**********************************************");
                   sop("**********************************************");
                   sop("**            M A I N   M E N U             **");
                   sop("**        ~~~~~~~~~~~~~~~~~~~~~~~~          **");
                   sop("** ======================================== **");
                   sop("** M) Morse Code                            **");
                   sop("** C) Caesar Cipher                         **");
                   sop("** V) Vignere Cipher                        **");
                   sop("** P) Playfair Cipher                       **");
                   sop("** ---------------------------------------- **");
                   sop("** X) Exit Program                          **");
                   sop("**                                          **");
                   sop("**********************************************");
                   sop("**********************************************");
                   sop(" ");
                   sop("Please select an encoding scheme: ");
                   keyin = SavitchIn.readNonwhiteChar();
                   switch(keyin)
                   case'M':
                   case'm': Morse();
                        break;
                   case'C':
                   case'c': Caesar();
                        break;
                   case'V':
                   case'v': Vignere();
                        break;
                   case'P':
                   case'p': Playfair();
                        break;
                   case'X':
                   case'x': sop("Thanks for using! Bye!");
                        break;
                   default: sop("Invalid Key Entered. Please select one from the menu.");
                        break;
                   } //switch
              } // do
              while(keyin != 'X' && keyin != 'x');
              System.exit(0);
         } // main
              public static void Morse()
                   char subKeyin;
                   sop("**********************************************");
                   sop("**********************************************");
                   sop("**            Morse Code Menu               **");
                   sop("**        ~~~~~~~~~~~~~~~~~~~~~~~~          **");
                   sop("** ======================================== **");
                   sop("** E) Encode                                **");
                   sop("** D) Decode                                **");
                   sop("** ---------------------------------------- **");
                   sop("** X) Return to Main Program                **");
                   sop("**                                          **");
                   sop("**********************************************");
                   sop("**********************************************");
                   sop(" ");
                   sop("Please select to encoding / decoding: ");
                   subKeyin = SavitchIn.readNonwhiteChar();
                   switch(subKeyin)
                        case'E':
                        case'e': MorseCode.encode();
                        break;
                        case'D':
                        case'd': MorseCode.decode();
                        break;
                        case'X':
                        case'x': sop("Returning to main menu...");
                        break;
                        default: sop("Invalid Key Entered. Please select one from the menu.");
                        break;
                   } // switch
              } //Morse
              private static void Caesar()
                   char subKeyin;
                   sop("**********************************************");
                   sop("**********************************************");
                   sop("**           Caesar Cipher Menu             **");
                   sop("**        ~~~~~~~~~~~~~~~~~~~~~~~~          **");
                   sop("** ======================================== **");
                   sop("** E) Encode                                **");
                   sop("** D) Decode                                **");
                   sop("** ---------------------------------------- **");
                   sop("** X) Return to Main Program                **");
                   sop("**                                          **");
                   sop("**********************************************");
                   sop("**********************************************");
                   sop(" ");
                   sop("Please select to encoding / decoding: ");
                   subKeyin =  SavitchIn.readNonwhiteChar();
                   switch(subKeyin)
                        case'E':
                        case'e': CaesarCipher.encode();
                        break;
                        case'D':
                        case'd': CaesarCipher.decode();
                        break;
                        case'X':
                        case'x': sop("Returning to main menu...");
                                   break;
                        default: sop("Invalid Key Entered. Please select one from the menu.");
                                       break;
                   } // switch
              } //CaesarCipher
              private static void Vignere()
                   char subKeyin;
                   sop("**********************************************");
                   sop("**********************************************");
                   sop("**           Vignere Cipher Menu             **");
                   sop("**        ~~~~~~~~~~~~~~~~~~~~~~~~          **");
                   sop("** ======================================== **");
                   sop("** E) Encode                                **");
                   sop("** D) Decode                                **");
                   sop("** ---------------------------------------- **");
                   sop("** X) Return to Main Program                **");
                   sop("**                                          **");
                   sop("**********************************************");
                   sop("**********************************************");
                   sop(" ");
                   sop("Please select to encoding / decoding: ");
                   subKeyin  = SavitchIn.readNonwhiteChar();
                   switch(subKeyin)
                        case'E':
                        case'e': VignereCipher.encode();
                        break;
                        case'D':
                        case'd': VignereCipher.decode();
                        break;
                        case'X':
                        case'x': sop("Returning to main menu...");
                        break;
                        default: sop("Invalid Key Entered. Please select one from the menu.");
                        break;
                   } // switch
              } //VignereCipher          
              private static void Playfair()
                   char subKeyin;
                   sop("**********************************************");
                   sop("**********************************************");
                   sop("**          Playfair Cipher Menu            **");
                   sop("**        ~~~~~~~~~~~~~~~~~~~~~~~~          **");
                   sop("** ======================================== **");
                   sop("** E) Encode                                **");
                   sop("** D) Decode                                **");
                   sop("** ---------------------------------------- **");
                   sop("** X) Return to Main Program                **");
                   sop("**                                          **");
                   sop("**********************************************");
                   sop("**********************************************");
                   sop(" ");
                   sop("Please select to encoding / decoding: ");
                   subKeyin  = SavitchIn.readNonwhiteChar();
                   switch(subKeyin)
                        case'E':
                        case'e': PlayfairCipher.encode();
                        break;
                        case'D':
                        case'd': PlayfairCipher.decode();
                        break;
                        case'X':
                        case'x': sop("Returning to main menu...");
                        break;
                        default: sop("Invalid Key Entered. Please select one from the menu.");
                        break;
                   } // switch
              } //PlayfairCipher     
              private static void sop(String newString)
                   System.out.println(newString);
              } // sop
    } //class

  • JTextArea Copy to System Clipboard

    I have written an applet that generates RSA type 1 key pairs. The application version works correctly and outputs to files. The online applet version works but instead of writing to files I write the key data to the JTextArea hoping that it could be copied and pasted into files by the user.
    The catch is that the private key (encrypted) data does not copy correctly when you use CTRL-C and then paste to Notepad. I think it has something to do with the encoded chars causing the copy to malfunction.
    Take a look at the applet and the source code and let me know if you have any ideas about what might work. The main class is KeyJenApplet.java. I have tried JTextPane, JTextField and old TextArea. The old TextArea had popupmenu copy available but it was weird in that it didn't even populate the TextArea entirely when the applet was run. It populated the data much like the copy by only doing a portion of it.
    http://www.cheersdata.com/keyjenapplet.html

    Thanks for the responses.
    I believe Windows does have a scripting language, which may well be the way to go, although so far I'm unfamiliar enough with it to be unsure.
    As for the threads idea, unfortunately, I'm not programming the other application, so that won't work in this case.
    Using java.awt.Robot is a good idea, and it may be the easiest, except that as you point out, the text in the clipboard would have to be broken down into keystrokes, which seems rather awkward and slow.
    The other issue is how to make sure that another app becomes the active window. The Robot can presumably do it by sending keystrokes (like Alt+Tab in Windows), which require that it be the most recently active window--not always a safe assumption. Might there be a safer way?
    Thanks,
    Gregory

  • Non-Blocking Writing and Strings

    Hello.
    My question is simple, is it possible to write strings using a non-blocking method?
    I was praying that there was a method in the NIO API that allowed me to, yet i can't find one.
    If the answer is blatantly obvious please forgive me, i'm tired and hungry :)
    Thank you for looking at this topic

    Strings are written to files or sockets using a certain encoding. I usually use UTF-8, but your application might be different.
    1. Get the SocketChannel from your non-blocking socket.
    SocketChannel ch = mySocket.getChannel(); // mySocket is java.net.Socket2. Make a CharBuffer out of the String you want to send.
    CharBuffer chars = CharBuffer.wrap(myString); // myString is your data3. Encode it so it becomes a ByteBuffer. I'll use the [UTF-8|http://www.joelonsoftware.com/articles/Unicode.html] Charset here.
    ByteBuffer bytes = Charset.forName("UTF-8").encode(chars);4. Use the write(ByteBuffer) method in the SocketChannel from 1.
    ch.write(bytes);Import declarations:
    import java.nio.channels.SocketChannel;
    import java.nio.CharBuffer;
    import java.nio.ByteBuffer;
    import java.nio.charset.Charset;s

Maybe you are looking for