Getting String encoding

Hello ,
I need to get encoding from String object which is already created and dont know which encoding it has,how can i get this encoding? is there some easy solutions if yes please give me a peace of code please,
thanks

To clarify: In Java character and String types are stored in UNICODE, so the actual codes should always be consistent whatever languages you're using and you shouldn't need to know what coding is used. Indeed I'd regard it as bad practice to write code which depends on the specific codes, there are plenty of classification tests in the Character class.
When text is changed to of from a sequence of bytes, that's when encoding becomes an issue. Of course a file is a sequence of bytes to encoding also applies when text data is read from or written to a file.
So whenever you read or write text to or from a file or a byte array a specific encoding will be used (even if you allow it to default to the standard encoding of the system you're running on).
Most encodings can only cope with a subset of the UNICODE characters. The exceptions are UTF-8 and UTF-16. If a character can't be converted Java normally substitutes a "?".
Character encodings tend to come with nice, readily memorable names like ISO-8859-1.

Similar Messages

  • Is it possible to get file encoding?

    I am working with windows netsh util
    /**filename = path to file*/
    private static BufferedReader readFileWithBufferedReader(String filename){
            FileInputStream fis = null;
            InputStreamReader sr= null;
            BufferedReader r    = null;
            try {
                fis = new FileInputStream(filename);
            } catch (FileNotFoundException ex) {
                ex.printStackTrace();
            }//fis catch
            try {
                /*creating InputStreamReader with encoding param*/
                sr = new InputStreamReader(fis, "Cp866" /*"Cp1251"*/);
                System.out.println("encoding ::: " +sr.getEncoding());
            } catch (UnsupportedEncodingException ex) {
                ex.printStackTrace();
            }//sr catch
                /*wrapping to BufferedReader*/
                br = new BufferedReader( sr);
            System.out.println("YES!!!");   
            return br;
        }I get InputStream from console. I set encoding as "cp866" (it's O.K.)
    Then, I save stream to file.
    Then user can open this file and get config from file.
    The problem is in open file procedure.
    I do not know file encoding: it can be "cp1251" (windows cyrillic) or it can be "cp866" (cmd output).
    So if user tries to open "cp1251" file with "cp866" encoding, he gets unreadable characters.
    Is it possible to get file encoding and then re-create InputStreamReader with proper encoding?

    Well, you can't get the file encoding. It's not saved with the file. Unless it's your file format, in which case you can save whatever you want.
    There are apps that can guess a file's encoding.
    Of course, if you have control over the files entirely, it shouldn't be a problem, and generally it'd make life a lot easier to just use UTF-8.
    So if user tries to open "cp1251" file with "cp866" encoding,
    he gets unreadable characters.what if you read a "cp866" with "cp1251" encoding?

  • Is there a way to get string in *ai file without Illustrator?

    Hi. I have a question.
    1. Type 'hello' in Illustrator document and save.
    2. open file to text editter.
    3. find 'hello' in text editter.
    4. text editter alert "Cannot find 'hello'"
    Is there a way to get string in *ai file without Illustrator?
    If you have answer, share me please.
    Thanks for reading.

    You can convert songs to Mono.  First, go to iTunes > Preferences > General > Import Settings.  Under the encoder menu is another drop-down menu for Settings.  Choose "Custom" and you'll be able to select a choice for Mono.  Once that is set, use the iTunes > Advanced menu to create a mono version.  The original stereo version will remain in your library unless you choose to delete it.

  • How can I get String from Bytes

    I want to get String from array of bytes but i have some trouble from byte that it's lager more than 128. How can I do ???
    Please hepl me. Thanks very much.

    This program is only to show you what the relationships are between unsigned byte, signed byte, character, and binary values. Because of the constraints that Java has, the program code is not especially clean. Run the program and see if it helps. As has been said, the character output is dependent on the encoding in use.
    Here is a sample of some of its output:
    Unsigned byte= 189 Signed byte= -67 Character= � Binary= 10111101
    Unsigned byte= 190 Signed byte= -66 Character= � Binary= 10111110
    Unsigned byte= 191 Signed byte= -65 Character= � Binary= 10111111
    Unsigned byte= 192 Signed byte= -64 Character= � Binary= 11000000
    Unsigned byte= 244 Signed byte= -12 Character= � Binary= 11110100
    Unsigned byte= 245 Signed byte= -11 Character= � Binary= 11110101
    Unsigned byte= 246 Signed byte= -10 Character= � Binary= 11110110
    public class ATest {
        public static void main(String[] args) {
            int in;
            byte by;
            String bin;
            char chr;
            for(in=0; in<256; in++) {
                // create a byte whose binary value is equal to the;
                // integer loop counter;
                by = (byte)in;
                // mask off sign extension [that I don't agree with!] and;
                // cast the resultant 8 bits to a char;
                chr = (char)(by & 0x00ff);
                // since there's no Byte.toInteger, must cast to int to get;
                // binary string and then delete unwanted portion of string;
                if(in<128) {
                    bin = Integer.toBinaryString((int)by);
                } else {
                    bin = Integer.toBinaryString((int)by).substring(24);
                // print everything;
                System.out.println(
                    "Unsigned byte= "+in+
                    " Signed byte= "+by+
                    " Character= "+chr+
                    " Binary= "+bin);
    }

  • GET String from databse

    Hi All,
    can any one help me on urgent basis for below
    I am having database connection program having a query which generate a string for XML format.
    after executing this program i am getting string as a null.
    please have a look for below program
                             sql.append("SELECT XMLRoot (XMLELEMENT ")
                             .append(" (\"CC_Hierarchy\",xmlattributes ( '0' as \"id\" ),") // \" nothing but "" in sql editor
                             .append(" (SELECT DBMS_XMLGEN.getxmltype")
                             .append(" (DBMS_XMLGEN.newcontextfromhierarchy")
                             .append("          ('SELECT LEVEL,")
                             .append("               XMLELEMENT (\"item\",")
                             .append("                     xmlattributes (cc_nbr || '' - '' ||CC_NM||DECODE(CC_NBR,DIV_CC_NODE,'' <font color=\"3349FF\"> <b>''||BU_NM||''</b> <font color=\"F62B04\"><b> ''||DIV_NM||'' </b><font color=\"FF33B7\"> <b> ''||CFO_NM||''</b><font color=\"green\"><b>''||FM_NM||''</b>'','' '') AS \"text\",")
                             .append("                                         cc_nbr AS \"id\",")
                             .append("                                         DECODE (SUBSTR (cc_nbr, 0, 1),''S'', 1, 0 ) AS \"child\", ")
                             .append("                                         DECODE (SUBSTR (cc_nbr, 0, 1),''S'', ''folderClosed.gif'', NULL) AS \"im0\", ")
                             .append("                                         DECODE (SUBSTR (cc_nbr, 0, 1),''S'', ''folderOpen.gif'',NULL) AS \"im1\", ")
                             .append("                                         DECODE (SUBSTR (cc_nbr, 0, 1),''S'', ''folderClosed.gif'', NULL) AS \"im2\" ")
                             .append("                                    ), ")
                             .append(" XMLELEMENT (\"userdata\", ")
                             .append("               xmlattributes (''itemType'' as \"name\" ), ")
                             .append("                              DECODE ( SUBSTR (cC_NBR, 0, 1),''S'',''PNODE'',''LNODE'') ")
                             .append("                    ) ) ")
                             .append("               FROM tableName ")
                             .append("               START WITH LTRIM (TRIM (cc_nbr), ''0'') = LTRIM (TRIM (''S531306''), ''0'') ")
                             .append("               CONNECT BY NOCYCLE parent_cc_nbr = PRIOR cc_nbr' ")
                             .append("               )")
                             .append("           )")
                             .append("      FROM DUAL)")
                             .append("     ), VERSION '1.0\" encoding=\"iso-8859-1') xmldoc ")
                             .append("     FROM DUAL");
                             System.out.println(sql.toString());
                             pst = connection.prepareStatement(sql.toString());
                             rs = pst.executeQuery();
                             while(rs.next()){
                                  System.out.println(rs.getString("xmldoc")); //here getting null
                             }

    Hi,
    you can do this as below:
    This example shows the use of getObject to directly get the XMLType from the ResultSet. This code snippet is the easiest way to get the XMLType from the ResultSet.
    import oracle.xdb.XMLType;
    PreparedStatement stmt = conn.prepareStatement(
    "select e.poDoc from po_xml_tab e");
    ResultSet rset = stmt.executeQuery();
    while(rset.next())
    // get the XMLType
    XMLType poxml = (XMLType)rset.getObject(1);
    // get the XML as a string...
    String poString = poxml.getStringVal();
    }

  • How to get string value from xml in JSF??

    In JSF How to get string value from xml, .ini and properties file. I want to get string value from xml or text to JSF

    Just use the appropriate API's for that. There are enough API's out which can read/parse/write XML, ini and properties files. E.g. JAXP or DOM4J for xml files, INI4J for ini files and Sun's own java.util.Properties for propertiesfiles.
    JSF supports properties files as message bundle and resource bundle so that you can use them for error messages and/or localization.

  • How to get string value from database table using Visual Studio 2005?

    Hi,
    Im developing plugin in illustrator cs3 using visual studio 2005. I need to get the values eneterd in database. Im able to get the integer values. But while getting string values it is returning empty value.
    Im using the below code to get the values from database table
    bool Table::Get(char* FieldName,int& FieldValue)
        try
            _variant_t  vtValue;
            vtValue = m_Rec->Fields->GetItem(FieldName)->GetValue();
            FieldValue=vtValue.intVal;
        CATCHERRGET
        sprintf(m_ErrStr,"Success");
        return 1;
    Im using the below code to get the values.
    AIErr getProjects()
        char buf[5000];
        int i;   
        std::string  catName;
        ::CoInitialize(NULL);
        Database db;
        Table tbl;
        errno_t err;
        err = fopen(&file,"c:\\DBResult.txt","w");
        fprintf(file, "Before Connection Established\n");
        //MessageBox(NULL,CnnStr,"Connection String",0);
        if(!db.Open(g->username,g->password,CnnStr))
            db.GetErrorErrStr(ErrStr);
            fprintf(file,"Error: %s\n",ErrStr);
        fprintf(file, "After Connection Established\n");
    if(!db.Execute("select ProjectID,ProjectName from projectsample",tbl))
            db.GetErrorErrStr(ErrStr);
            fprintf(file,"Error: %s\n",ErrStr);
        int ProjectID;
        int UserID;
        int ProjectTitle;
        char ProjectName[ProjectNameSize];
        if(!tbl.ISEOF())
            tbl.MoveFirst();
        ProjectArrCnt=0;
        for(i=0;i<128;i++)
            buf[i]='\0';
            int j=0;
        while(!tbl.ISEOF())
            if(tbl.Get("ProjectID",ProjectID))
                fprintf(file,"Project ID: %d ",ProjectID);
                ProjectInfo[ProjectArrCnt].ProjectID = ProjectID;
                sprintf(buf,"%d",ProjectID);
                //MessageBox(NULL, buf,"f ID", 0);
                j++;
            else
                tbl.GetErrorErrStr(ErrStr);
                fprintf(file,"Error: %s\n",ErrStr);
                break;
            //if(tbl.Get("ProjectTitle",ProjectName))
            if(tbl.Get("ProjectName",ProjectName))
                MessageBox(NULL,"Inside","",0);
                fprintf(file,"ProjectTitle: %s\n",ProjectName);
                //catName=CategoryName;
                ProjectInfo[ProjectArrCnt].ProjectName=ProjectName;
                //sprintf(buf,"%s",ProjectName);
                MessageBox(NULL,(LPCSTR)ProjectName,"",0);
            else
                tbl.GetErrorErrStr(ErrStr);
                fprintf(file,"Error: %s\n",ErrStr);
                break;
            ProjectArrCnt++;
            //MessageBox(NULL, "While", "WIN API Test",0);
            tbl.MoveNext();
        //MessageBox(NULL, ProjectInfo[i].ProjectName.c_str(),"f Name", 0);
        ::CoUninitialize();
        //sprintf(buf,"%s",file);
        //MessageBox(NULL,buf,"File",0);
        fprintf(file, "Connection closed\n");
        fclose(file);
        for(i=0;i<ProjectArrCnt;i++)
            sprintf(buf,"%i",ProjectInfo[i].ProjectID);
            //MessageBox(NULL,buf,"Proj ID",0);
            //MessageBox(NULL,ProjectInfo[i].ProjectName.c_str(),"Project Name",0);
        return 0;
    In the above code im geeting project D which is an integer value. But not able to get the project name.
    Please some one guide me.

    As I said in the other thread, this really isn't the place to ask questions about a database API unrelated to the Illustrator SDK. You're far more like to find people familliar with your problem on a forum that is dedicated to answering those kinds of questions instead.

  • How to get the "encoding" of a XML file using JDOM

    As in XML file, <?xml version="1.0" encoding="UTF-8" ?> indicates the encoding of this file
    while using JDOM to parse a XML file, how can I get the encoding type?
    thanx!!!

    What my program do is to get the encoding of XML files and convert them to UTF-8 encoding files, while I need this "encoding" information of the original XML document thus I can convert...
    After reading specifications and JDOM docs, the truth turns to be disappointed, no function is provided to get this information in JDOM level 2(the current released one), while it's promissed that this function will be provided in JDOM level API....
    Thanx all for your help and attention!!!

  • How to get the encoding of a XML file ...

    Hi,
    How do you get the encoding of a XML file?
    For example,
    <?xml version="1.0" encoding="SJIS"?>
    I am trying to retrieve the above encoding="SJIS", but I can't seem to locate the API for doing so.
    Thanks in advance for any help,
    Eric

    Hi ddossot,
    Thanks for your suggestion.
    However, the xerces.jar file that comes with my old tomcat server is an old version and thus, the getEncoding method is not even present in the DocumentImpl class. The option to update to a newer version of tomcat and xerces is not available. What a pity... :-(
    Well, I just have to try to find a way around. Worst case scenario, parse the first line in the xml file myself.
    Regards,
    Eric

  • How to get String out of  void method

    I have a problem to get String out of void method. I override method actionPerformed(), and I need to use String from this method in other methods. I get nothing in smth. Can anyone help me with this.
    class
    StringBuffer smth = new StringBuffer();
    StringBuffer s;
          public void actionPerformed(ActionEvent event){
              String vnos;
              if(event.getSource() == btn_vnos){
                   input = field.getText();
                   s = new StringBuffer(input);
                    smth = s;
                }             Thanks

    You have needs to use a static variable or somehow pass an instance reference, through a list or array or some such thing, perhaps through the constructor. Or think up some other jazz, like adding a method "public String getMyStinkin'String" ;~)
    ~Cheers

  • How to get string from jtextpane along with its attributes

    sir,
    How to get string from jtextpane along with its attributes
    i,e font,size,style,color etc.
    please help me out.
    my mail id is [email protected]

    JTextPane extends JTextComponent
    JTextComponent.getDocument()
    a Document is a set of Element, see Document.getRootElements(). Each Element has attributes, stored within an AttributSet object see Element.getAttributes()
    a Document can also be rendered as a String, see Document.getText( offest, length ), use it with 0 and Document.getLength() as parameters.

  • I go through the process of burning a DVD from a Premier Pro Project and at the end of the process I get an encoding error and the dvd does not start burning.  How do I fix this?

    I go through the process of burning a DVD from a Premier Pro Project and at the end of the process I get an encoding error and the dvd does not start burning.  How do I fix this?

    adam@honestmusky wrote:
    Yes I am using encore.  I used to have no problem doing this, but I had to get a new computer and now something isn't working right.
    How about some DETAILS?
    -Premiere Pro Video Editing Information FAQ http://forums.adobe.com/message/4200840
    Also describe the EXACT steps you take to go from Premiere Pro to Encore

  • Getting String using ResourceBundle and XLIF resource bundle.

    Hello,
    I am using Jdev. 11.1.1.2.0. I am trying to use XLIFF resource bundle in the Model project and trying to get string from the bundle using following code. I am getting MissingResourceException. if I use Property Bundle, it works fine.
    public String getMessage(String code)
    return ResourceBundle.getBundle("model.ModelBundle").getString("MESSAGE1");
    Any help to make it work with XLIFF resource bundle will be appreciated.
    Thanks,
    Amit
    Edited by: Amit Patel on Apr 1, 2010 10:23 AM

    To get the values from the resource bundle, you use the <fmt:message> tag
    <fmt:message bundle="${appbundle}" key="lbl.accountnum"/>

  • New InitialContext() gets String index out of bounds

    Context ctx = null;
    ctx = new InitialContext();
    DataSource dataSource = (DataSource) ctx.lookup("jdbc/datasource");
    connection = dataSource.getConnection();
    I get:
    String index out of range: -1
    weblogic.jndi.Environment.getContext(Environment.java:308)
    weblogic.jndi.Environment.getContext(Environment.java:285)
    weblogic.jndi.WLInitialContextFactory.getInitialContext(WLInitialContextFactory.java:117)
    javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:667)
    javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:288)
    javax.naming.InitialContext.init(InitialContext.java:223)
    javax.naming.InitialContext.<init>(InitialContext.java:175)
    Earlier when I had provider_url specified I didn't get this problem, but it should be working without specifing provider_url...
    And well now it doesn't work with provider_url localhost since they set -Djava.net.preferIPv4Stack=true
    Which made so it stopped listening to localhost:port...
    Does someone know a possible solution for:
    1. String index of range
    2. the preferIPv4Stack thingy, which makes the listeners to stop listening to localhost:port

    Be sure values contains data.
    Then make sure that size = values.length
    Either you don't have any data to iterate through, or the size variable is too big. So it's trying to search in parts of the array that don't exist.

  • How to get string (specified by line and column) from txt file with labview

    Hi everyone
    How to get string (specified by line and column) from txt file with labview
    thx 
    Solved!
    Go to Solution.

    As far as I know, a text file has no columns.  Please be more specific.  Do you mean something like the 5th word on line 4, where words are separated by a space, and lines are separated by a newline character?  You could the Read from Spreadsheet String function and set the delimiter to a space.  This will produce a 2D array of strings.  Then use index array and give the line number and column number.
    - tbob
    Inventor of the WORM Global

Maybe you are looking for

  • How to deal with "Script stopped responding" in general Part 3

    OK, I have asked about this issue before, and am back because it won't go away. First, I have tried resetting Firefox. Yesterday was the most recent time. I have tried using add-on Script Blockers. The Script Blocker program worked for a while. The p

  • MTO-Subcontracting

    Hi Scenerio: 1. Against saleorder MRP will be done, output will be PR with account assignment cat "M" 2. Subcontracting PO will be created w r t PR (Sucontracting PO will a/c assignt cat "M" and Item cat "L" ) 3. Compoents will be shown at "Sale orde

  • On Flash Player Setting manager(Advanced tab) Active X Version is ok...Plug in Version Not installed

    Please how do I get the Plug in Version? I have only the ActiveX version..11.7.700.169..I need the plugin version..anyone? appreciate

  • Nano and Shuffle read "synced" but aren't.

    Hi, all. I'm a newbie here. I download from two playlists to my Nano (Gen. 4, 16Gb) and to my Shuffle (Gen. 3, 4 or 6 Gb), to keep the categories of music separate. Since upgrading to version 9-point-whatever, both iPods read almost immediately as "S

  • Exporting High Quality Flash to Quicktime for use in FCP4.5

    I am currently working on a interactive DVD production including various Flash animations. I've tried exporting them as almost every possible combination of compressions I could think of using. Every time I import any clip (although seeming smooth in