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).

Similar Messages

  • 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!

  • Is it faster to store strings in UNICODE?

    I have learned that, for applications using JDBC to access DB2, storing strings in UNICODE format provides a substantial performance improvement. Do you know if the same is true for Oracle?

    900605 wrote:
    Lets talk about objects now.
    If i create an object and left without nullifying then it stays in memory till garbage collector is called.
    What happens if i nullify in finally? will the memory is cleared or in this case also just link(Object pointing) is cleared and it occupy memory still the garbage collector is called?In addition to what EJP said, make sure you understand that it is not possible to "nullify" an Object. Objects can never be null, only references can.
    When you do x = null; you're not "clearing an object." You're just setting a reference variable to null, with the only direct result being that whatever object that reference previously pointed to now has one less reference pointing to it.

  • Converting Hex string to unicode

    I am reading in a hex representation of Unicode characters as a string.(for example: 004100200042)
    I want to convert the string from hex to unicode, and write the corresponding characters to a file. The output should look like follow:
    A B (0041 = Capital A, 0020 = space, 0042 = Capital B)
    Could you please assist?

    Problem solved, no need to look into it. Thank you

  • 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.

  • ASCII string to Unicode

    My problem: i have to parse a file-format where special-characters are replaced by an (ASCII) escape sequence - e.g. \344 or \u2200.
    I get these char-sequences through a FileReader and a StreamTokenizer into a String. Since i need to draw the String, i need to re-create the special-chars, but using the "internationalisation tutorial" doesnt work here. There it is said to use a String.getBytes(string,"ENCODING") and then recreate a String with this byte-array. But there is no difference!...
    Any ideas on how to do it?

    Translating the string "\u2200" into the corresponding Unicode character is fairly simple: drop off the "\u" portion and executechar uChar = (char)Integer.parseInt(theRest, 16);This is simplified by the fact that the Unicode encodings are always "\u" followed by 4 hexadecimal digits -- are they not? Now, what about the things like "\344"? Are they always the same length? (If not, how do we know that is the escape sequence and that it is not "\34" followed by the character "4"?) And are they decimal or hexadecimal or octal?

  • Parsing strings with Unicode values 16 bits

    How can I get the Unicode value for a character in a String when the value is greater than 16 bits?
    I need to extract a supplemental plane Unicode value from a string. However,  String.charCodeAt(index) truncates the Unicode value to 16 bits,  returning what should be 0x02F91A  as  0xF91A.  I see discussions that show that earlier versions of Flex stores such char codes as the two code points of a surrogate pair, but  in Flex 4, the string length is just 1 when I put only this character in the string.

    Does it work in JavaScript?  Could send it over via externalInterface.

  • How to convert Raw data to string in Unicode conversion

    Hi All,
    I want to convert my report in Unicode while conversion we are getting error as "The key of internal table "IRESBD" contains components of type "X" or "XSTRING". The "READ TABLE IRESBD" statement is not permitted for such tables"
    Regards,

    Thanks for reply ,
    I tried to use the FM but not able to get any value ? is this FM converts all internal table or used to convert one field value.
    My report is Unicode so i need to internal table while reading Internal table which contains fiield as GUID_16 type Raw is showing error.
    Regards,

  • Convert document into string with unicode

    I want to convert my document into string with all <,>,& to be converted into <, >, and &. When I am doing transformation, I am getting <,> etc.
    Can anybody suggest me how to do that.
    regards,
    Ranjan

    I don't know of any way to tell the parser to convert is for you, you'll have to replace the characters yourself after you got the string from the parser.
    Aviran
    http://www.aviransplace.com

  • Convert structure into single field in string  in unicode system .

    Hi all
    i need to convert whole structure in single fields which is string format
    plese refer this code .....this is structure which i want to use in concatenate statement
    statement is
    CONCATENATE EXPORTSTRING HFTP_ZSD_RKFR  CR_LF INTO EXPORTSTRING.
    where data are ...
    EXPORTSTRING type xstring
    CR_LF              type x
    structure HFTP_ZSD_RKFR having follwing fields
    MANDT     MANDT     CLNT     3     0
    VBELN_VL     VBELN_VL     CHAR     10     0
    LFDNUM     LFDNUM     NUMC     3     0
    VKORG     VKORG     CHAR     4     0
    VSTEL     VSTEL     CHAR     4     0
    VSBED     VSBED     CHAR     2     0
    KUNAG     KUNAG     CHAR     10     0
    KUNWE     KUNWE     CHAR     10     0
    SPDNR     SPDNR     CHAR     10     0
    LFDAT     LFDAT     DATS     8     0
    LFUHR     LFUHR     TIMS     6     0
    WADAT     WADAT     DATS     8     0
    TRAID     TRAID     CHAR     20     0
    ROUTE     ROUTE     CHAR     6     0
    WERKS     WERKS_D     CHAR     4     0
    MATNR     MATNR     CHAR     18     0
    LFIMG     LFIMG     QUAN     13     3
    MEINS     MEINS     UNIT     3     0
    ANZPK     ANZPK     NUMC     5     0
    ANZPK     ANZPK     NUMC     5
    KBETR     KBETR     CURR     11
    KPEIN     KPEIN     DEC     5
    KMEIN     KMEIN     UNIT     3
    KWAER     KWAER     CUKY     5
    KWERT     KWERT     CURR     13
    BELNR     BELNR_FI     CHAR     10
    GJAHR     GJAHR     NUMC     4
    MWSKZ     MWSKZ     CHAR     2
    SAKNR     SAKNR     CHAR     10
    BUKRS     BUKRS     CHAR     4
    BUDAT     BUDAT     DATS     8
    KOSTL     KOSTL     CHAR     10
    AUFNR     AUFNR     CHAR     12
    PRCTR     PRCTR     CHAR     10
    BRGEW     BRGEW     QUAN     13
    GEWEI     GEWEI     UNIT     3
    XBILL     ZSD_XBILL     CHAR     1
    XPARK     ZSD_XPARK     CHAR     1
    XPARK     ZSD_XPARK     CHAR     1
    XBLNR     XBLNR     CHAR     16
    KHERK     ZSD_KHERK     CHAR     1
    LIFEX     LIFEX     CHAR     35
    SDABW     SDABW     CHAR     4
    KBETR_MAUT     KBETR     CURR     11
    KPEIN_MAUT     KPEIN     DEC     5
    KMEIN_MAUT     KMEIN     UNIT     3
    KWERT_MAUT     KWERT     CURR     13
    KBETR_OEL     KBETR     CURR     11
    KPEIN_OEL     KPEIN     DEC     5
    KMEIN_OEL     KMEIN     UNIT     3
    KWERT_OEL     KWERT     CURR     13
    KBETR_PAL     KBETR     CURR     11
    KPEIN_PAL     KPEIN     DEC     5
    KMEIN_PAL     KMEIN     UNIT     3
    KWERT_PAL     KWERT     CURR     13
    KBETR_VAT     KBETR     CURR     11
    KPEIN_VAT     KPEIN     DEC     5
    KPEIN_VAT     KPEIN     DEC     5
    KMEIN_VAT     KMEIN     UNIT     3
    KWERT_VAT     KWERT     CURR     13
    BLDAT     BLDAT     DATS     8
    MWS_BETRG     WRBTR     CURR     13
    KURSF     KURSF     DEC     9
    UVK06          CHAR     1

    I have used this FM
    SAP_CONVERT_TO_TXT_FORMAT
    There's also a method in cl_abap_char_utilities to convert a structure to a C container, look for it, I only have 4.6C here and that class is only in ECC

  • Initialising strings with unicode characters

    This works
    System.out.println("Hello World");
    but this will not compile
    System.out.println("&#20320;&#22909;");
    How do I get unicode characters into my Java source?
    I am running Windows XP and editing my files using notepad.
    If I save my source as ASCII it compiles, but I do not get the foreign characters.
    If I save my file as utf-8 or unicode the source will not compile.

    I have got it!
    On Windows XP using notepad the java source file can be "saved as" Unicode.
    The source can then be compiled using;
    javac HelloWorld.java -encoding unicode
    The code compiles and executes.
    It is even possible to give variables names that are Chinese characters, which is really what you would expect to be able to do.

  • How to store text in AD attributes of type String(Unicode)

    In our company, we store the name of the building in which an employee works in one of the ActiveDirectory attributes named extensionAttribute# where # represents a number form 1-15.  I want to be able to store the names of buildings in the AD
    attribute named "buildingName". According to the
    buildingName attribute in the MSDN library, the syntax is "String(Unicode)".
    When I try something that seems simple to write some text into this attribute such as
    Set-QADUser jdoe -ObjectAttributes @{buildingName="My Building Name"}
    I get an error that says "Set-QADUser : The requested operation did not satisfy one or more constraints associated with the class of the object."
    I have been searching forums and code libraries for a solution to this issue, but I do not understand why I can't store string data into this attribute. I did try the following code snippets to try to convert the string to Unicode (and UTF-8) before I wrote
    to the buildingNameAttribute, but I still get the same error.
    $text = "My Building Name"
    $enc = [System.Text.Encoding]::Unicode
    # $enc = [System.Text.Encoding]::UTF8
    $encText = $enc.GetBytes($text)
    $encText
    Set-QADUser jdoe -ObjectAttributes @{buildingName=$encText}
    Has anyone else had this issue or know how to overcome it? I can, of course, continue to use the extensionAttribute in which I currently have the data stored, but I really want to free it up and use the "buildingName" attribute.
    Gardner Rowe Systems Analyst III UT MD Anderson Cancer Center - Making Cancer History

    From your link:
    buildingName attribute
    The name of the building where an organization or organizational unit is based.
    IOW, it is an attribute of organization or organizational unit class of object not a user object, so you can't set it for a user.
    [string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "

  • 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

  • Unicode(String) to actual Unicode !

    Hi, i have an unicode data which is retrieved from database, the unicode is in String format(\u4eba\u53c2), how to make it to be actual unicode "\u4eba\u53c2". i have a problem where the unicode from database doesn't give me the actual character but the unicode string itself. Please comment on it . Thanks.
    _calv                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    Hi Calv,
    I'm pretty sure that the conversion from the ASCII string to Unicode is not available within the API. (If someone knows otherwise please jump in). However it should be fairly easy for you to program this conversion: for example, you could parse your string into the six character substrings that represent characters, strip off the \u, and then cast the sixteen bit integer into a Character.
    In case it's helpful, I am pasting a couple of methods I wrote to go in the opposite direction:
    returns a (ASCII) string that represents the specified character by a  unicode escape sequence
    static public String toUnicodeString(  char character) {
         short unicode = (short) character;
       char hexDigit[] = {
          '0', '1', '2', '3', '4', '5', '6', '7',
          '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
       char[] array = {hexDigit[( unicode >> 12) & 0x0f],hexDigit[( unicode >> 8) & 0x0f],
            hexDigit[( unicode >> 4) & 0x0f], hexDigit[ unicode & 0x0f] };
    String result = new String ("\\u" + new String (array));
       return result;
    returns a (ASCII)  string representing the java string argument:
    e.g. -> "\u1234\u5678"
    static public String toUnicodeString(  String  string) {
         String result = "\"";
         for (int   index =      0; index < string.length (); index++) {
              result = result +  toUnicodeString (string.charAt (index));
         result = result + "\"";
       return result;
    }   Regards,
    Joe

  • 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;

Maybe you are looking for