Saving a JTextArea string to a file

Hello there, well i have a little problem that i can not figure out. i am creating a swing application that is a text editor. i am new at this so i am reading the api, books etc.. but can not seem to make the application to save. i have followed the format and done it several ways and still i can not make it work. i did notice something that when i initalize the variable JTextArea textArea in the beginning instead of the method initComponent, and by making it static i can write it once, and then open it up and read it. but it mess the application when you save, freezing the window. i am going to attach my code so that you can see what i am doing, please answer as soon as possible i really want this problem to work by now.
import java.io.*;
import javax.swing.*;
public class InternalPanel extends JInternalFrame{
     private static String title = "Untitled ";
     private int width = 400;
     private int height = 300;
     private int x = 15;
     private int y = 15;
     private boolean stateT = true;
     private boolean stateF = false;
     private JScrollPane scroller;
     private JTextArea textArea;
     private static int count;
     public InternalPanel(){
          super(title + (count));               
          initComponent();
     public InternalPanel(File file){
          readerComponent(file);
     private void initComponent(){
          textArea = new JTextArea();
          scroller = new JScrollPane();
          scroller.setViewportView(textArea);
          getContentPane().add(scroller);
          setIconifiable(stateT);
          setMaximizable(stateT);
          setClosable(stateT);
          setResizable(stateT);     
          setSize(width, height);
          setLocation((x * count), (y * count));
          show();
          ++count;
     private void readerComponent(File file){
          initComponent();
          fileReader(file);
     private void fileReader(File file){
          int symblo;
          try{
               FileReader reader = new FileReader(file);
               while((symblo = reader.read()) != -1){
                    textArea.read(reader, this);
                    setTitle(file.getName());
               reader.close();
          }catch(IOException e){
               System.out.println(e);
     public void fileWriter(File file){     
          String context = textArea.getText();
          System.out.println(context);
          try{               
               FileWriter writer = new FileWriter(file);
               writer.write(context);
               writer.flush();
               writer.close();
          }catch(IOException e){
               System.out.println(e);
}

Hello there, well i have a little problem that i can not figure out. i am creating a swing application that is a text editor. i am new at this so i am reading the api, books etc.. but can not seem to make the application to save. i have followed the format and done it several ways and still i can not make it work. i did notice something that when i initalize the variable JTextArea textArea in the beginning instead of the method initComponent, and by making it static i can write it once, and then open it up and read it. but it mess the application when you save, freezing the window. i am going to attach my code so that you can see what i am doing, please answer as soon as possible i really want this problem to work by now.
import java.io.*;
import javax.swing.*;
public class InternalPanel extends JInternalFrame{
     private static String title = "Untitled ";
     private int width = 400;
     private int height = 300;
     private int x = 15;
     private int y = 15;
     private boolean stateT = true;
     private boolean stateF = false;
     private JScrollPane scroller;
     private JTextArea textArea;
     private static int count;
     public InternalPanel(){
          super(title + (count));               
          initComponent();
     public InternalPanel(File file){
          readerComponent(file);
     private void initComponent(){
          textArea = new JTextArea();
          scroller = new JScrollPane();
          scroller.setViewportView(textArea);
          getContentPane().add(scroller);
          setIconifiable(stateT);
          setMaximizable(stateT);
          setClosable(stateT);
          setResizable(stateT);     
          setSize(width, height);
          setLocation((x * count), (y * count));
          show();
          ++count;
     private void readerComponent(File file){
          initComponent();
          fileReader(file);
     private void fileReader(File file){
          int symblo;
          try{
               FileReader reader = new FileReader(file);
               while((symblo = reader.read()) != -1){
                    textArea.read(reader, this);
                    setTitle(file.getName());
               reader.close();
          }catch(IOException e){
               System.out.println(e);
     public void fileWriter(File file){     
          String context = textArea.getText();
          System.out.println(context);
          try{               
               FileWriter writer = new FileWriter(file);
               writer.write(context);
               writer.flush();
               writer.close();
          }catch(IOException e){
               System.out.println(e);
}

Similar Messages

  • Set text of jtextArea to a text file

    I have tried everything in trying to let the user select a text file using jfilechooser and then set the text of a jtextArea as the text file. Nothing has worked so far, so all I have right here is the basic functionality of choosing the file.
    If someone could show me a good way to read the whole text file and put that text into a jtextArea, I would really appreciate it.
    Since nothing has worked all I have is this:
    JFileChooser chooser = new JFileChooser();
         int returnVal = chooser.showOpenDialog(this);
         String getFile = chooser.getSelectedFile().getPath();

    ... followed by theJTextArea.read(new FileReader(getFile), null);

  • Replace String within a file

    i want to replace a string within a file
    there is NO GUI ..
    i take in mind two approaches
    1) hold the file content in memory
    and rewrite the file
    2) write the new data to a new file.
    and then rewrite the original file
    any better ideas

    sorry, no..
    Your idea is kinda right if small file is within existance..
    Small file.
    Why not just use the filereader and filewriter? read the docs upon that
    Large file
    Why wont you create a string buffer, and parse the file chunk by chunk into that buffer one at a time. Then of course you saved the position of the character or word you wanted to apend or write, and you just write it back to that area.

  • Saving the output of a .sql file in .csv format

    Hi,
    I am saving the output of a .sql file in .csv format. But the problem is , the record of few columns have "new line" character in it, so when it is getting saved in .csv format, those records are coming in multiple rows, but they should come in one single row in single block. Please advise how to overcome this problem.
    Regards,
    Niraj

    Hi Guys,
    I guess, there is a misunderstanding.
    He is talking about the issue caused as a result of the data containing a "CRLF" ( Carriage return Line feed ) .
    That is mainly a data issue.
    The query i presume, must be right.
    I guess you should be able to fix it using some string functions.
    Some thing similar to this
    CREATE TABLE ASH (NAME VARCHAR2(10))
    SELECT REPLACE(NAME, CHR(13)||CHR(10), 'ISH') FROM ASH;
    SELECT REPLACE(NAME, CHR(10), 'ISH') FROM ASH;
    SELECT REPLACE(NAME, CHR(13), 'ISH') FROM ASH;
    depending on the type of new line whether it is CR or LF. or CRLF.
    Regards
    Ashish/-

  • Simple question: I want to write JTextArea mylog;  to a File myfile;

    How do I write JTextArea mylog; to a File myfile;

    If you're talking about saving its content as text file, you might use a FileWriter.
    If you want to save the component itself, you should use Object serialization.

  • How to save the content of a JTextArea into a txt file?

    Hi, I want to save the content of a JTextArea into a txt file line by line. Here is part of my code(catch IOException part is omitted):
    String s = textArea.getText();
    File file = new File("file.txt");
    BufferedWriter bw = new BufferedWriter(new FileWriter(file));
    bw.write(s);
    bw.close();
    But I found in the file all is binary code instead of text, any people can help me?
    Thanks in advance

    I can see text in the file now, but the problem is
    when I write three lines in textarea, for example
    111
    222
    333
    then I open the txt file with notepad, it is
    111222333
    How to save them line by line? Use a PrintWriter. It lets you write lines (it's the same class as System.out).
    http://java.sun.com/j2se/1.4/docs/api/java/io/PrintWriter.html

  • Append a string to a file without overwritting.

    OK, let's do this as easy as can be...
    I have a file "A.txt" and its contents is:
    AAAAAAAAAAIf we retreive the File data, its length is 10.
    Now, I have the next code:
    import java.io.*;
    public class MyClass {
        public static void writeToFile(File f, String writeThis, int where) throws IOException, FileNotFoundException {
            RandomAccessFile raf = new RandomAccessFile(f, "rw");
            raf.seek((long)where);
            raf.writeBytes(writeThis);
            raf.close();
        public static void main(String args[]){
            try {
                writeToFile(new File("A.txt"), "java", 3);
            } catch (Exception anyE) {}
    }This is what I want:
    File A.txt contents
    AAAjavaAAAAAAA
       ^ Appended to the fileNow the file data length is 14, 10 A's + java (4)
    This is what I get:
    AAAjavaAAA
       ^ Overwrote the file contents.Now the file data length is still 10, Java overwrote 4 A's.
    How can I append a string to a file at any desired position without overwriting nothing.
    I've checked all java.io package and I found that only RandomAccessFile class allow me to have a file pointer in order to read from there.
    It's important not to append data at the end of the file, I have some tokens there in my app.

    Hi, i am trying to do the same thing. Can u use a randomaccessfile and seek to the pt where u want to insert. save that location. store the data from that pt to the end of the file in a string buffer. then append the string to be inserted at the position u had saved earlier. and then append the string buffer to it. think this should do it. i dont know if it works.
    i had another problem .. i was looking to delete some portion from a file and maintain the continuity. for eg. i have file containing "aaaaajavaaaaaa" and i want to remove java .. from it resulting in "aaaaaaaaaa". is there a easier way to do it. let me know thanks

  • Having trouble converting array to spreadsheet string, storing the file and coverting back to array with complex numbers

    I am working with a network analyzer. I have arrays made of 5 columns the first consisting of an integer and the next four consisting of complex numbers. I am converting the array into a spreadsheet string and then saving the file using the write characters to a file VI. That seems to work well as when I open the file in Excel all the data is there. However when I try to reverse the process, open file and convert back to array, I loose some of the data. Specifically the imaginary parts of my complex numbers are all going to zero. I have narrowed down the problem to be in the conversion from spreadsheet string to array and vice versa. I
    think the problem may be with the 'format' input to the VI. I do not have an adequate resource for this so I am not sure what to put in to accomplish my task. Any takers?

    Hi Biz
    I don't think there is a direct way of converting a complex number to a
    string, so when you convert the array to a spreadsheet string, the
    numbers would be converted to real data.
    However, you could try separating the real and imaginary parts using the
    "Numeric: Complex to Re/Im" function, and then store these - either in
    separate files or in adjacent columns/rows in the same file. Then, when
    you read in the data again, use the "Numeric: Re/Im to Complex" function
    to put the two "halves" together.
    If you actually want Excel to interpret the numbers as imaginary, then
    you'll probably want to create a string for each complex number of the
    form "Re + Im*i" (after separating the Re and Im parts), by using
    "String:Format into String" with 2 numeric inputs and the format string
    "%f+%fi".
    Reading the data back into Labview then would require splitting the
    string into the 2 pieces by using "Stringcan from String" with 2
    numeric outputs (smae precision as original numbers specified by the 2
    Default Value inputs) and the same format string "%f+%fi", and then using
    the above-mentioned "Numeric: Re/Im to Complex" function. It worked for
    me, so if you can't follow what I am describing, send me an email and I
    can email you what I did (LV 5.1.1).
    Paul
    Biz wrote:
    > Having trouble converting array to spreadsheet string, storing the
    > file and coverting back to array with complex numbers
    >
    > I am working with a network analyzer. I have arrays made of 5 columns
    > the first consisting of an integer and the next four consisting of
    > complex numbers. I am converting the array into a spreadsheet string
    > and then saving the file using the write characters to a file VI. That
    > seems to work well as when I open the file in Excel all the data is
    > there. However when I try to reverse the process, open file and
    > convert back to array, I loose some of the data. Specifically the
    > imaginary parts of my complex numbers are all going to zero. I have
    > narrowed down the problem to be in the conversion from spreadsheet
    > string to array and vice versa. I think the problem may be with the
    > 'format' input to the VI. I do not have an adequate resource for this
    > so I am not sure what to put in to accomplish my task. Any takers?
    Research Assistant
    School of Physiotherapy, Curtin University of Technology
    Selby Street, Shenton Park, Western Australia, Australia. 6008
    email: [email protected]
    Tel. +61 8 9266 4657 Fax. +61 8 9266 3699
    "Everyone who calls on the name of the Lord will be saved." Romans 10:12
    "For all have sinned and fall short of the glory of God, and are
    justified freely by his grace through the redemption that came by Christ
    Jesus." Romans 3:23-4

  • How to search a special string in txt file and return it's position in txt file?

    How to search a special string in txt file and return it's position in txt file?

    I just posted a solution for a similar question here:  http://forums.ni.com/ni/board/message?board.id=170​&view=by_date_ascending&message.id=362699#M362699
    The top portion can search for the location of a string, while the bottom portion is to locate the position of a character.  Both can search for a character.
    The position of the character within the file is displayed in the indicator(s).
    R

  • Search and replace strings in a file while ignoring substrings

    Hi:
    I have a java program that searches and replaces strings in a file. It makes a new copy of the file, searches for a string in the copy, replaces the string and renames the new copy to the original file, thereafter deleting the copy.
    Now searching for "abcd", for eg works fine, but searching for "Topabcd" and replacing it doesnot work because there is a match for "abcd" in a different search scenario. How can I modify the code such that if "abcd" is already searched and replaced then it should not be searched for again or rather search for "abcd" as entire string and not if its a substring of another string.
    In the below code output, all instances of "abcd" and the ones of "Topabcd" are replaced by ABCDEFG and TopABCDEF respectively, whereas according to the desired output, "abcd" should be replaced by ABCDEFG and "Topabcd" should be replaced by REPLACEMEFIRST.
    try
              String find_productstring = "abcd";
              String replacement_productstring = "ABCDEFG";
              compsXml = new FileReader(compsLoc);
              compsConfigFile = new BufferedReader(compsXml);
              File compsFile =new File("file.xml");
              File compsNewFile =new File("file1.xml");
              BufferedWriter out =new BufferedWriter(new FileWriter("file1.xml"));
              while ((compsLine = compsConfigFile.readLine()) != null)
                    new_compsLine =compsLine.replaceFirst(find_productstring, replacement_productstring);
                    out.write(new_compsLine);
                    out.write("\n");
                out.close();
                compsConfigFile.close();
                compsFile.delete();
                compsNewFile.renameTo(compsFile);
            catch (IOException e)
            //since "Topabcd" contains "abcd", which is the search above and hence the string "Topabcd" is not replaced correctly
             try
                   String find_producttopstring = "Topabcd";
                   String replacement_producttopstring = "REPLACEMEFIRST";
                   compsXml = new FileReader(compsLoc);
                   compsConfigFile = new BufferedReader(compsXml);
                   File compsFile =new File("file.xml");
                   File compsNewFile =new File("file1.xml");
                   BufferedWriter out =new BufferedWriter(new FileWriter("file1.xml"));
                   while ((compsLine = compsConfigFile.readLine()) != null)
                         new_compsLine =compsLine.replaceFirst(find_producttopstring, replacement_producttopstring);
                         out.write(new_compsLine);
                         out.write("\n");
                     out.close();
                     compsConfigFile.close();
                     compsFile.delete();
                     compsNewFile.renameTo(compsFile);
                 catch (IOException e)
            }Thanks a lot!

    Hi:
    I have a java program that searches and replaces
    strings in a file. It makes a new copy of the file,
    searches for a string in the copy, replaces the
    string and renames the new copy to the original file,
    thereafter deleting the copy.
    Now searching for "abcd", for eg works fine, but
    searching for "Topabcd" and replacing it doesnot work
    because there is a match for "abcd" in a different
    search scenario. How can I modify the code such that
    if "abcd" is already searched and replaced then it
    should not be searched for again or rather search for
    "abcd" as entire string and not if its a substring of
    another string.
    In the below code output, all instances of "abcd" and
    the ones of "Topabcd" are replaced by ABCDEFG and
    TopABCDEF respectively, whereas according to the
    desired output, "abcd" should be replaced by ABCDEFG
    and "Topabcd" should be replaced by REPLACEMEFIRST.
    try
    String find_productstring = "abcd";
    String replacement_productstring = "ABCDEFG";
    compsXml = new FileReader(compsLoc);
    compsConfigFile = new
    BufferedReader(compsXml);
    File compsFile =new File("file.xml");
    File compsNewFile =new File("file1.xml");
    BufferedWriter out =new BufferedWriter(new
    FileWriter("file1.xml"));
    while ((compsLine =
    compsConfigFile.readLine()) != null)
    new_compsLine
    =compsLine.replaceFirst(find_productstring,
    replacement_productstring);
    out.write(new_compsLine);
    out.write("\n");
    out.close();
    compsConfigFile.close();
    compsFile.delete();
    compsNewFile.renameTo(compsFile);
    catch (IOException e)
    //since "Topabcd" contains "abcd", which is
    the search above and hence the string "Topabcd" is
    not replaced correctly
    try
                   String find_producttopstring = "Topabcd";
    String replacement_producttopstring =
    topstring = "REPLACEMEFIRST";
                   compsXml = new FileReader(compsLoc);
    compsConfigFile = new
    gFile = new BufferedReader(compsXml);
                   File compsFile =new File("file.xml");
                   File compsNewFile =new File("file1.xml");
    BufferedWriter out =new BufferedWriter(new
    dWriter(new FileWriter("file1.xml"));
    while ((compsLine =
    compsLine = compsConfigFile.readLine()) != null)
    new_compsLine
    new_compsLine
    =compsLine.replaceFirst(find_producttopstring,
    replacement_producttopstring);
    out.write(new_compsLine);
    out.write("\n");
    out.close();
    compsConfigFile.close();
    compsFile.delete();
    compsNewFile.renameTo(compsFile);
                 catch (IOException e)
    Thanks a lot!I tried the matches(...) method but it doesnt seem to work.
    while ((compsLine = compsConfigFile.readLine()) != null)
    if(compsLine.matches(find_productstring))
         System.out.println("Exact match is found for abcd");
         new_compsLine =compsLine.replaceFirst(find_productstring, replacement_productstring);
    out.write(new_compsLine);
    out.write("\n");
         else
         System.out.println("Exact match is not found for abcd");
         out.write(compsLine);
         out.write("\n");

  • Conversion of xml string to xml file

    To convert xml string to xml file in java i used
    Document XMLDoc=DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader("<root><main>Title</main></root&g t;")));
    But it is showing an error as InputSource cannot be resolved
    How to rectify this

    I assume you mean there is a compiler error? (It helps if you explain your problem instead of just giving a vague description of it.) It sounds like you have to import InputSource. You do know about the import statements that go at the beginning of a Java class, don't you?

  • How to convert RAW files that saved in UCCX server to wav file?

    Hi all,
    How we can covert the RAW files that are saved in UCCX server to wav file by using command prompt in UCCX servers. Or is there some other way? So that we should be able to hear the sound of these files.
    C:\Program Files\Cisco\Desktop_Audio
    Regards
    Ali Raza

    Hi,
    I use Switch File Audio Convertor from NCH Software to do this.
    It is a commercial product but there is a time limited evaluation and if you decide to keep it it is only $30.
    http://www.nch.com.au/switch/index.html
    It is great for converting audio files to the correct format for music on hold as well.

  • How to save string in a file with special-chars

    Hello,
    i´m usingthe MD5-llb to create a password.
    Then i  want to save this MD5-string to a file and later read it back abd compare.
    Works perfect with one proplem:
    Some word create a "\r" in the MD5-string and when i save this string to a file and read it back then its read back as a "\n" so that the compare is not working.
    My question is: How can i save a string exactly like it is to somewhere and read it back (also invisible chars)
    For example the word: heinz
    is in MD5: \r\FB^\07\A6\07T\C7\D9\C2\94\AB\C9\1DS\95 (string indicator as codes display)
    when i save the string to a file then i rerad back: \n\FB^\07\A6\07T\C7\D9\C2\94\AB\C9\1DS\95
    I used the "write text file" and "read text file"
    What do i have to use to save and read the same?
    Thx
    Solved!
    Go to Solution.

    I believe an MD5 hash is 16 bytes long. Use the binary read and write file I/O functions and specify the length of the data to be read or written.
    Now is the right time to use %^<%Y-%m-%dT%H:%M:%S%3uZ>T
    If you don't hate time zones, you're not a real programmer.
    "You are what you don't automate"
    Inplaceness is synonymous with insidiousness

  • "The document 'Backup of Backup of Oral Report' could not be saved as 'Oral Report'. Bad file descriptor"

    Hello,
    Whenever I try to save my Keynote file, I receive an error message saying: "The document 'Backup of Backup of Oral Report' could not be saved as 'Oral Report'. Bad file descriptor".
    I've tried using other name to save my file, saving the file as a backup, saving it within my documents, and on a USB, but the file won't save. I'm using Keynote '09, Version 5.1.1 (1034) on my Mac Desktop running Mac OS X Version 10.6.8
    How can I fix this problem and save my file?

    change icloud backup to local backup on this compuet. this worked for me.

  • Problem in outputting a string into a file

    Hi guys,
    I tried to output a string to a file. The string is 'Size : 30u201D X 13 ½u201D X17 ¾u201D(H)'.
    However, with this code :
    l_file = '/erp/reports/testgk.txt'.
    l_str = 'Size : 30u201D X 13 ½u201D X17 ¾u201D(H)'.
    OPEN DATASET l_file FOR OUTPUT IN TEXT MODE ENCODING DEFAULT.
    TRANSFER l_str TO l_file.
    It returned me a weird string: 'Size : 30M-bM-@M-] X 13 M-BM-=M-bM-@M-] X17 M-BM->M-bM-@M-](H)'
    Would you please let me know how to solve this problem?
    Thanks, gk

    Hello gk,
    I tried this code & works fine for me though:
    DATA: v_data TYPE string VALUE ' 30u201D X 13 ½u201D X17 ¾u201D(H)',
          v_file TYPE string VALUE
                  '\glbwi720InterfaceID2100I_MB_207INsdn.txt'.
    OPEN DATASET v_file FOR OUTPUT
    IN TEXT MODE
    ENCODING DEFAULT.
    IF sy-subrc = 0.
      TRANSFER v_data TO v_file.
      CLOSE DATASET v_file.
    ENDIF.
    Looks like the "usual" ENCODING problem
    BR,
    Suhas

Maybe you are looking for