Read Lines from, JTextArea

Hi there,
I'm trying to save the text from a JTextArea as a file. It all work fine, except the file is written as on long string. Is there any way around this? I was going to read the text line by line, add it to a Vector and then write the file from the Vector, but how do u read just on line from a JTextArea.
All I can find is .getText - but that dosn't do the trick.
ANy suggestions Dukes?

well, yes but the problem is:
I load one .txt file (or similar) into the JTextArea, then u change it round a bit and click on save.
This is when the .getText method comes into play, unfortunately it seems to read the whole area as one string (where line-breaks appears as little black squares).
Is it possibly the FileOutput sequence that's the problem?
(there's no "\n" in the loaded text)

Similar Messages

  • Read lines from text file to java prog

    how can I read lines from input file to java prog ?
    I need to read from input text file, line after line
    10x !

    If you search in THIS forum with e.g. read lines from file, you will find answers like this one:
    Hi ! This is the answer for your query. This program prints as the output itself reading line by line.......
    import java.io.*;
    public class readfromfile
    public static void main(String a[])
    if you search in THIS forum, with e.g. read lines from text file
    try{
    BufferedReader br = new BufferedReader(new FileReader(new File("readfromfile.java")));
    while(br.readLine() != null)
    System.out.println(" line read :"+br.readLine());
    }catch(Exception e)
    e.printStackTrace();
    }

  • I want to read lines from file, count it and extract numbers from a first line.

    i must do un loop?

    HI,
    i try to explain how to use to LABVIEW TOOLS...
    1. USE a for next loop
    2. here you must open the file with the VI. read lines from file.
    you can choos how many lines you read at same time.
    3. the string you can convert into an number.
    4. in the loop is the literal counter... this is you line couter....
    iun schrieb:
    > i must do un loop?

  • Read lines from more than 1 file of different file extensions, extract the data and output to screen

    Hi,
    I am trying to read data from more than one file at once. The files are different types e.g. one is a text file one is an xml file like so, StudentInformation.txt, CollegeInformation.xml. The files are all stored in one place, in this case on the D drive of
    a local computer. I am trying to locate any files in the D drive with a file extension of .txt or of .xml (there may be more than two of these files in the future, so I'm trying to allow for that). Then I want to open all of these files, extract the information
    and output all the information in one display window. I want all the information from these two or more files to be displayed together in the display window.
    Here is the code so far. It is throwing up errors.
            //Load from txt or xml files
            private void btnLoad_Click(object sender, RoutedEventArgs e)
                    IEnumerable<string> fileContents = Directory.EnumerateFiles("D:\\", "*.*", SearchOption.TopDirectoryOnly)
                    .Select(x => new FileInfo(x))
                    .Where(x => x.Extension == ".xml" || x.Extension == ".txt")
                    .Select(file => ParseFile(file));}
                    private string ParseFile(FileInfo file)
                        try
                            using (StreamReader sr = new StreamReader(file.FullName))
                                string line;
                                while ((line = sr.ReadLine()) != null)
                                    //Logic here to determine if this is the correct file and append accordingly
                                    lbDisplay.Items.Add(line);
                                return line;
                        catch (Exception ex)
                            // Let the user know what went wrong
                            MessageBox.Show("The file could not be read: ");
                            MessageBox.Show(ex.Message);
    The error it throws up is:
    Error 1
    'BookList.MainWindow.ParseFile(System.IO.FileInfo)': not all code paths return a value

    This is the Small Basic programming language so moving to a C# forum.
    But you need all paths to return a value, including if an exception is called and it jumps to the catch, perhaps just:
    // Let the user know what went wrong
    MessageBox.Show("The file could not be read: ");
    MessageBox.Show(ex.Message);
    return "";

  • Read lines from a file

    With "ApartmentFileHandler" I can write Apartment-objects to a file and read them from a file.
    To write I loop through each room in the apartment and write its size
    and type. I put 1 Room per line.
    To read I read each line of the file and recreate the room stored
    there. When there are no lines left in the file I pass the Rooms from
    the file to the Apartment constructor and return the new Apartment.
    Only one Apartment is stored in each file. (Apartment doesn?t implement
    Serializable, so I cant write straight Apartment-objects to a file.)
    So in the file, there are stored one "Room" per line: String type,
    double size
    QUESTION: How am I able to read all lines: first line first -> make a new room of
    it, and store to a roomArray? Then second -> do same as I did to the
    first.
    Now my read()-method doesn't read all lines. How to change it to read next line?
    Thanks in advance.
    public class Room extends Space
    public Room(String type, double area)
    public String getType()
    public double getSize()
    public class Apartment extends Space
    public static final String KITCHEN
    public Apartment(Room[] rooms)
    public String getType()
    public double getSize()
    public Room[] getRooms()
    public class ApartmentFileHandler extends Object {
         private FileOutputStream ostream;
         private ObjectOutputStream op;
         private FileInputStream istream;
         private ObjectInputStream ip;
         private String filepath;
    public ApartmentFileHandler (String filepath) {
                              this.filepath = filepath;      
    public Apartment read()
                                      throws InvalidApartmentFile,
                                                 IOException {
          istream = new FileInputStream(filepath);
          ip = new ObjectInputStream(istream);
                                  // count how many rows in the file ie. rooms
                           String lineThatIsRead = ip.readLine();
                           int count =0;                                             
                           while (lineThatIsRead != null) {
                                    count =count +1;
                                    lineThatIsRead =ip.readLine();
         Room room;
         Room roomArray[ ] = new Room[count];
          for(int i =0; i<count; i++) {
                                  String type  =ip.readUTF();
              double size =ip.readDouble();
                                   room =new Room(type, size);
              roomArray[ i ] =room;
                                Apartment apartment = new Apartment(roomArray);
                                return apartment;
            public void write(Apartment apartment)
                  throws IOException {
                    ostream = new FileOutputStream(filepath);
                    op = new ObjectOutputStream(ostream);
                    int numberOfRooms =apartment.getRooms().length;
                    Room[] allRooms =apartment.getRooms();
                    for (int i=0; i< numberOfRooms; i++) {
                         op.writeUTF( allRooms[ i ].getType() );
                         op.writeDouble( allRooms[ i ].getSize() );
                         op.writeChars("\n");

    Hi,
    I recommend using java.io.BufferedReader in conjunction with java.io.FileReader:
    BufferedReader reader=new BufferedReader(new FileReader(filepath));
    java.io.BufferedReader provides the method public java.lang.String readLine() throws java.io.IOException which lets you read a complete line from the underlying java.io.Reader object. Furthermore, BufferedReader will - as the name implies - buffer your IO-operations which will help you improve the program's performance. In order to read all the lines contained in a text file you might want to apply a loop:
    String line;
    while((line=reader.readLine())!=null && line.length()!=0){
    //process data in string line (parse into string and double)
    Of course, everything must be contained within a try-catch-block in order to be able to handle upcoming IOException objects.
    Regards,
    Michael

  • How to write a function read line from a file in FDK?

    Hello,
    I want to write a function that can read a file in line by line in FDK. How do I write it. If FDK could not. Is there any the way? Please help.
    Thank you,
    Thai Nguyen

    Thai,
    You can use the "channel" functions for this. I'm far from an expert on channel programming but I've read files line-by-line successfully by going one character at a time, looking for a carriage return.
    You can open up the file channel with something like:
      ChannelT chan;
      FilePathT *path;
      UCharT ptr[1];
      IntT numRead;
      path = F_PathNameToFilePath("C:\\temp\\mydoc.txt", NULL, FDefaultPath);
      if((chan = F_ChannelOpen(path,"r")) == NULL)
          return;
      //read the first character
      numRead = F_ChannelRead(ptr, sizeof(UCharT), 1, chan);
    ...then you can call F_ChannelRead iteratively to build the string in a buffer, looking for a carriage return (ASCII 13) and stopping there. (that is, ptr[0] == 13).
    There might be a better way. This is just the way I've gotten it to work. It probably is not a good method for unicode files.
    Russ

  • Read lines from file

    Hi. I use buffered reader to read from a file. The file contains a line of strings (04/21/2005 some text bla bla here). Each line ends with a \n, to define that its the end of the line. How can i print this out, so each line is printed on a new line? Suggestions?
    String filename = "someFile.txt";
    BufferedReader infile = new BufferedReader(new FileReader(filename));
    String read;
    while ((read = infile.readLine()) != null)
         //print each line, but how?
    infile.close();

    I was wondering if the \n defines that its "end of
    line" so that all strings between the \n is
    understood as one line.Yes. It may also be \r\n, depending on the platform. It's one of the System properties. line.delimiter, I think.
    Allso, when i print with
    System.out.println(infile); only
    java.io.BufferedReader@691177 is printed. Do I have
    to parse it in any way?No. You normally can't "print" an object. All you'll do is print out the result of the object's toString() method, which usually returns the class name and the object's hash code.
    And you should keep in mind that a File object is only a representation of the file's name. It has no access to the file's contents.

  • Fire an event automatically after reading line from file

    Hi all
    I am writing a programe in which i need to fire an event automatically after reading each line (i.e. on every EOL) from the file.
    Thanks
    jon

    jonhill wrote:
    ..I am writing a programe in which i need to fire an event automatically after reading each line (i.e. on every EOL) from the file.Thanks for sharing that with us. Let us know how it goes. If you have any questions, feel free to ask them.
    BTW - sounds like a very weird requirement.

  • Reading lines from txt doc

    so here is the deal, i have this txt doc that my program is reading from useing he readline() method, now the deal is through that when i print the lines that match i get something that looks like this;
    2 Jeffery Johnson A001 06/14/1978 08/01/2006 402-486-5104 Lincoln NE 68588 1400
    but i want it to look like this
    2
    Jeffery Johnson
    A001
    06/14/1978
    08/01/2006
    402-486-5104
    lincoln
    ne
    68588
    1400
    so i dont know how to format the macthing lines to do this.
    thanks

    Try this for example:
    String [] newText = "Jeffery Johnson A001 06/14/1978 08/01/2006 402-486-5104 Lincoln NE 68588 1400".split (" ");To see what the String array consists off, try this:
        for (int i = 0; i < newText.length; i++)
            System.out.println ("newText[" + i + "] has a value of " + newText);
    }Once you understand how it's working, you will then be able to format your original text in whatever way you want.
    As for the split() method, maybe the use of *split ("\s")* would be better than *split (" ")*. The smarties will know that one better than me.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Reading lines from JEditorPane

    Hi,
    I wonder if there is some way to read text in a JEditorPane line by line. Something like when using BufferedReader when reading from text files. Like method readLine() in BufferedReader?

    I did a bit of searching and haven't found anything that would make this possible

  • Read lines from text-file in specified [ITEM]

    Hello,
    are there any functions integrated in Labview to read a text-file which looks like this:
    [ITEM-NAME_01]
    parameter1 = here
    parameter2 = 1123
    parameter3 = a453
    [ITEM-NAME_02]
    parameter4 = here
    parameter5 = 1123
    parameter6 = a453
    Can this be done easy, or do i have to manually search the file for the "["-character ?
    At the end i want a VI where i pass the file-name and the item-name as input, and as output i want one array with the parameter-names and the other array with the values.
    How can this be done?
    Thanks for your help

    Hi OnlyOne,
    you are talking about Configuration files?
    Look in the file palette, sub-palette "configuration files". It's all in there!
    Best regards,
    GerdW
    CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
    Kudos are welcome

  • Read lines from second sheet from an excel

    i have an excel file with two tab sheets.
    i use this code but it doesnt work correctly. actually it works but for the first tabsheet.
    i want it for the second one only. please help. i wiil reward with points in helpfull answers.
      call method of application 'Worksheets' = sheet
        exporting
          #1 = 2.
      set property of sheet 'Name' = 'Timesheets'.
      call method of sheet 'Activate'.
    CALL METHOD OF gs_chart 'Location'
       EXPORTING
         #1 = 2
         #2 = 'Timesheets'.
      call function 'ALSM_EXCEL_TO_INTERNAL_TABLE'
        exporting
          filename                = p_file
          i_begin_col             = 1
          i_begin_row             = 7
          i_end_col               = 1
          i_end_row               = 60000
        tables
          intern                  = itemp
        exceptions
          inconsistent_parameters = 1
          upload_ole              = 2
          others                  = 3.
      if sy-subrc <> 0.
    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
            WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
      endif.
      clear w_itemp.
      loop at itemp.
        w_itemp = itemp.
        at last.
          w_lin = w_itemp-row.
        endat.
      endloop.

    Hi See following link :
    http://searchsap.techtarget.com/tip/1,289483,sid21_gci868246,00.html?FromTaxonomy=/pr/283958
    Reward points if helpful.
    Regards.
    Srikanta Gope

  • Getting a single line from a JTextArea

    I have a JTextArea with a fixed size. I've used the .setLineWrap(true) and .setWrapStyleWord(true) on this JTextArea, so when the user types in some text, that's longer that the JTextArea, it will wrap unto the next line. I need to get each visible line from the JTextArea. That is not each line of text, that is seperated by a newline (when the user type Enter), but every line, that is visibly seperated in the JTextArea.
    How can i do that.

    The javax.swing.text.Utilities class can help:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    public class TestUtility extends JFrame
         public TestUtility()
              final JTextArea textArea = new JTextArea( "one two three four five", 5, 10 );
              textArea.setLineWrap( true );
              textArea.setWrapStyleWord( true );
              JScrollPane scrollPane = new JScrollPane( textArea );
              getContentPane().add( scrollPane );
              textArea.addCaretListener( new CaretListener()
                   public void caretUpdate(CaretEvent e)
                        int pos = textArea.getCaretPosition();
                        try
                             int start =  Utilities.getRowStart(textArea, pos);
                             int end =  Utilities.getRowEnd(textArea, pos);
                             System.out.println( start + " : " + end );
                        catch (BadLocationException ble) {}
         public static void main(String[] args)
              TestUtility frame = new TestUtility();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setVisible(true);

  • Getting the visible lines from a JTextArea

    I'm using a JTextArea with a fixed size. I've used the setLineWrap(true) and setWrapStyleWord(true) methods on this JTextArea, so when the user types in some text longer than the visible width, it will wrap into the next line. I need to get each visible line from the JTextArea to create a String array of text lines.
    I mean visible text lines (lines visibly separated in the JTextArea), not real text lines separated by a line break character as "\n".
    How can I do this?

    This information is supposed to be contained in the View information of the component. But as far as I can tell it doesn't work for a JTextArea.
    So if you can use a JTextPane then check out the "getWrappedLines" method in this posting:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=608220
    Basically, a View exists for each line in the Document and then each line may have multiple views if the line needs to wrap. So the basic code just count the number of views within each line but you can change the code to get each view separately. Once you have each view you can get the start and end of the text from the document that this View represents.
    Or if you need to use a JTextArea then you can calculate the starting offset of each each line with respect to the model. You can use the viewToModel(..) method to get the starting offset of each line. We know that each line in a text area is a fixed height, so the starting offset of the first line would be modelToView(0, 0); If the line height is 16, then the starting offset of the second line would be modelToView(0, 16), etc. Once you know the starting offset of each line you can subString out the text for each line.

  • How can we get the selected line number from JTextArea ?

    how can we get the selected line number from JTextArea ? and want to insert line/string given line number into JTextArea??? is it possible ?

    Praitheesh wrote:
    how can we get the selected line number from JTextArea ?
    textArea.getLineOfOffset(textArea.getCaretPosition());
    and want to insert line/string given line number into JTextArea??? is it possible ?
    int lineToInsertAt = 5; // Whatever you want.
    int offs = textArea.getLineStartOffset(lineToInsertAt);
    textArea.insert("Text to insert", offs);

Maybe you are looking for

  • How to Reverse Page Order in Acrobat Pro 9

    Hello Community, I thought this would be an easy thing to do in Acrobat but so far I am finding it is not. I am creating a PDF from multiple files, they are jpegs, and I am dragging and dropping them into the "combine files" window in the order I wan

  • Erase to FAT16

    If a SLR camera flash card needs to use FAT16 and be formatted in FAT16 is it possible to do that using Disk Utility or does that only erase in FAT32 format? Currently to format the flash card it needs to be done on a PC. The Mac recognizes FAT16 but

  • Double subfolders with same name

    Hi, I suddenly into Thunderbird (31.4.0) double subfolders with the same name. The mail can not be moved to the folders. Removing conscious folder succeeds. Thunderbird and system then completely stopped and started again. Situation with double subfo

  • X connection to :0.0 host broken (explicit kill or server shutdown)

    Hello All, I strongly believed in using JAVA Swing GUI, for huge data visualization. Now I encounter a problem: I start up my application, and things work very well and looks pretty fast. I try and create a JPanel with is almost 11.3MPixels (just len

  • NFL Redzone coming up "Subscription Required"

     First off I have no stb's. I only have a cablecard.When I go to channel 835 it brings up Subcription required there is no music or splash screen. I've contacted support through chat and it must have been at least 2 hours of sending back and forth fr