How to save a UTF-8 encoded text file ?

hi People
I have a little script which reads the source text from a layer and saves it to a .txt file. This is on a Mac and all was good until recently when I tried opening the .txt file on a PC in Notepad and found my ˚ degree symbols all whack.
Resaving the .txt file in TextEdit as Unicode (UTF-8) encoding solved the problem, now opens fine in Notepad.
But ideally I'd like the script to output the .txt as UTF-8 in the first place. It's currently Western (Mac OS Roman). I've tryed adding in myfile.encoding = "UTF8" but the resulting file is still Western (and the special charaters have wigged out again)
any help greatly appreciated../daniel
    var theComp = app.project.activeItem;
    var dataRO = theComp.layer("dataRO").sourceText;
    // prompt user to save file
    var theFile = new File ("~/Desktop/"+ theComp.name + "_output.txt");
    theFile = theFile.saveDlg("Save an ASCII export file.");
    if (theFile != null) {          // check user didn't cancel dialog
        theFile.lineFeed = "windows";
        //theFile.encoding = "UTF8";
        theFile.open("w","TEXT","????");
        theFile.writeln("move details:");
        theFile.writeln(dataRO.value.toString());
    theFile.close();

Hi,
Got it, it seems, the utf-8 standard use 2-bytes (and more) encoding on accents and special characters.
I found some info there with some code http://ivoronline.com/Coding/Theory/Tutorials/Encoding%20-%20Text%20-%20UTF%208.php
However there was some error so I fixed it. (However for 3 and 4 bytes characters i didnt test it. So maybe you'll have to change back the 0xbf to 0x3f or something else.)
So here is the code.
Header 1
function convertCharToUTF(character){
    var utfBytes = "";
    c = character.charCodeAt(0)
    if (c < 0x80) {
        utfBytes =  String.fromCharCode (c);
    else if (c < 0x800) {
        utfBytes =  String.fromCharCode (0xC0 | c>>6);
        utfBytes +=  String.fromCharCode (0x80 | c & 0xbF);
    else if (c < 0x10000) {
        utfBytes = String.fromCharCode (0xE0 | c>>12);
        utfBytes += String.fromCharCode (0x80 | c>>6 & 0xbF);
        utfBytes += String.fromCharCode (0x80 | c & 0xbF);
    else if (c < 0x200000) {
        utfBytes += String.fromCharCode (0xF0 | c>>18);
        utfBytes += String.fromCharCode (0x80 | c>>12 & 0xbF);
        utfBytes += String.fromCharCode (0x80 | c>>6 & 0xbF);
        utfBytes =+ String.fromCharCode (0x80 | c & 0xbF);
        return utfBytes
function convertStringToUTF(stringToConvert){
    var utfString = ""
    for (var i = 0 ; i < stringToConvert.length; i++){
        utfString = utfString + convertCharToUTF(stringToConvert.charAt (i))
    return utfString;
var theFile= new File("~/Desktop/_output.txt");
theFile.open("w", "TEXT");
theFile.encoding = "BINARY"
theFile.linefeed = "Unix"
theFile.write("");//or theFile.write(String.fromCharCode (0xEF) + String.fromCharCode (0xEB) + String.fromCharCode (0xBF)
theFile.write(convertStringToUTF("Your stuff éàçËôù"));
theFile.close();

Similar Messages

  • How to save the RichTextBox Content in Text file

    hI ,
    I NEED TO SAVE THE RichTextBox Content in text file ? 

    If this IS a LabVIEW question, here's an example of how to load a rich text file (to help if you don't know how to get a rich text in LabVIEW).
    If you have a Rich Text Box, you can use the invoke method "SaveFile" to match the function you linked to.

  • How to read UTF-8 encoded text file randomly?

    I am trying to read a text file which has been encoded in UTF-8. The problem is that I need to access the file randomly. The RandomAccessFile is a low-level class and there seems to be no-way to wrap it in InputStreamReader so that UTF-8 encoding can be done on-the-fly. Is there any easy way to do that. Below is the simplified version of my program.
    import java.io.*;
    public class Test{
            public Test(String filename){
                    try{
                            RandomAccessFile rafTemIn = new RandomAccessFile(new File(filename), "r");
                            while(true){
                                    char chr = rafTemIn.readChar();
                                    System.err.println(chr);
                    } catch (EOFException e) {
                            System.err.println("File read.");
                    } catch (IOException e) {
                            System.err.println("File input error");
            public static void main(String[] args){
                    Test t= new Test("template.idx");
    }

    The file that I am going to read could be few hundreds of MBs or GBs. Hence, I will index interesting items in the file. The index file contain the keyword and the byte offset in the file. So, I will need to seek to any byte to read it. The file could be UTF-8 encoded XML or UTF-8 encoded plain text.
    Also, would like to add-up that in the sample program above I am reading the file sequentially. The concerned class has another method which actually does the reading randomly. If this helps, I am pasting the simplified version of code again but this also includes the said method.
    import java.io.*;
    public class Test{
            long bloc;
            long eloc;
            RandomAccessFile rafTemIn;
            public Test(String filename){
                    bloc=0L;
                    eloc=0L;
                    try{
                            rafTemIn = new RandomAccessFile(new File(filename), "r");
                            while(true){
                                    char chr = rafTemIn.readChar();
                                    System.err.println(chr);
                    } catch (EOFException e) {
                            System.err.println("File read.");
                    } catch (IOException e) {
                            System.err.println("File input error");
            public String getVal(String templateName){
                    String stemval=null;
                    try {
                            rafTemIn.seek(bloc); //bloc is a long value for beginng location to read from. It changes.
                            byte[] b = new byte[(int)(eloc - bloc + 1L)];
                            rafTemIn.read(b,0,(int) (eloc - bloc + 1L));
                            stemval = new String(b,"UTF-8");
                    } catch(IOException eio) {
                            System.err.println("Template Dump file IO error.");
                    return stemval;
            public static void main(String[] args){
                    Test t= new Test("template.idx");
                    System.out.println(t.getVal("wikipedia"));
    }

  • How to save changes back into binary text file

    I have a repository with a single binary field that contains an HTML file
    I have a pageflow with a form where users can edit content, including the contents of the HTML file.
    Can I just treat that like any other property:
    If the name of my binary field containing an HTML file is “file”
    Can I just treat it like any other field in the repository and do :
    <pre>
    try{
    properties = node.getProperties();
    properties[0] = new Property("title",new Value(form.title));
    properties[1] = new Property("description",new Value(form.description));
    properties[2] = new Property("file",new Value(form.contentText));
    properties[3] = new Property("author",new Value(form.author));
    node.setProperties(properties);
    String title = form.title;
    nodeId = node.getId();
    title = node.getProperty("title").getValue().toString();
    } catch(Exception e){
    e.printStackTrace();
    error = "error1";
    RepositoryManager manager = null;
    try{
    manager = RepositoryManagerFactory.connect();
    NodeOps nodeOps = manager.getNodeOps();
    nodeOps.updateProperties(nodeId, properties);
    } catch(Exception e){
    error += "error2";
    e.printStackTrace();
    </pre>
    Thanks much.

    I have a repository with a single binary field that contains an HTML file
    I have a pageflow with a form where users can edit content, including the contents of the HTML file.
    Can I just treat that like any other property:
    If the name of my binary field containing an HTML file is “file”
    Can I just treat it like any other field in the repository and do :
    <pre>
    try{
    properties = node.getProperties();
    properties[0] = new Property("title",new Value(form.title));
    properties[1] = new Property("description",new Value(form.description));
    properties[2] = new Property("file",new Value(form.contentText));
    properties[3] = new Property("author",new Value(form.author));
    node.setProperties(properties);
    String title = form.title;
    nodeId = node.getId();
    title = node.getProperty("title").getValue().toString();
    } catch(Exception e){
    e.printStackTrace();
    error = "error1";
    RepositoryManager manager = null;
    try{
    manager = RepositoryManagerFactory.connect();
    NodeOps nodeOps = manager.getNodeOps();
    nodeOps.updateProperties(nodeId, properties);
    } catch(Exception e){
    error += "error2";
    e.printStackTrace();
    </pre>
    Thanks much.

  • How to save the data present in TEXT BOX?

    Hi friends i am able to create a text editor in one of my screen but i want to know how to save the data when the text is entered in that text box and retrive when they open the screen?

    Hi ,
    Please check the format below since it is based on a working code
    first you need to create a text in s010 function module...
    there should be some key based on which you plan to save the text..imagine it is Purchase order then..PO+item numner is always unique.eg:0090010(900PO/item10).so in the code you can append these two and they will be unique..so you can always retrieve them,overwrite,save them anytime you need
    **************data declarations
    TYPES: BEGIN OF TY_EDITOR,
    EDIT(254) TYPE C,
    END OF TY_EDITOR.
    data: int_line type table of tline with header line.
    data: gw_thead like thead.
    data: int_table type standard table of ty_editor.
    ****************fill header..from SO10 t-code..when you save you need the unique key..youfill it here and pass it in save_text function module
    GW_THEAD-TDNAME = loc_nam. " unique key for the text -> our unique key to identify the text
    GW_THEAD-TDID = 'ST'. " Text ID from SO10
    GW_THEAD-TDSPRAS = SY-LANGU. "current language
    GW_THEAD-TDOBJECT = 'ZXXX'. "name of the text object created in SO10
    *To Read from Container and get data to int_table
    CALL METHOD EDITOR ->GET_TEXT_AS_R3TABLE
    IMPORTING
    TABLE = int_table
    EXCEPTIONS
    ERROR_DP = 1
    ERROR_CNTL_CALL_METHOD = 2
    ERROR_DP_CREATE = 3
    POTENTIAL_DATA_LOSS = 4
    others = 5.
    IF SY-SUBRC 0.
    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    ENDIF.
    loop data from int_table and save to int_line-tdline appending it.
    *save the text
    CALL FUNCTION 'SAVE_TEXT'
    EXPORTING
    HEADER = GW_THEAD
    TABLES
    LINES = InT_LINE
    EXCEPTIONS
    ID = 1
    LANGUAGE = 2
    NAME = 3
    OBJECT = 4
    OTHERS = 5.
    IF SY-SUBRC 0.
    ENDIF.
    *To pass to Container
    CALL METHOD EDITOR ->SET_TEXT
    hope that the above sample with helps you solve the problem
    Please check and revert,
    Reward if helpful
    Regards
    Byju

  • How to save Internal table as a local file?

    Hi,
    How to save Interanl table as a local file ?
    I had some data which i had selected in Interanl table and would like to send this as an attachment by attaching internal table contents as a local file--

    Hi friend,
    See sample code for GUI_DOWNLOAD.
    *Types
    TYPES: BEGIN OF g_r_mara,
           matnr LIKE mara-matnr,
           ersda LIKE mara-ersda,
           laeda LIKE mara-laeda,
           mtart LIKE mara-mtart,
           mbrsh LIKE mara-mbrsh,
           END OF g_r_mara.
    *Data
    DATA: g_t_mara TYPE TABLE OF g_r_mara,
          filename TYPE string.
    *Tables
    TABLES: mara, sscrfields.
    *Selection Screen
    SELECT-OPTIONS: s_matnr FOR mara-matnr.
    SELECTION-SCREEN BEGIN OF LINE.
    *SELECTION-SCREEN COMMENT 10(20) text-001 FOR FIELD p1.
    SELECTION-SCREEN PUSHBUTTON 12(20) word USER-COMMAND uc.
    SELECTION-SCREEN END OF LINE.
    *Initilizing data.
    INITIALIZATION.
      word = 'word'.
      filename = 'C:\Testing.doc'.   <------- File name and location
    AT SELECTION-SCREEN.
      CASE sscrfields-ucomm.
        WHEN 'UC'.
    *Data retrival
          SELECT matnr ersda laeda mtart mbrsh
            INTO  CORRESPONDING FIELDS OF TABLE g_t_mara
            FROM mara
            WHERE matnr IN s_matnr.
    *Downloading data from internal table to excel
          CALL FUNCTION 'GUI_DOWNLOAD'
            EXPORTING
              filename              = filename
              filetype              = 'ASC'
              write_field_separator = 'X'
            TABLES
              data_tab              = g_t_mara.
      ENDCASE.
    (Note: Downloaded file is in C:\Testing.doc)
    You can change the file format by changing the extension in filename.
    Might helpful for u.
    Thanks..

  • How to read the content of a text file (by character)?

    Guys,
    Good day!
    I'm back just need again your help. Is there anyone knows how to read the content of a text file not by line but by character.
    Please help me. Thank you so much in advance.
    Jojo

    http://java.sun.com/javase/6/docs/api/index.html
    package java.io
    InputStream.read(): int
    Reads the next byte of data from the input stream.
    Implementation:
    InputStreamReader
    An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset. The charset that it uses may be specified by name or may be given explicitly, or the platform's default charset may be accepted.

  • How to get summary columns in delimited text file

    How to get summary columns in delimited text file
    I am trying to generate a delimited text file output with delimited_hdr = no.The report is a Group above report with summary columns at the bottom.In the text file the headers are not getting repeated & thats ok.The problem is the summary data is getting repeated for each row of data.Is there a way where i will get all the data & summary data will get displayed only once.I have to import the delimited text file in excel spreadsheet.

    Sorry there were a typos :
    When I used desformat=DELIMITEDDATA with desttype=FILE, I get error "unknown printer driver DELIMITEDDATA". When you look for help, DELIMITED is not even listed as one of the values for DESTFORMAT. But if you scroll down and look for DELIMITER it says , this works only in conjuction with DESTFORMAT=DELIMITED !!!!!!??!! This is in 9i.
    Has this thing worked for anybody ? Can anyone please tell if they were able to suppress the sumary columns or the parent columns of a master-detail data for that matter ?

  • How do i split content from the text file using tab and spaces...?

    Hi.. Just want to ask help to all the experts. Im new in java and i have this problem on how to split the contents of the text file. ill show you the contents in order to let you see what i mean.
    FileName: COL.txt
    AcctNo AcctName Primary Secondary Status Opendate
    121244 IPI Company Noel Jose Active 12/05/2007
    As you can see the content i want to split it per column.. Please help me

    Jose_Noel wrote:
    Hi prometheuzz,
    What do you mean by one thread...?You created two threads* with the same question in it. That way, people might end up giving you an answer that has already been posted in your other thread: thus wasting that person's time.
    Just don't create multiple threads with the same question please.
    * a thread is a post here at the forum

  • Linux server(how to save command out put to another file. )

    hi all,
    i have Q ?
    how to save command out put to another file.
    Ex: #ps -ef
    that particular cmd output i need to save another file.
    is it possible ...if possible ..please let me know
    And how to save command history in Linux.

    df -h >> /oracle/output.log
    /oracle -- mount point name
    Regards
    Asif Kabir

  • ANYBODY KNOW how to save a swatch in an ID file at a percentage?

    ANYBODY KNOW how to save a swatch in an ID file at a percentage?
    So that every time it's used, it applies that percentage automatically?

    LOL...nevermind. Took me 2 seconds to realize all I needed to do after posting this. Sad trombone.

  • How can I save an email as a text file before deleting from it my inbox?

    Some emails I want to save to my computer so that i can view them without opening up my email. I used to be able to do this by saving to a documents folder as a text file. (Outlook express). I do not find this capablity in Thunderbird. if it is there, I have not found it.

    '''File|Save As''' gives you several options. By default it will save as a .eml file, which will need an email client to view. You can usually save by drag-and-drop, but that creates an .eml file too.
    You can save as HTML by putting in an html file extension when doing File|Save As.
    This add-on:
    https://nic-nac-project.org/~kaosmos/mboximport-en.html
    gives you multiple options for saving one or more messages in various formats.

  • NEED HELP! How do I export UTF-8 encoded HTML to PDF?

    Right now my HTLM to output is in Japanese, and encoded in UTF-8 format.
    I tried to use html_entity_decode(), however that does not work, all I get are a bunch of weird characters.
    If anyone have any experience with exporting UTF-8 encoded HTML in Japanese or any foreign glyph-like language to PDF, please help me on this.

    Ellis home wrote:
    In File/Document Setup do you have bleed set to 0?
    Yeah.
    [Jongware] wrote:
    What are 'the obvious export settings'? You are looking at these as well?
    Right. Export > Marks and Bleeds. (I was posting from my phone and couldn't check InDesign to see what it was called.) Those are my settings, at any rate.
    With its default settings, there are no 'blue' bleed lines. You may have changed its color (this can be done in Preferences), or you may mistake the default Purple of margins for blue, or you may mistake any empty frame for 'bleed' (as the default 'new layer' color is blue). Or maybe someone did draw a blue frame to act as 'Bleed' -- but calling it that is not going to work. InDesign can only use its own kind of Bleed, the one you set up in Page Size, that displays outside of the Document Page, and that you can switch off in the PDF Export dialog
    Sorry, I was wrong about about the colour, too. I need it to be cropped to the line I have circled in red - it's the innermost border.

  • How to read some lines from a text file using java.

    hi,
    i m new to java and i want to read some lines from a text file based on some string occurrence in the file. This file to be read in steps.
    we only want to read the file upto the first Occurrence of "TEXT" string.
    How to do it ,,,
    Kinldy give the code
    Regards,
    Sagar
    this is the text file
    dfgjdjj
    sfjhjkd
    ghjkdg
    hjkdgh TEXT
    ikeyt
    ujt
    jk
    tyk TEXT
    rukl
    r

    Hendawy wrote:
    Since the word "TEXT" is formed of 4 letters, you would read the text file 4 bytes by four bytes. Wrong on two counts. First, the file may not be encoded 1 byte per character. It could be utf-16 in which case it would be two byte per character. Second, even if it were 1 byte per character, the string "Text" may not start on a 4 byte boundary.
    Consider a FileInputStream object "fis" that points to your text file. use fis.read(byte[] array, int offset, int len) to read every four bytes. Convert the "TEXT" String into a byte array "TEXT".getBytes(), and yous the Arrays class to compare the equality of the read bytes with your "TEXT".getBytes()Wrong since it relies on my second point and will fail when fis.read(byte[] array, int offset, int len) does not read 4 bytes (as is no guaranteed to). Check the Javadoc. Also, the file may not be encoded with the default character encoding.
    The problem is easily solved by reading a line at a time using a BufferedReader wrapping an InputStreamReader wrapping a FileInputStream and specifying the correct character encoding.
    Edited by: sabre150 on Apr 29, 2009 2:13 PM

  • How do you read data from a text file into a JTextArea?

    I'm working on a blogging program and I need to add data from a text file named messages.txt into a JTextArea named messages. How do I go about doing this?

    Student_Coder wrote:
    1) Read the file messages.txt into a String
    2) Initialize messages with the String as the textSwing text components are designed to use Unix-style linefeeds (\n) as line separators. If the text file happens to use a different style, like DOS's carriage-return+linefeed (\r\n), it needs to be converted. The read() method does that, and it saves the info about the line separator style in the Document so the write() method can re-convert it.
    lethalwire wrote:
    They have 2 different ways of importing documents in this link:
    http://java.sun.com/docs/books/tutorial/uiswing/components/editorpane.html
    Neither of those methods applies to JTextAreas.

Maybe you are looking for