Converting String to unicode encoded string

Hi,
I would like to convert non-ascii characters in a String or the whole string to unicode encoded character.
For example:
If i have some japanese character, I would like it to be converted to /uxxxx
How can i do this? I don't want the exact character, as I am able to get that using getBytes("encoding format"). All i want is code point representation of the non ascii unicode characters.
Any help to do this will be appreciated.
Thanks in advance.

I tried to do what that but I am not sure whether that is right or not.
String inputStr = "some non ascii string";
char[] charArray = inputStr.toCharArray();
int code;
StringBuffer sb = new StringBuffer();
for(int i = 0; i < charArray.length; i++)
code = (int) charArray;
String hexString = Integer.toHexString( code );
sb.append(hexString);
System.out.println("Code point is "+sb.toString());
My above code does not work as expected. Could you please tell me where i am goofing?
Thanks!

Similar Messages

  • Converting Base64 encoded String to String object

    Hi,
    Description:
    I have a Base64 encoded string and I am using this API for it,
    [ http://ws.apache.org/axis/java/apiDocs/org/apache/axis/encoding/Base64.html]
    I am simply trying to convert it to a String object.
    Problem:
    When I try and write the String, ( which is xml ) as a XMLType to a oracle 9i database I am getting a "Cannot map Unicode to Oracle character." The root problem is because of the conversion of the base64 encoded string to a String object. I noticed that some weird square characters show up at the start of the string after i convert it. It seems like I am not properly converting to a String object. If i change the value of the variable on the fly and delete these little characters at the start, I don't get the uni code error. Just looking for a second thought on this.
    Code: Converting Base64 Encoded String to String object
    public String decodeToString( String base64String )
        byte[] decodedByteArray = Base64.decode( base64String );
        String decodedString = new String( decodedByteArray, "UTF-8");
    }Any suggestions?

    To answer bigdaddy's question and clairfy a bit more:
    Constraints:
    1. Using a integrated 3rd party software that expects a Base64 encoded String and sends back a encoded base64 String.
    2. Using JSF
    3. Oracle 10g database and storing in a XMLType column.
    Steps in process.
    1. I submit my base64 encoded String to this 3rd party software.
    2. The tool takes the encoded string and renders a output that works correctly. The XML can be modified dynamically using this tool.
    3. I have a button that is binded to my jsf backing bean. When that button is clicked, the 3rd party tool sets a backing bean string value with the Base64 String representing the updated XML.
    4. On the backend in my jsf backing bean, i attempt to decode it to string value to store in the oracle database as a XML type. Upon converting the byte[] array to a String, i get this conversion issue.
    Possibly what is happen is that the tool is sending me a different encoding that is not UTF-8. I thought maybe there was a better way of doing the decoding that i wasn't looking at. I will proceed down that path and look at the possibility that the tool is sending back a different encoding then what it should. I was just looking for input on doing the byte[] decoding.
    Thanks for the input though.
    Edited by: haju on Apr 9, 2009 8:41 AM

  • String unicode - Encoding used ?

    Hi,
    Can some one please provide me information on how is it working?
    1) String uses unicode. Does it just stores unicode equivaluent or it
    uses any encoding for storing the unicode value. I have got various
    responses ranging from UTF-8 , UTF-16 to default encoding of the system.
    2) If it doesn't uses default encoding of the system then please let me know how the following works
    String x = "Some japanese character" // read from file using default encoding
    Runtime.exec("echo" + x "> file") ; //
    Who does the conversion from String 's encoding to platforms default encoding?
    If the string doesn't uses encoding and stores it as unicode equivaluent , then also who does the converstion from unicode equivalent to platform's local encoding

    http://java.sun.com/docs/books/tutorial/i18n/text/index.html

  • How to convert a base64 encoded string to binary?

    Hi, gurus,
    I want to convert a base64 encoded string (a image  which is read from a xml file)
    into a normal binary string and then upload to archive link.
    could you pls give me some hints on that?
    br.
    jun

    thank you for your quick reply!
    my real requirement is to extract an image(it 's said it's encoded using base64?) from a xml file and upload it sap archive linke,
    following is the xml content, does that mean i need to convert all the chars in the
    <mime_content> pair to your fm, that will be convert to binary string?
    <MIME_CONTENT xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/" href="" xfa:contentType="image/jpg"
    >/9j/4AAQSkZJRgABAAEAYABgAAD//gAfTEVBRCBUZWNobm9sb2dpZXMgSW5jLiBWMS4wMQD/2wCE
    AAgFBgcGBQgHBgcJCAgJDBQNDAsLDBgREg4UHRkeHhwZHBsgJC4nICIrIhscKDYoKy8xMzQzHyY4
    PDgyPC4yMzEBCAkJDAoMFw0NFzEhHCExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTEx
    MTExMTExMTExMTExMTExMf/EAaIAAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKCwEAAwEBAQEB
    AQEBAQAAAAAAAAECAwQFBgcICQoLEAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEU
    MoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2Rl
    ZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK
    0tPU1dbX2Nna4eLj5OXm5jp6vHy8/T19vf4foRAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYS
    QVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNU
    VVZXWFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5
    usLDxMXGx8jJytLT1NXW19jZ2uLj5OXm5jp6vLz9PX29/j5v/AABEIAFQAUwMBEQACEQEDEQH/
    2gAMAwEAAhEDEQA/APf6ACgAoAy/EWsxaLYGZgHmbiKP+8f8BXBjsbHB0ud79EduCwksVU5VourO
    Gg8X64kxdp0kUn7jRjaPy5/Wvk1neKjK90/Kx9LPK8I42St8zTv/ABjqS2tuYYYI3mjLFtpOPmI4
    59q662eV1CLikrq/4tfocdHKqDnJSbdniKuiMdQhv1GpyefbOcN8gBT3GBUYTO6sai9s7xf4G2
    JyqjKn+5VpL8T0NHV0V0YMrDII6EV9kmpK6PlGnF2YtMQUAFABQAUAcj4s8V3Gm3xsbGNN6qC8jj
    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</MIME_CONTENT
    >

  • There is a question about encode String

    hello
    i find a question when i decode java program at linux(redhat 7.3 Valhalla) and J2SDK 1.4.1_02.
    when i want to encode a String from GB2312 to UTF-16BE, the String used CJK and alpha bet mixed. the String length is error and can not convert success!
    from API documents, the string length when count the CJK character ,2 bytes count to 1,but there is 2! for example ,when i encode a CJK character to a UTF-16BE,when the string length is 1.then in the UTF-16BE should be 1,but there is not 1 but 2!!!:(
    by the way ,when my code run at windows2000,it's right!! no error!
    to everyone:what should i do ? is it a bug in j2sdk1.4.1_02?

    There are multiple 16-bit Unicode encodings, i.e.,
    UTF-16
    UnicodeBigUnmarked
    UnicodeLittleUnmarked
    UnicodeBig
    UnicodeLittle
    with/without BOM (byte order mark).
    Try these at a time, or confirm the unicode encoding used on an OS by the following.
    System.out.println(System.getProperty("sun.io.unicode.encoding"));

  • Encoding from UTF-8 encoded String to Microsoft Project default encode

    Hi Expert ...
    I have a problem with encoding a String from UTF-8 String in order to write a MPX (Microsoft Project) file. I used UTF-8 on my Database encoding, and I want to write a MPX file using MPXJ library, but the result is (?) character. I think it's because I didn't encode yet to Shift JIS (a Microsoft Product default encoding). And after that I try to encode the String with Shift_JIS encoding, but the same result is appeared. I try to looking another way, but there is no result.
    I hope some expert would help me to solve this problem.
    Thank you,
    Alfian B.

    Totally wrong. A String doesn't have an encoding.
    Now if you had an array of bytes, which were encoded using one charset, and you wanted to convert that to an array of bytes encoded using a second charset, you would use code like this:byte[] bytes = // the bytes encoded in UTF-8, let's say
    String s = new String(bytes, "UTF-8"); // make that into a String
    byte[] newbytes = s.getBytes("windows-31j"); // encode the String into windows-31j

  • String to Unicode

    Hi .
    I have a string like "Hello "
    I wantto convert this to unicode sequence like this . "\u65e5\u672c\u8a9e\u6587\u5b57\u5217"
    How can I do it ?

    in jnlp file . for example
    I wantto use the following string as parameter to pass main class .
    <argument>"-<`6%w~l60~}d'i(~f3-^!=="</argument> The parser probably complains about the lowerthan character. You should check the Java Web Start docs for ways to escape such special charaters. Note that "unicode syntax" won't help much, as the '\' already has a special meaning already in JWS (as an escape marker).
    There's most probably something you can do at the XML level (use entities, or whatever XML syntax enables to escape special characters).

  • String to unicode coversion

    plz tell me how do i convert long String in to unicode..........
    i hav string like
    "this is pri"
    i want to convert it into unicode?

    pri wrote:
    can u plz expain me with code?Can you please use a spell checker or something before posting.
    Can you please explain in more detail what it is you are trying to do
    so we can guide you to where in the Java API you can find the answer.

  • Unicode to String Conversion

    Dear all,
    I'm trying to get the String from unicode, previously i'm converting the String to Unicode like below,
    String s = "\\u"+Integer.toHexString(s.charAt(0));
    Which is giving me the same what i appended above even after Conversion using UTF-8.
    If i do String s ="\u30f3"
    It is giving me correct character. But my problem is i'm getting the latter part i.e hexString latter in the run time...through Integer.toHexString..
    i can't add this as a character.. so it is taking as a two different strings..
    How to handle this situation..
    Hope i can find the answer,
    Thanks in advance,
    Srinivas N

    Below is my IOUtils class. In particular, see the loadTextFile method for an example of how to read a UTF file, and the isUTF method to detect if a file is Unicode
    You will not be able to compile this class unless you have my InfoFetcher class. You should be able to find a reference to this class by searching google for "InfoFetcher tjacobs01"
    You are welcome to use and modify this class, but please don't change the package or take credit for it as your own work
    package tjacobs.io;
    import java.awt.Component;
    import java.io.*;
    import java.net.URL;
    import java.net.URLConnection;
    import java.text.MessageFormat;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    import javax.swing.JOptionPane;
    import javax.swing.JTable;
    import javax.swing.table.TableModel;
    import tjacobs.io.InfoFetcher.FetcherListener;
    * IOUtils class
    * This is an important class that I use a lot.<p>
    * has a lot of static utilities. Most should be fairly self-explanatory
    public class IOUtils {
         public static final int DEFAULT_BUFFER_SIZE = (int) Math.pow(2, 20); //1 MByte
         public static final int DEFAULT_WAIT_TIME = 30000;
         public static final boolean ALWAYS_BACKUP = false;
         public static String loadTextFile(File f) throws IOException {
              return loadTextFile(f, isUTF16(f));
         public static String loadTextFile(File f, boolean UTF16) throws IOException {
              BufferedReader br = !UTF16 ?
                        new BufferedReader(new FileReader(f)) :
                        new BufferedReader(
                             new InputStreamReader(new FileInputStream(f),
                                                   "UTF-16"));
              int length = (int) f.length();
              char data[] = new char[!UTF16?(int)length : ((int)length) / 2 - 1];
              int got = 0;
              do {
                   got += br.read(data, got, data.length - got);
              while (got < data.length);
              return new String(data);
         public static InfoFetcher loadData(InputStream in) {
              byte buf[] = new byte[DEFAULT_BUFFER_SIZE]; // 1 MByte
              return loadData(in, buf);
         public static InfoFetcher loadData(InputStream in, byte buf[]) {
              return loadData(in, buf, TimeOut.DEFAULT_WAIT_TIME);
         public static InfoFetcher loadData(InputStream in, byte buf[], int waitTime) {
              return new InfoFetcher(in, buf, waitTime);
         public static InfoFetcher loadData(InputStream in, int initBufLength, int waitTime) {
              return loadData(in, new byte[initBufLength], waitTime);
         public static InfoFetcher loadData(File f) throws FileNotFoundException{
              //if (!f.exists()) throw new FileNotFoundException(f.getAbsolutePath());
              //create the inputstream first so that we can generate the FileNotFoundException right away
              InputStream in = new BufferedInputStream(new FileInputStream(f));
              long len = f.length();
              if (len > Integer.MAX_VALUE) {
                   throw new RuntimeException("File size exceeds maximum size for a byte buffer");
              return loadData(in, (int) len, TimeOut.NO_TIMEOUT);
         public static InfoFetcher loadData(URL url) throws IOException{
              return loadData(url.openConnection());
         public static InfoFetcher loadData(URLConnection conn) throws IOException {
              int size = conn.getContentLength();
              if (size < 0) return loadData(conn.getInputStream(), 2000, DEFAULT_WAIT_TIME);
              return loadData(conn.getInputStream(), size, DEFAULT_WAIT_TIME);
          * Note: There is no guarentee that this method will
          * ever return. For instance, if you call loadAll on
          * an open socket connection it won't return until the
          * socket has closed
         public static String loadAllString(InputStream in) {
              InfoFetcher fetcher = loadData(in);
              fetcher.run();
              return new String(fetcher.buf, 0, fetcher.got);
          * Note: There is no guarentee that this method will
          * ever return. For instance, if you call loadAll on
          * an open socket connection it won't return until the
          * socket has closed
         public static byte[] loadAll(InputStream in) {
              InfoFetcher fetcher = loadData(in);
              return fetcher.readCompletely();
         public static void copyBufs(byte src[], byte target[]) {
              int length = Math.min(src.length, target.length);
              for (int i = 0; i < length; i++) {
                   target[i] = src;
         * Not threaded by default. If you need this to run
         * in a separate, create a new thread or runnable class
         * @param in
         * @param out
         public static void pipe (InputStream in, OutputStream out) {
              pipe (in, out, TimeOut.NO_TIMEOUT);
         * Not threaded by default. If you need this to run
         * in a separate, create a new thread or runnable class
         * @param in
         * @param out
         public static void pipe (InputStream in, final OutputStream out, int timeout) {
              pipe (in, out, timeout, false);
         private static class PipeFetcher implements FetcherListener {
              OutputStream out;
              InputStream in;
              public IOException ex;
              boolean closeWhenDone;
              public PipeFetcher (InputStream in, OutputStream out, boolean closeWhenDone) {
                   this.out = out;
                   this.closeWhenDone = closeWhenDone;
              public void fetchedMore(byte[] buf, int start, int end) {
                   try {
                        out.write(buf, start, end - start);
                   catch (IOException iox) {
                        ex = iox;
                        try {
                             in.close();
                             out.close();
                        catch (IOException iox2) {
                             iox2.printStackTrace();
              public void fetchedAll(byte[] buf) {
                   if (closeWhenDone) {
                        try {
                             out.close();
                        catch (IOException iox) {
                             iox.printStackTrace();
         * Not threaded by default. If you need this to run
         * in a separate, create a new thread or runnable class
         * @param in
         * @param out
         public static IOException pipe (final InputStream in, final OutputStream out, int timeout, final boolean closeWhenDone) {
              InfoFetcher info = new InfoFetcher (in, new byte[DEFAULT_BUFFER_SIZE], timeout);
              PipeFetcher pf = new PipeFetcher(in, out, closeWhenDone);
              info.addFetcherListener(pf);
              info.run();
              return pf.ex;
              info.addInputStreamListener(new InputStreamListener() {
                   public void gotMore(InputStreamEvent ev) {
                        try {
                             out.write(ev.getBytes(), ev.getStart(), ev.getBytesRetrieved() - ev.getStart());
                        catch (IOException iox) {
                             System.err.println ("Pipe closing");
                   public void gotAll(InputStreamEvent ev) {}
              Thread t= new Thread (info);
              t.start();
         public static byte[] expandBuf(byte array[]) {
              return expandBuf(array, array.length * 2);
         public static byte[] expandBuf(byte array[], int newlength) {
              byte newbuf[] = new byte[newlength];
              copyBufs(array, newbuf);
              return newbuf;
         public static byte[] trimBuf(byte[] array, int size) {
              byte[] newbuf = new byte[size];
              for (int i = 0; i < size; i++) {
                   newbuf[i] = array[i];
              return newbuf;
         * @see getFileOutputStream(File, boolean)
         public static OutputStream getFileOutputStream(File file) throws IOException {
              return getFileOutputStream(file, true);
         * Convienience method for opening a FileOutputStream w/wo a buffer
         * makes sure that the file directory exists so this should always succeed.
         public static OutputStream getFileOutputStream(File file, boolean buffered) throws IOException {
              if (!file.exists() && !file.isDirectory()) {
                   confirmDirectoryExists(file.getParentFile());
              if (file.exists()) {
                   if (ALWAYS_BACKUP) {
                        file.renameTo(new File(file.getAbsolutePath() + "~"));
                   } else {
                        file.delete();
              file.createNewFile();
              OutputStream out = new FileOutputStream(file);
              if (buffered) {
                   out = new BufferedOutputStream(out);
              return out;
         * Confirms that a directory exists and makes it if it doesn't
         public static void confirmDirectoryExists(File dir) {
              if (!dir.exists()) {
                   confirmDirectoryExists(dir.getParentFile());
                   dir.mkdir();
              if (!dir.isDirectory()) {
                   confirmDirectoryExists(dir.getParentFile());
         public static OutputStream getFileOutputStream(String name) throws IOException {
              return getFileOutputStream(name, true);
         public static PrintStream getFilePrintStream(String file) throws IOException {
              return new PrintStream(getFileOutputStream(file));
         public static PrintStream getFilePrintStream(File file) throws IOException {
              return new PrintStream(getFileOutputStream(file));
         public static OutputStream getFileOutputStream(String name, boolean buffered) throws IOException {
              return getFileOutputStream(new File(name), buffered);
         * @param f if f is a directory it returns the absolue path to f otherwise it returns the absolute path to the directory f is in
         public static String getDirectory(File f) {
              if (f.isDirectory()) {
                   return f.getAbsolutePath();
              else {
                   return f.getParentFile().getAbsolutePath();
         * Get the file without the extension.
         * @see getFileNoExtension(String);
         public static String getFilenameNoExtension(File f) {
              return getFilenameNoExtension(f.getName());
         * Gets the file name without the extension
         * returns the whole file name if no '.' is found<br>
         * otherwise returns whatever's before the last .
         public static String getFilenameNoExtension(String s) {
              int idx = s.indexOf('.');
              if (idx == -1) {
                   return s;
              else {
                   return s.substring(0, idx);
         * gets the file extension
         * if a '.' character is found it returns what's after the last .
         * if not, it returns the empty string
         public static String getFileExtension(String s) {
              int idx = s.lastIndexOf('.');
              if (idx == -1) {
                   return "";
              else {
                   return s.substring(idx + 1);
         * @see getFileExtension(String)
         public static String getFileExtension(File f) {
              return getFileExtension(f.getName());
         * Delete everything in a directory. Recursively deletes all sub-directories
         public static void deleteDirectory (File f, Component parent) {
              if (!f.isDirectory()) {
                   throw new RuntimeException("File " + f.getAbsolutePath() + " is not a directory!");
              int val = JOptionPane.showConfirmDialog(parent, "Confirm Delete " + f.getAbsolutePath(), "Confirm Delete " + f.getAbsolutePath(), JOptionPane.OK_CANCEL_OPTION);
              if (val == JOptionPane.OK_OPTION) {
                   deleteAllFiles(f);
         private static void deleteAllFiles (File f) {
              //recursively delete all its contents
              if (!f.isDirectory()) {
                   //throw new RuntimeException("File " + f.getAbsolutePath() + " is not a directory!");
                   f.delete();
              else {
                   File[] files = f.listFiles();
                   for (int i = 0; i < files.length; i++) {
                        if (files[i].equals(f) || files[i].equals(f.getParent())) {
                             continue;
                        deleteAllFiles(files[i]);
                   f.delete();
         * static utility method for copying a file to another location
         public static void copyFile (File src, File newParent) throws FileNotFoundException {
              if (!src.exists()) {
                   return;
              if (!newParent.exists()) {
                   newParent.mkdirs();
                   //throw new RuntimeException("Parent folder must exist");
              if (newParent.isDirectory()) {
                   File newFile = new File(newParent, src.getName());
                   if (src.isDirectory()) {
                        newFile.mkdir();
                        File children[] = src.listFiles();
                        for (int i = 0; i < children.length; i++) {
                             copyFile(children[i], newFile);
                   else {
                        //loadFile
                        InfoFetcher info = loadData(new FileInputStream(src));
                        final BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(newFile));
                        info.addInputStreamListener(new InputStreamListener() {
                             int lastbytes = 0;
                             public void gotMore(InputStreamEvent ev1) {
                                  try {
                                       out.write(ev1.getBytes(), lastbytes, ev1.getBytesRetrieved() - lastbytes);
                                       lastbytes = ev1.getBytesRetrieved();
                                  catch (IOException iox) {
                                       iox.printStackTrace();
                             public void gotAll(InputStreamEvent ev2) {
         * @deprecated use the Find class
         public static File find(Pattern p, File start) {
              return recursiveFind(start, null, p, true);
         * @deprecated use the Find class
         public static File find(Pattern p) {
              return find(p, new File("."));
         * @deprecated use the Find class
         private static File recursiveFind(File current, File cameFrom, Pattern p, boolean startDescending) {
              Matcher m = p.matcher(current.getName());
              if (m.matches()) {
                   return current;
              File[] files = current.listFiles();
              if (startDescending) {
                   File value = descend(current, cameFrom, p, startDescending);
                   if (value != null) return value;
                   return ascend(current, cameFrom, p, startDescending);
              else {
                   File value = ascend(current, cameFrom, p, startDescending);
                   if (value != null) return value;
                   return descend(current, cameFrom, p, startDescending);               
         * @deprecated use the Find class
         private static File ascend(File current, File cameFrom, Pattern p, boolean startDescending) {
              File par = current.getParentFile();
              if (par == null) {
                   return null;
              par = par.getAbsoluteFile();
              if (par.equals(cameFrom)) {
                   return null;
              return recursiveFind(par, current, p, false);
         * @deprecated use the Find class
         private static File descend(File current, File cameFrom, Pattern p, boolean startDescending) {
              File files[] = current.listFiles();
              if (files == null) {
                   return null;
              for (int i = 0; i < files.length; i++) {
                   File child = files[i];
                   if (child.equals(cameFrom)) {
                        continue;
                   File f = recursiveFind(child, current, p, true);
                   if (f != null) {
                        return f;
              return null;
         * Utility for saving a string to a file. Rather than have to set
         * up all the writers etc and trap exceptions, just returns a boolean
         * if it worked
         * <p>
         * @see saveData(File, byte[])
         public static boolean saveData(File f, String s) {
              return saveData(f, s.getBytes());
         * Utility for saving a string to a file. Rather than have to set
         * up all the writers etc and trap exceptions, just returns a boolean
         * if it worked
         public static boolean saveData(File f, byte[] data) {
              try {
                   OutputStream out = new BufferedOutputStream(new FileOutputStream(f));
                   out.write(data);
                   out.close();
              catch(IOException iox) {
                   iox.printStackTrace();
                   return false;
              return true;
         * Way to save a stream to a file. Not multithreaded.
         * Will block until the save is done
         * @param f
         * @param in
         * @return
         public static boolean saveData(File f, InputStream in) throws FileNotFoundException {
              return pipe(in, new FileOutputStream(f), TimeOut.NO_TIMEOUT, true) == null;
              //InfoFetcher fetcher = loadData(in);
    //          try {
    //               FileOutputStream out = new FileOutputStream(f);
    //               fetcher.addFetcherListener(new FetcherListener() {
    //                    public void fetchedMore(byte[] buf, int start, int end) {
    //                    public void fetchedAll(byte[] buf) {
    //          } catch (IOException iox) {
    //               iox.printStackTrace();
    //               return false;
    //          return true;
         * @deprecated use Find
         public static List<File> findAllFiles(Pattern p) {
              ArrayList<File> l = new ArrayList<File>();
              //File start = File.listRoots()[0];
              File start = new File("C:\\");
              return recursiveFindAll(start, null, p, true, l, 0);
              //l;
         * @deprecated use Find
         private static List recursiveFindAll(File current, File cameFrom, Pattern p, boolean startDescending, ArrayList<File> list, int level) {
              //System.out.println("" + level + " Scanning: " + current + "par: " + cameFrom);
              System.out.println("Scanning: " + current);
              Matcher m = p.matcher(current.getName());
              if (current.getName().equals("C:\\")) {
                   System.out.println("root");
                   try {
                        System.in.read();
                   catch (IOException iox) {}
              if (m.matches()) {
                   //return current;
                   list.add(current);
                   System.out.println("Adding " + current);
              File[] files = current.listFiles();
              if (startDescending) {
                   //File value = descend(current, cameFrom, p, startDescending);
                   descendAll(current, cameFrom, p, startDescending, list, level + 1);
                   //ascendAll(current, cameFrom, p, startDescending, list, level + 1);
                   //if (value != null) return value;
                   //return ascend(current, cameFrom, p, startDescending);
              else {
                   //ascendAll(current, cameFrom, p, startDescending, list, level + 1);
                   descendAll(current, cameFrom, p, startDescending, list, level + 1);
                   //File value = ascend(current, cameFrom, p, startDescending);
                   //if (value != null) return value;
                   //return descend(current, cameFrom, p, startDescending);               
              return list;
         * @deprecated use Find
         private static List ascendAll(File current, File cameFrom, Pattern p, boolean startDescending, ArrayList<File> list, int level) {
              File par = current.getParentFile();
              if (par == null) {
                   return list;
              par = par.getAbsoluteFile();
              if (par.equals(cameFrom)) {
                   return list;
              recursiveFindAll(par, current, p, false, list, level);
              return list;
         * @deprecated use Find
         private static File descendAll(File current, File cameFrom, Pattern p, boolean startDescending, ArrayList<File> list, int level) {
              File files[] = current.listFiles();
              if (files == null) {
                   return null;
              for (int i = 0; i < files.length; i++) {
                   File child = files[i];
                   if (child.equals(cameFrom)) {
                        continue;
                   recursiveFindAll(child, current, p, true, list, level);
              return null;
         public File getUniqueName(File f) {
              return getUniqueName (f, new MessageFormat("~{0,number,integer}"));
         public String getNameWOExtension(File f, boolean useAbsolute) {
              int idx = f.getName().indexOf(".");
              return (idx == -1) ? (useAbsolute ? f.getAbsolutePath() : f.getName()) : (useAbsolute ? f.getAbsolutePath() : f.getName()).substring(0, (useAbsolute ? f.getAbsolutePath().lastIndexOf(".") : f.getName().lastIndexOf(".")));
         public String getFileType (File f, boolean includeDot) {
              int idx = f.getName().lastIndexOf(".");
              return idx == -1 ? "" : f.getName().substring(idx + (includeDot ? 0 : 1));
         public File getUniqueName(File f, MessageFormat format) {
              String base = getNameWOExtension(f, true);
              String extension = getFileType(f, true);
              int count = 0;
              while (f.exists()) {
                   count++;
                   f = new File (base + format.format(new Object[] {Integer.valueOf(count)}) + extension);
              return f;
         public static boolean isUTF16 (File f) throws IOException {
              FileInputStream in = null;
              try {
                   if (!f.exists() || f.length() < 2) return false;
                   in = new FileInputStream(f);
                   byte b = (byte)in.read();
                   if (!(b == -1)) return false;
                   b = (byte) in.read();
                   return b == -2;
              finally {
                   if (in != null) in.close();
         public static boolean isUTF16(PushbackInputStream in) {
              boolean got1 = false, got2 = false;
              byte b = 0, b2 = 0;
              try {
                   b = (byte)in.read();
                   got1 = true;
                   if (!(b == -1 || b== -2)) {
                        return false;
                   b2 = (byte) in.read();
                   got2 = true;
                   return b == -1 ? b2 == -2 : b2 == -1;
              catch (IOException iox) {
                   iox.printStackTrace();
              finally {
                   try {
                        if (got1) {
                             in.unread(b);
                        if (got2) {
                             in.unread(b2);
                   } catch (IOException iox) {
                        iox.printStackTrace();
              return false;
         public void saveJTableToCSV(JTable table, File f) throws IOException {
              if (table == null || f == null) return;
              TableModel model = table.getModel();
              if (model == null) return;
              int rows = model.getRowCount();
              int columns = model.getColumnCount();
              PrintWriter pw = new PrintWriter(new FileWriter(f));
              for (int i = 0; i < rows; i++) {
                   for (int j = 0; j < columns; j++) {
                        Object o = model.getValueAt(i, j);
                        pw.print(o.toString());
                        if (j != columns - 1) {
                             pw.print(",");
                   pw.println();
         public static String getPathRelativeTo(File path, File relativeTo) {
              return getPathRelativeTo(path.getAbsolutePath(), relativeTo.getAbsolutePath());
         public static String getPathRelativeTo(String path, String relativeTo) {
              if (!path.startsWith(relativeTo)) return null;
              path = path.substring(relativeTo.length());
              if (path.startsWith(File.separator)) path = path.substring(File.separator.length());
              return path;

  • Hi,encoding String value?

    hi,
    PrintWriter out = new PrintWriter(new OutputStreamWriter(res.getOutputStream(), "UTF8"), true);
    the above line working well, i can able to convert to UTF-8 encoding.
    how to convert string values to URF-8 .
    any one can convert the following lines to UTF-8
    StringWriter writer = new StringWriter();
    OutputStream out = response.getOutputStream();
    out.write(writer.toString().getBytes());
    /code]
    thanks
    siva                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    out.write(writer.toString().getBytes("UTF-8"));

  • UIImage to Base64 Encoded String does not matched with PHP Encoded String

    Hi, I have converted an image to base64 string using the following
    UIImage* pic = [UIImage imageNamed:@"closeBtn.png"];
        NSData* pictureData = UIImagePNGRepresentation(pic);
        [Base64 initialize];
        NSString * encodedString = [Base64 encode:pictureData];
    The result obtained by this method and by converting the same image to base64 string in PHP or ASP is different. I am comparing the base64 string (testData) with online generated string from URL http://www.dailycoding.com/Utils/Converter/ImageToBase64.aspx
    Please help ASAP

    Keith:
    I am converting the PNG Image.Actually i want to post a image to PHP server via JSON. for that i am converting the image into base64 string and then sending JSON via HTTP. but when server receives a image data , it cannot convert and save it properl (blank image with 0x0 dimensions). I have compared the Base64 String created from xCode with some online conversion tools. and results are different. I have even tried with JPG images as well.
    How can I get the Same Encoded String as PHP or ASP code can have?

  • How can I convert an int to a string?

    Hi
    How can I convert an int to a string?
    /ad87geao

    Here is some the code:
    public class GUI
        extends Applet {
      public GUI() { 
        lastValue = 5;
        String temp = Integer.toString(lastValue);
        System.out.println(temp);
        showText(temp);
      private void showText(final String text) {
        SwingUtilities.invokeLater(new Runnable() {
          public void run() {
            tArea2.setText(text + "\n");
    }

  • Cannot convert type class java.lang.String to class oracle.jbo.domain.Clob

    Cannot convert type class java.lang.String to class oracle.jbo.domain.ClobDomain.
    Using ADF Business Components I have a JSFF page fragment with an ADF form based on a table with has a column of type CLOB. The data is retrieved from the database and displayed correctly but when any field is changed and submitted the above error occurs. I have just used the drag and drop technique to create the ADF form with a submit button, am I missing a step?
    I am using the production release of Jdeveloper11G

    Reproduced and filed bug# 7487124
    The workaround is to add a custom converter class to your ViewController project like this
    package oow2008.view;
    import javax.faces.application.FacesMessage;
    import javax.faces.component.UIComponent;
    import javax.faces.context.FacesContext;
    import javax.faces.convert.Converter;
    import javax.faces.convert.ConverterException;
    import oracle.jbo.domain.ClobDomain;
    import oracle.jbo.domain.DataCreationException;
    public class ClobConverter implements Converter {
         public Object getAsObject(FacesContext facesContext,
                                   UIComponent uIComponent,
                                   String string) {
           try {
             return string != null ? new ClobDomain(string) : null;
           } catch (DataCreationException dce) {
             dce.setAppendCodes(false);
             FacesMessage fm =
               new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                "Invalid Clob Value",
                                dce.getMessage());
             throw new ConverterException(fm);
         public String getAsString(FacesContext facesContext,
                                   UIComponent uIComponent,
                                   Object object) {
           return object != null ?
                  object.toString() :
                  null;
    }then to register the converter in faces-config.xml like this
    <faces-config version="1.2" xmlns="http://java.sun.com/xml/ns/javaee">
      <application>
        <default-render-kit-id>oracle.adf.rich</default-render-kit-id>
      </application>
      <converter>
        <converter-id>clobConverter</converter-id>
        <converter-class>oow2008.view.ClobConverter</converter-class>
      </converter>
    </faces-config>then reference this converter in the field for the ClobDomain value like this
              <af:inputText value="#{bindings.Description.inputValue}"
                            label="#{bindings.Description.hints.label}"
                            required="#{bindings.Description.hints.mandatory}"
                            columns="40"
                            maximumLength="#{bindings.Description.hints.precision}"
                            shortDesc="#{bindings.Description.hints.tooltip}"
                            wrap="soft" rows="10">
                <f:validator binding="#{bindings.Description.validator}"/>
                <f:converter converterId="clobConverter"/>
              </af:inputText>

  • Need to convert a long into a string, please

    hi there
    i need to convert a long into a string. can i just cast it like this:
    (String)longNumber = some function that returns a long;

    Why not just use Long.toString()? If you start with a long value, you can create a Long object and get it's value as a String.

  • Need to convert  Date from calendar to String in the format dd-mom-yyyy

    Need to convert Date from calendar to String in the format dd-mom-yyyy+..
    This is absolutely necessary... any help plz..
    Rgds
    Arwinder

    Look up the SimpleDateFormat class: http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html
    Arwinder wrote:
    This is absolutely necessary... any help plz..For you maybe, not others. Please refrain from trying to urge others to answer your queries. They'll do it at their own pace ( if at all ).
    People on the forum help others voluntarily, it's not their job.
    Help them help you.
    Learn how to ask questions first: http://faq.javaranch.com/java/HowToAskQuestionsOnJavaRanch
    (Yes I know it's on JavaRanch but I think it applies everywhere)
    ----------------------------------------------------------------

Maybe you are looking for