Reg Exp help needed (trouble with line breaks)

Hello,
I am attempting to parse a line of text with regular expressions. I am having difficulty with the line breaks.
I want to divide the following line by the first '\n' char.
For instance, I wan the output to be as follows:
found 1: one
found 2: ddd
dddHowever, I get the following with my attached code:
found 1: one
found 2: dddHowever, the second line break seems to be the end of the second group.
How do I get the any character '.' to read past any subsequent line breaks?
import java.util.regex.*;
public class Test
     String rawSequenceArg = ">one\nddd\nddd";     
       Pattern p = Pattern.compile(">([^\n]+)\n(.+)");
       Matcher m = p.matcher(rawSequenceArg);
       if(m.find())
            System.out.println("found 1: " + m.group(1));
            System.out.println("found 2: " + m.group(2));
}

In this case, the DOTALL flag is the one you need; it allows the dot (period, full stop) to match line separator characters. MULTILINE makes the '^' and '$' anchors match the beginning and end of logical lines, instead of just the beginning and end of the input.

Similar Messages

  • Applescript batch convert .RTF to .TXT with line breaks

    Hey guys, looking for help with an Applescript that can change a .RTF to a .TXT with line breaks.
    I have an Applescript that will go from a .DOC to a plain .TXT but haven't found anything to get from the .RTF to a .TXT wth line breaks.
    I'm doing this for Avid's Script Sync.
    Thanks for the help.

    Ok, you obviously mean something specific by "line breaks" that you're not being clear about.  are you looking for a specific kind of line ending: Mac style carriage return (CR) ending? Windows style carriage return line feed (CR/LF) endings, unix style line feed (LF) endings?  textutil provides LF by default (it's a unix utility after all); if you need a different line ending you'll need to pipe it through tr or modify it via applescript after you've done the conversion

  • Applescript batch convert DOC to TXT with line breaks

    Hey guys, I recently got stuck at work having to convert over 1,000 DOC files to TXT files with line breaks.
    I've found online several different Applescripts that work great at converting DOC files to TXT files but I can't find one that will do the TXT files with line breaks.
    If anyone has a script that can do this I would be crazy grateful.
    Converting these one by one with Word is taking forever to do.
    Thanks for any help you can give me.

    Excuse me for a moment for speaking harshly to you.  You are causing yourself utterly unnecessary headaches by not being clear with us and not stopping to think, and it's high time you learned that that is an incorrect way to approach anything on a computer.  Consider:
    you don't know what you're doing (in the sense that you don't know what 'text with line breaks' means)
    you don't know (or at least haven't explained) why this needs to be done
    (therefore) you don't know if this needs to be done at all
    (and yet) you are doing it anyway, in a mindlessly repetitive fashion, driving yourself batty and irritating me
    At least for the time being, humans are the ones who think and computers the ones who grunt away mindlessly; try to reverse those roles and everything gets done badly and slowly. Stop, look, think, plan ahead - that's what your brain is good at if you give it a chance.
    Now, as far as I can tell from poking around the web, 'text only with line breaks' means that the document  is saved as a plain-text file, but with a carriage return linefeed combination (CR/LF) as a paragraph delimiter (this is a Windows format - unix uses a single linefeed, Macs might use a single carriage return or a single linefeed). I don't know why anyone would want that format - most software will convert that seamlessly (or at least can be told to convert that).  Are you trying to feed this into some dinosaur of a database?  At any rate, if that's what you want, this script should do it. caution, this script overwrites the original files; I suggest you make a copy of one or two files in a separate folder, and run the script on them first to check that the output works for whatever reason you're doing this:
    set baseFolder to choose folder with prompt "Choose a folder of files to process"
    tell application "Finder"
              set fileList to (every file of baseFolder whose name extension is "txt") as alias list
    end tell
    repeat with thisFile in fileList
              set itsText to read thisFile
              if (offset of (return & linefeed) in itsText) = 0 then
      -- file is not already formatted with CR/LF, so convert
                        set itsChunks to tid(itsText, {return, linefeed})
                        set itsNewText to tid(itsChunks, return & linefeed)
                        set fp to open for access thisFile with write permission
                        set eof of fp to 0
      write itsNewText to fp as text
      close access fp
              end if
    end repeat
    on tid(input, delim)
      -- handler for text items conversions
              set {oldTID, my text item delimiters} to {my text item delimiters, delim}
              if class of input is list then
                        set output to input as text
              else
                        set output to text items of input
              end if
              set my text item delimiters to oldTID
              return output
    end tid

  • Replacing hyphen with line break

    Hi,
    In my application I want to replace the hyphen with line break
    . I am using APEX4.0
    I am using the following javascript code:
    <html>
    <script type="text/javascript">
    function test()
    var visitorName = "<br/>";
    var myOldString = "&P2_SI.";
    var myNewString = myOldString.replace(/-/g, visitorName);
    </script>
    </html>
    I have no clue how to get it executed and make the javascript work.... can someone help?

    My application is a online test.. One of the question in Page 3 is to re-arrange the sentence that is in the form of bullets. In the text area, as there are no formatting the candidate just gives hyphen - and enters all the sentences.. so in the DB the values are saved in the single line and when we evaluate the paper, it looks odd. So we want to replace the hyphen with the line break
    , so that when evaluating the paper, the format looks good, enter of one sentence there will be a line break.
    After the candidate is done with the Page 3, clickig next button, saves the values to the DB, and the page (branching) goes to Page 4 and clicking the Previous button takes the candidate to Page 2 (branching).
    The Dynamic Action is created in the following order
    -Advanced
    -action name
    -Event ->Change
    Selection Type->Item(s)
    Item(s)->P3_S2I
    Condition-> No condition
    -Action->Execute Javscriot code
    Disabled Fire on Page Load (as the code should execure only after the candidate type something in P3_S2I text area or after the Next button is clicked.
    Code:
    <script type="text/javascript">
    var special = "<br/>";
    var myOldString = "&P3_S2I.";
    var myNewString = myOldString.replace(/-/g, special);
    document.write("<br /> " + myNewString);
    </script>
    -Selection Type -> Item(s)
    Item - P3_S2I
    -Click Create
    This time I was taken to the next page.... but at the DB level hyphen is not replaced by the line break

  • How to avoid starting a page with line breaks?

    Hello. I've just started to refine my Master's thesis and some of the topics moved up and down as I edited their contents. The problem is that in some cases the topic breaks right after the title, and the rest of the contents just move away to another page. Is there any way to avoid starting a page with line breaks or broken topics?

    At the end of your title, you didn't inserted a line break but a paragraph break (carriage return).
    Acivate the mode "Show hidden characters"
    Select the carriage return (paragraph break)
    Delete it
    Press Shift + return to insert a true line break.
    It may be useful to apply that several times if you inserted several carriage returns between the title and the first filled line.
    Yvan KOENIG (VALLAURIS, France) 15 mai 2011 19:40:14

  • Re-post Replacing Hyphen with Line break

    Can someone please respond to the post: Replacing hyphen with line break
    Thanks.

    Please learn proper forum etiquette. Posts like this are (a) unnecessary and (b) actually quite annoying. At the very least, bump the original posting (but not, like, 30 minutes later because noone answered).

  • Help needed in plotting line graph!

    Hi i need help in plotting a line graph complete with both axes shown,plus the legend on the side shown.
    Pls help!!!!
    rgds

    Here's a simple line graph applet I did some time backimport java.awt.*;
    public class LineGraff extends java.applet.Applet{
       double []toGraff = {6.0, -14.0, -164.0, -210.0, 108.0, 770.0,
                                1354.0, 896.0, -572.0, -1348.0, -780.0, -108.0};
       double []numsFromFile = {6.0, -14.0, -164.0, -210.0, 108.0, 770.0,
                                1354.0, 896.0, -572.0, -1348.0, -780.0, -108.0};
       int max, min, size, Hscale;
       double Vscale;
       public void init(){
          size = numsFromFile.length-1;
          java.util.Arrays.sort(numsFromFile);
          max = (int) numsFromFile[size];
          min = (int) numsFromFile[0];
          Vscale = max-min;
          Vscale = 200/Vscale;
         Hscale = Math.round(300/size);
       public void paint(Graphics g) {
          g.setFont(new Font("Arial",0,14));
          g.drawString("Example app: drawing a graph from a double array",25,18);
          g.setFont(new Font("Arial",0,10));
          g.setColor(Color.blue);
          g.fillRect(10,20,365,230);
          g.setColor(Color.cyan);
          g.drawLine(25,25,25,225);
          g.drawLine(25,140,330,140);
          g.setColor(Color.white);
          int intA = 30, intB = 0, intC = 0;
          int intD = (int) (Math.round(140 - (Vscale * toGraff[0])));
             for(int i=1; i <= size; i++) {
               intC = intA + Hscale;
               intB = intD;
               intD = (int) (Math.round(140 - (Vscale * toGraff[ i ])));
               g.drawLine(intA, intB, intC, intD);
                  if(toGraff[ i ] > 0)
                     g.drawString(Double.toString(toGraff[ i-1 ]), intA+6, intB-3);
                  else
                     g.drawString(Double.toString(toGraff[ i-1 ]), intA+6, intB+8);
               intA += Hscale;
          g.drawString(Double.toString(toGraff[size]), intA+6, intD-3);    
    }

  • Copy the contents of Jtabl with line breaks to Excel

    Hi every one,
    In my stand alone application,I am copying the contents of Jtable i.e contents having the line breaks(\n).
    While copying and pasting the contents to Jtable,instead of linebreaks, a square symbol is appearing in the excel along with the line break.line break functionality is happening,but the additional symbol(empty square box) is appearing.
    here is my code:
    S = (String) "\""+mProcessQuestionTestItemTable.getValueAt(rowsselected, colsselected[j])+"\""; S=S.replace("\r\n", "\n").replace("\n", "\r\n");
    stringbuffered.append(S);can anyone help me in this?
    thank you!!                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Hi,
    I want to copy the contents of Jtable(contents having Line breaks(\n)) and pasting to Excel.
    While pasting the contents to Excel, a box is appearing in the excel.
    To remove the empty square box, i tried the sample code:
    originalstr =(String)"\""+ mProcessQuestionTestItemTable.getValueAt(rowsselected, colsselected[j])+"\"";
    originalstr=originalstr.replace("\r\n", "\n").replace("\n", "\r\n");
    strngBuffere.append(S);
    There will be no box,If i copy the contents of Jtable and pasting in notepad.
    the box is appearing in Excel only.
    can you suggest something to solve this..
    Thank you.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Help needed please, with Iphone stuck with apple picture and progress bar after software update attempted

    Help needed please, everytime I try to update the software version on my iphone it comes up with a message saying it could not be completed and is now frozen with the apple picture and progress bar on it. Do I unplug it and hope the macbook pro sees it again, I also stupidly did not back up before starting the download which I realise I will have to go back to the previous back up. This keeps happening, everytime I do this type of update, I'm starting to think I should just give up on updating my software on the Iphone. I thought it was happening because I was using a window based computer to do the updates, this time I used my Macbook Pro. Please somebody help

    ljm17 wrote:
    ...This keeps happening, everytime I do this type of update, I...
    Then you should know what you need to do... If you don't remember...
    See Here  >  http://support.apple.com/kb/HT1808

  • Trouble with line spacing and text flow in Indesign 6

    Hello everyone. I'm a graphic artist working with magazine layout new to Indesign. I've used Quark for years and recently came across this problem...
    Within a paragraph we'll usually use a soft return to bump certain words to the next line. However, there are occassions I'm noticing that by doing this the lines ABOVE where I'm bumping the word change and reflow. I've never had an issue with this before and it causes a serious problem for us. Is this a setting I have on that I'm not aware? What can I do to avoid this happening?
    Thank you for any input or advice.

    It's one of the major differences between Quark and ID.
    ID has a "paragraph composer" as will as a single line composer like Quark's, and it's on by default. When you use the paragraph composer the text is constantly analyzed and spacing adjusted for the best fit and appearance (according to the spacing algorithm and your justification settings) for the entire paragraph. If you force a line break, ID may adjust all the lines above as well as the lines that follow.
    If this is a "serious problem" you shoud probably witch to the single line composer. You'll find a drop down for it in the paragraph style definitin dialog under the Justification settings, or you can change an individual paragraph as a local override from the Control panel flyout menu.
    Most of us whove been ID users for some time find the paragraph composer to be one of the strenghts of ID, and feel it generates nicer looking text than a single line composer.

  • TS3999 Help! Trouble with my calendar and icloud.

    I am having trouble with my calendar and icloud.
    Customers send me meeting invites and I can accept them no problem. But if they subsequently change the date or time I get an error message:
    Access to “appointment name” in “Home” in account “iCloud” is not permitted.
    The server responded:
    “403”
    to operation CalDAVWriteEntityQueueableOperation
    sometimes the time changes in my calendar, sometimes it doesn't, and my customers keep getting messages back from icloud 'accepting' the original date, not the changed date!!
    It is driving me an my clients crazy!  any help would be appreciated.

    I had a problem specific to the Calendar on web-based Firefox (PC) Was asked for a separate sign-in I'd never seen before which didn't work. I resolved this by signing out, signing in again.

  • WRITE string with line break inside string.

    I would like to add a line break into a string that I want to write with the WRITE statement, but without using SKIP or NEWLINE or WRITE: \.
    CONCATENATE 'part1'
                ?the_line_break?
                'part2'
      INTO lv_string.
    WRITE lv_string.
    Any idea?

    Interesting requirement..
    WRITE statement does not interpret OS line break codes.
    You've to program to induce line break, try the following example code.
    data: lv_string(20),
          lv_off type i.
    concatenate 'part1'
                '~'
                'part2'
      into lv_string.
    search lv_string for '~'.
    lv_off = sy-fdpos + 1.
    write: at 1(sy-linsz) lv_string0(sy-fdpos), lv_stringlv_off.
    Regards
    Sridhar

  • Help! Trouble with property name="jnlp.versionEnabled" value="true"/

    Trouble with <property name="jnlp.versionEnabled" value="true"/> and file: protocol.
    I can't get the versionEnabled flag to work with local file system URL's.
    Here is code example (NanoHTTPD.java came from here -> http://elonen.iki.fi/code/nanohttpd/) :
    C:\test>dir
    Volume in drive C has no label.
    Volume Serial Number is CCC7-E05D
    Directory of C:\test
    05/08/2008  10:08 AM    <DIR>          .
    05/08/2008  10:08 AM    <DIR>          ..
    05/08/2008  09:44 AM               109 hello.java
    05/08/2008  09:57 AM               542 hello.jnlp
    04/10/2008  09:52 AM            20,547 NanoHTTPD.java
                   3 File(s)         21,198 bytes
                   2 Dir(s)  26,610,700,288 bytes free
    C:\test>type hello.java
    public class hello
    public static void main(String[] args)
    System.out.printf("Hello world\n");
    C:\test>type hello.jnlp
    <?xml version="1.0" encoding="utf-8"?>
    <jnlp spec="6.0+" codebase="http://localhost/" >
    <!-- codebase="file:///C:/test" -->
    <!-- codebase="http://localhost/" -->
        <information>
            <title>hello</title>
            <vendor>hello</vendor>
            <description>hello</description>
        </information>
        <resources>
            <j2se version="1.6" />
            <property name="jnlp.versionEnabled" value="true"/>
            <jar href="hello.jar" version="1.0" />
        </resources>
        <application-desc main-class="hello"/>
    </jnlp>
    C:\test>javac NanoHTTPD.java hello.java
    Note: NanoHTTPD.java uses or overrides a deprecated API.
    Note: Recompile with -Xlint:deprecation for details.
    Note: NanoHTTPD.java uses unchecked or unsafe operations.
    Note: Recompile with -Xlint:unchecked for details.
    C:\test>jar cvf hello__V1.0.jar hello.class
    added manifest
    adding: hello.class(in = 459) (out= 299)(deflated 34%)
    C:\test>start java -cp . NanoHTTPD
    C:\test>javaws http://localhost/hello.jnlpjava console output :
    Java Web Start 1.6.0_10-beta
    Using JRE version 1.6.0_10-beta Java HotSpot(TM) Client VM
    User home directory = C:\Documents and Settings\4381
    c:   clear console window
    f:   finalize objects on finalization queue
    g:   garbage collect
    h:   display this help message
    m:   print memory usage
    o:   trigger logging
    p:   reload proxy configuration
    q:   hide console
    r:   reload policy configuration
    s:   dump system and deployment properties
    t:   dump thread list
    v:   dump thread stack
    0-5: set trace level to <n>
    Hello worldchange hello.jnlp, jnlp start element to this:
    <jnlp spec="6.0+" codebase="file:///C:/test" >
    javaws hello.jnlpjava console output:
    Java Web Start 1.6.0_10-beta
    Using JRE version 1.6.0_10-beta Java HotSpot(TM) Client VM
    User home directory = C:\Documents and Settings\4381
    c:   clear console window
    f:   finalize objects on finalization queue
    g:   garbage collect
    h:   display this help message
    m:   print memory usage
    o:   trigger logging
    p:   reload proxy configuration
    q:   hide console
    r:   reload policy configuration
    s:   dump system and deployment properties
    t:   dump thread list
    v:   dump thread stack
    0-5: set trace level to <n>
    #### Java Web Start Error:
    #### helloStacktrace in detail :
    Detail ST:
    java.lang.ClassNotFoundException: hello
         at java.net.URLClassLoader$1.run(Unknown Source)
         at java.security.AccessController.doPrivileged(Native Method)
         at java.net.URLClassLoader.findClass(Unknown Source)
         at com.sun.jnlp.JNLPClassLoader.findClass(Unknown Source)
         at java.lang.ClassLoader.loadClass(Unknown Source)
         at java.lang.ClassLoader.loadClass(Unknown Source)
         at com.sun.javaws.Launcher.doLaunchApp(Unknown Source)
         at com.sun.javaws.Launcher.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)Take version out of file name:
    C:\test>move hello__V1.0.jar hello.jar
    C:\test>javaws hello.jnlp
    java console output:
    Java Web Start 1.6.0_10-beta
    Using JRE version 1.6.0_10-beta Java HotSpot(TM) Client VM
    User home directory = C:\Documents and Settings\4381
    c:   clear console window
    f:   finalize objects on finalization queue
    g:   garbage collect
    h:   display this help message
    m:   print memory usage
    o:   trigger logging
    p:   reload proxy configuration
    q:   hide console
    r:   reload policy configuration
    s:   dump system and deployment properties
    t:   dump thread list
    v:   dump thread stack
    0-5: set trace level to <n>
    Hello world

    The short answer is that e4x XML rocks!
    Beyond that, consider that you are sending xml to Flex. For
    any format other than e4x, Flex has to convert the xml into that
    format. The precise algorithms Flex uses for this are not obvious
    or published. This is why I have never liked using mx:Model. It
    converts the xml into nested objects, but i have never been
    comfortable predicting exactly what the resulting structure will
    be.
    Once you get an e4x xml node identified (toXMLString()), you
    CAN predict exactly whate the data you want is going to be because
    there is no conversion. And I and just very comfortable with xml.
    Tracy

  • Output with line breaks seemingly randomly placed

    Hola -
    I've adapted Tyler Muth's RSS feed article (http://tylermuth.wordpress.com/2008/01/22/producing-rss-from-plsql/) for the most part successfully; however, my output has breaks in the lines at inappropriate places, often in the mddle of an XML element tag for example. The placement of the breaks varies if I change the values of l_idx, l_len, l_defrows, l_maxrows, and l_desclen, but the breaks persist. They're not reflected in the code below but I've added the utl_file.fflush to no good effect.
    Examples of broken output:
    <pre>
    <title>Three
    prehistoric inventions that shaped us /</title>
    <guid
    isPermaLink="false">226402455778123622</guid>
    <pubDate>Thu, 04 Aug 2011 12:36:22
    EST</pubDate>
    <guid isPermaLink="fal
    se">220922455778123622</guid>
    <item
    >
    </pre>
    It's a lot of data so I won't post it here, but here's the code & the table; any ideas as to where to start investigating will be greatly appreciated.
    Code:
    create or replace
    PROCEDURE "RSSLOOP3" ( fund_in IN VARCHAR2, fund_in2 IN VARCHAR2 := 'XXX')
    is
    -- customizable parameters
    l_title varchar2(255) := ' New Titles Since ' || to_char(sysdate - 90, 'MM/DD/YYYY');
    l_link varchar2(255) := 'replace this' || fund_in || '.rss';
    l_description varchar2(255) := 'This is a feed of changes to items ' || fund_in;
    l_language varchar2(255) := 'en-us';
    -- end customizable parameters
    l_version varchar2(10) := '2.0';
    l_clob clob;
    l_idx pls_integer := 1;
    l_len pls_integer := 255;
    l_defrows pls_integer := 100;
    l_maxrows pls_integer := 100;
    l_desclen pls_integer := 250;
    -- for output to file
    fh UTL_FILE.FILE_TYPE;
    path VARCHAR2(30);
    filename VARCHAR2(30);
    begin
    path := '/http/live/screens/rss/';
    filename := fund_in || '.rss';
    fh := UTL_FILE.FOPEN(path, filename, 'w');
    for i in (
    select xmlelement( "rss",
    -- Begin XML Header Block
    xmlattributes( l_version as "version"),
    xmlelement( "channel",
    xmlforest( l_title as "title",
    l_link as "link",
    l_description as "description",
    l_language as "language"),
    -- End XML Header Block
    -- Begin List of Individual Articles or Items
    xmlagg(
    xmlelement( "item",
    xmlelement("title", x.title),
    xmlelement("link", x.link),
    xmlelement("description", convert(x.description, 'UTF8', 'AL32UTF8')),
    xmlelement("callnum", x.callnum),
    xmlelement("pubDate", to_char(x.updated_on,'Dy, DD Mon RRRR hh24:mi:ss')),
    xmlelement("guid", XMLATTRIBUTES('false' as "isPermaLink"),x.id||to_char(x.updated_on,'JHH24MISS'))
    -- End List of Individual Articles or Items
    ) as result
    from ( -- Actual Database Query that populates the list of Items
    select id,title,link,description,updated_on, callnum
    from drx_rss_feeds
    where (fund like fund_in||'%')
    and rownum < (l_maxrows+1)) x)
    loop
    l_clob := xmltype.extract(i.result,'/').getclobval;
    exit;
    end loop; --i
    --- OUTPUT RESULTS
    for i in 1..ceil(dbms_lob.getlength(l_clob)/l_len) loop
    UTL_FILE.PUT_LINE(fh,(substr(l_clob,l_idx,l_len)));
    l_idx := l_idx + l_len;
    end loop; --i
    UTL_FILE.FCLOSE(fh);
    end rssloop3;
    Table:
    CREATE TABLE "DRX_RSS_FEEDS"
    "ID" VARCHAR2(32 BYTE),
    "TITLE" VARCHAR2(255 BYTE),
    "DESCRIPTION" VARCHAR2(4000 BYTE),
    "LINK" VARCHAR2(1000 BYTE),
    "AUTHOR" VARCHAR2(255 BYTE),
    "UPDATED_ON" DATE,
    "CALLNUM" VARCHAR2(255 BYTE),
    "FUND" VARCHAR2(10 BYTE)
    )

    Or have a look at the Oracle Documentation, for instance at the parameters for utl_file.fopen
    max_linesize Maximum number of characters for each line, including the
    newline character, for this file (minimum value 1, maximum
    value 32767). If unspecified, Oracle supplies a default value of
    1024.It wouldn't surprise me if your randomly placed line breaks are all 1023 characters a part.
    Anton

  • Printing with line breaks

    Hi,
    I am using the following code to print some text from a text file.
    import java.awt.*;
    import java.awt.font.*;
    import java.awt.geom.*;
    import java.awt.print.*;
    import java.io.BufferedReader;
    import java.io.DataInputStream;
    import java.io.FileInputStream;
    import java.io.InputStreamReader;
    import java.text.*;
    public class Print implements Printable {
    private static final String mText = "";
    private static AttributedString mStyledText = new AttributedString(mText);
        static public void main() {
            String toPrint = "";
            try {
                FileInputStream fstream = new FileInputStream("/Library/iDemo/print.txt");
                DataInputStream in = new DataInputStream(fstream);
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                String strLine;
                while ((strLine = br.readLine()) != null) {
                    toPrint = toPrint + System.getProperty("line.separator") + strLine;
                in.close();
            } catch (Exception e)
                System.err.println("Error: " + e.getMessage());
            mStyledText = new AttributedString(toPrint);
            PrinterJob printerJob = PrinterJob.getPrinterJob();
    Book book = new Book();
    book.append(new Print(), new PageFormat());
    printerJob.setPageable(book);
    boolean doPrint = printerJob.printDialog();
    if (doPrint) {
    try {
    printerJob.print();
    } catch (PrinterException exception) {
    System.err.println("Printing error: " + exception);
    public int print(Graphics g, PageFormat format, int pageIndex)
    Graphics2D g2d = (Graphics2D) g;
    g2d.translate(format.getImageableX(), format.getImageableY());
    g2d.setPaint(Color.black);
            Point2D.Float pen = new Point2D.Float();
            AttributedCharacterIterator charIterator = mStyledText.getIterator();
            LineBreakMeasurer measurer = new LineBreakMeasurer(charIterator, g2d.getFontRenderContext());
            float wrappingWidth = (float) format.getImageableWidth();
            while (measurer.getPosition() < charIterator.getEndIndex())
                TextLayout layout = measurer.nextLayout(wrappingWidth);
                pen.y += layout.getAscent();
                float dx = layout.isLeftToRight() ? 0 : (wrappingWidth - layout.getAdvance());
                layout.draw(g2d, pen.x + dx, pen.y);
                pen.y += layout.getDescent() + layout.getLeading();
            return Printable.PAGE_EXISTS;
    }The problem I am having is that it removes the line breaks when printing. I have checked the file I am reading from and that has the line breaks. How can I get it to include the line breaks?
    Thanks

    The problem is that once it prints all this the line break is gone.
    Up until the following code the line breaks are fine. However, the printed document I'm getting has no line breaks at all.
    mStyledText = new AttributedString(toPrint);
            PrinterJob printerJob = PrinterJob.getPrinterJob();
    Book book = new Book();
    book.append(new Print(), new PageFormat());
    printerJob.setPageable(book);
    boolean doPrint = printerJob.printDialog();
    if (doPrint) {
    try {
    printerJob.print();
    } catch (PrinterException exception) {
    System.err.println("Printing error: " + exception);
    public int print(Graphics g, PageFormat format, int pageIndex)
    Graphics2D g2d = (Graphics2D) g;
    g2d.translate(format.getImageableX(), format.getImageableY());
    g2d.setPaint(Color.black);
            Point2D.Float pen = new Point2D.Float();
            AttributedCharacterIterator charIterator = mStyledText.getIterator();
            LineBreakMeasurer measurer = new LineBreakMeasurer(charIterator, g2d.getFontRenderContext());
            float wrappingWidth = (float) format.getImageableWidth();
            while (measurer.getPosition() < charIterator.getEndIndex())
                TextLayout layout = measurer.nextLayout(wrappingWidth);
                pen.y += layout.getAscent();
                float dx = layout.isLeftToRight() ? 0 : (wrappingWidth - layout.getAdvance());
                layout.draw(g2d, pen.x + dx, pen.y);
                pen.y += layout.getDescent() + layout.getLeading();
            return Printable.PAGE_EXISTS;
    }

Maybe you are looking for