Dividing a Text File into Sub Files

Hello Guys,
Thanks for being here to help people with their programming problems. I am trying to create a programs that divides the Romeo and Juliet play into different Acts. The play has 5 Acts, subdivided into several Scenes.
I am trying to ignore everything before ACT 1 Starts. The idea I am trying to use is the follow.
Create a function which get a BufferReader as input.
Create and StringBuilder to build the ACTs.
Create a loop to go thru the play line by line.
Store the line in a String variable.
Append the line to the StringBuilder.
If the string matches to "ACT 1" delete everything in the StringBuilder.
Keep looping. If the string matches to ACT 2, create a New file called Act 1 with the content of the builder.
I have 2 problems. The first is a NullPointerException. The second is that I got the program to create the file before, however, everything was in a single line, as opposed to multiple line like the play I am using. The other problems is that the "word" ACT 2 wasn't check and the program overlooked it. Everthing until the end of the file was written in the file act1.txt
Here is the file with the play I am using (Romeo_Juliet.txt)
[https://docs.google.com/leaf?id=0BxusGNRkVpmsODFkOWZjNmUtMWY2MS00ZTk2LWIzN2YtYzk0YWNkYWQ4MDYw&hl=en]
Please Help!!!
I will really appreciate it!
Here is my code
import java.io.*;
import java.lang.*;
public class DivideActs {
     static void divideIntoActs(BufferedReader br){
          FileOutputStream out; // declare a file output object
          PrintStream p; // declare a print stream object
          String line = new String();
          StringBuilder builder = new StringBuilder();
          String st = new String();
          int count = 0;
          try {
               while (br.readLine() != null) {
                    line = br.readLine();
                    if (line.toString().matches("ACT 1")) {
                         line = "";
                         count = builder.length();
                         builder.delete(0, count);
                    // line = br.readLine().toString();
                    builder.append(line);
                    if (line.matches("ACT 2")) {
                         out = new FileOutputStream("act1.txt");
                         p = new PrintStream(out);
                         st = builder.toString();
                         p.println(st);
                         System.out.println("File Written Succesfully");
                         p.close();
          } catch (FileNotFoundException e) {
               System.out.println("Could not load file!");
          } catch (IOException e) {
               e.printStackTrace();
     public static void main(String[] args) throws IOException {
          FileReader reader = new FileReader("Romeo_Juliet.txt");
          BufferedReader buffReader = new BufferedReader(reader);
          divideIntoActs(buffReader);
          buffReader.close();
}Edited by: locorecto on Apr 25, 2010 10:54 AM

locorecto wrote:
I have 2 problems. The first is a NullPointerException.The stack trace produced by the NPE should tell you what line is throwing the exception.
The second is that I got the program to create the file before, however, everything was in a single line, as opposed to multiple line like the play I am using. readLine() doesn't preserve the newline at the end of the line. You'll have to add it back in.
The other problems is that the "word" ACT 2 wasn't check and the program overlooked it. Everthing until the end of the file was written in the file act1.txtMaybe the line wasn't exactly "ACT 2". You're probably better off using regular expressions. Or at least something like String.indexOf.
There are more problems.
import java.lang.*;You don't have to import the java.lang package. It's automatically imported.
          FileOutputStream out; // declare a file output object
          PrintStream p; // declare a print stream object
To be pedantic: you're not declaring objects here. You're declaring reference variables that will refer to objects of the given type.
          String line = new String();
You need to declare line, but assigning an empty string to it is pointless.
          String st = new String();
Same here. Also, you can declare this in the block where you use it.
               while (br.readLine() != null) {
                    line = br.readLine();Do you see what you're doing here? You're throwing away every alternate line. You read a line to see if it's null, throw it away, then read the next line.
This is probably why it's not finding "ACT 2" (it's on an even-numbered line where you're looking for odd, or vice-versa). But even if it found the "ACT 2" line, your output would be missing half the lines.
                    if (line.toString().matches("ACT 1")) {That toString() there is unnecessary. line is already a String.
                         line = "";If you just do a continue; at the end of this block, you don't need to bother with this.
                         count = builder.length();
                         builder.delete(0, count);I think you could just do builder.setLength(0). Or just instantiate a new StringBuilder. For that matter you don't need to create a StringBuilder at all until you find Act I.
If you make a change like this, you no longer need the count variable.
You know, Perl is made for tasks like this.

Similar Messages

  • I got my ipad 2 yesterday.  I am trying to transfer photos as albums to ipad via itunes. I put the photos in a file with sub-files as I was told. The all tranfer but into one album. Is there a way to do what I am trying?

    I am trying to tranfer photos from pc to ipad via itunes. I put the photos in a file and sub-files in order to tranfer them as albums: an main album with albums within. All the photos tranfered but into only one album. Is there a way to do this? Is there an app that would help. Also, I tranfered two albums into iphoto. I edited a photo in one album which created a new album of edits. I have removed the photos form the album but I am not able to delete the album themselves. Any help will be greatly appreciated.

    I am having the same problem and it is even bigger.
    When opening a 1-page PDF in iBooks and sending it via mail it is sent inline as preview, but the recipient cannot open the file anymore. Also on iPad and iPhone there is no "open in" possible.
    Somehow the mail app does destroy the file. What is going wrong?

  • Embedding Full-text Index into PDF File

    Hello Everyone,
    I've tried to create and embed full-text index into PDF file, but with no luck. I've followed steps described at http://help.adobe.com/en_US/Acrobat/9.0/Standard/WSC28D4DBB-6A78-4027-9E04-F50FE411CFB9.w. html - there can be seen progress of collecting of data and at the end the button Update index is enabled. This is signal for me that Index was created. After clicking on Ok button, saving document as new one and then reopening "new created" document, there is info that no Index is embedded in the Manage Embedded Index dialog. Is there any other step necessary to do? Or is it bug? Adobe Acrobat Pro 9.1 on Windows Vista 32bit is used.
    Jan
    PS: Interesting is also comment at the bottom of above mentioned help page...

    Thanks for the response. It is true that if I make changes and look at the embedded index status, it shows that it needs updating
    However the problem I can't get around after extensive testing is that sometimes for no apparent reason the index is dropped on save. This can happen if I check the status of the index to make sure it is valid, save the file, and reopen it.
    I've concluded that this must be a bug and am using other indexing options for the time being.

  • How To Divide Source File Into Smaller Files Without Exporting?

    Hello Everyone,
    I'm a beginner with PPro CS4 and to video editing in general. I've done a lot of Googling and searching of these forums to get an answer to this question, but I haven't found a clear answer. Here's my problem:
    I have many hours of HDV footage shot over the past few years with a Canon HV30. This footage is on dozens of DV tape cassettes. I want to capture most of it to disk.
    When I capture a tape to disk, I get a single large mpeg4 file. (PPro captures all HDV footage to mpeg4.) "Scene select" doesn't work with the HV30, so my only other way to make smaller capture files would be to set In/Out points with batch capture. But this would mean hours of fast-forwarding and reversing with the VCR-like controls on the camera to review all the tapes and set the points. I thought it might be FASTER to simply capture an entire tape in one operation, THEN review the captured tape within PPro (it's much faster using the scrubber), and dividing that file into smaller files within PPro, thereby avoiding all the mechanical fast-forwarding and rewinding on the camera itself.
    But the only way I can find to do this seems to involve EXPORTING clips. Am I wrong to think that exporting a clip to a new file involves a degradation of the original mpeg4 source file? Or will there be no loss to the quality if I simply export to mpeg4 format?
    It seems there should be an easy way to simply divide the original capture into smaller source files for later editing, without putting the footage through another generation of processing (exporting), which might entail some loss of quality. Or am I wrong about this?
    (CS4 Master Suite, i7 3630k, 16GB RAM, C: 256GB SSD, D: 1T Setpoint F3, E: 1T Setpoint F3)

    HDV footage is mpeg2 (whats in a number ). CS4 does not do scene detect you need to use HDV split for that.
    http://strony.aster.pl/paviko/hdvsplit.htm.
    You can run your already captured files through hdv split and it will chop the file into clips and off you go.

  • Copy Labels (text) in Illustrator file into keyword (file info) field

    I'm curious if there is any way to copy the text in an illustrator file, and paste it into the keyword field within the file info dialog box, with those words being separated by commas.
    If I do this manually, the text is pasted as one long running word, making the keywords useless.
    I do have an applescript which extracts the text from an illustrator file, and pastes it into an excel file, separating the words with commas, with file name. However, it doesn't seem possible to then import this data back in to multiple files. Bridge doesn't appear to be capable of this....
    ..so the alternative I can see would be to get the text directly into the file info box, separated by commas... just not sure how.
    any ideas? I have thousands upon thousands of artfiles that need to be keyworded somehow!

    Hallo Jay,
    I think there is two ways:
    a) Although I have no serious experiences with Bridge scripting I think you need a Bridge script which runs over your Illustrator files, calls an Illustrator script for collected labels and use the Bridge API to write the metadata back into the file.
    b) You write an Illustrator script which runs over the files and collects the labels and creates a text file with these information (file name, keywords). Process this file and use a 3rd party XMP tool for adding these keywords to the file.
    Regards,
    Tom

  • Converting html file into zip file and send email attaching zip file

    Hi Experts,
    I am trying to send email with attachment(html). Which contains more than 7MB. So, It is throwing an error like Size exceeded.
    So, Now i need to compress the data for less than 7MB.
    I decided to convert HTML File into ZIP File.
    Kindly suggest me to convert the HTML file into ZIP file and sending email with attached ZIP file.
    Correct answer rewarded,
    Thanks & Regards,
    N. HARISH KUMAR

    Hi Experts,
    *// HTML_TAB converting into ZIP File
       DATA  : zip_tool TYPE REF TO cl_abap_zip,
               filename TYPE string ,
               filename_zip TYPE string .
       DATA  : t_data_tab TYPE TABLE OF x255,
               bin_size TYPE i,
               buffer_x TYPE xstring,
               buffer_zip TYPE xstring.
    filename = text-007.                                                                          "'HTML_TAB
    *describe the attachment
       DESCRIBE TABLE html_tab LINES tab_lines.
       bin_size = tab_lines * 255.
       CALL FUNCTION 'SCMS_BINARY_TO_XSTRING'
         EXPORTING
           input_length = bin_size
         IMPORTING
           buffer       = buffer_x
         TABLES
           binary_tab   = html_tab.
       IF sy-subrc <> 0.
    *     message id sy-msgid type sy-msgty number sy-msgno
    *     with sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
       ENDIF.
    *create zip tool
       CREATE OBJECT zip_tool.
    *add binary file
       CALL METHOD zip_tool->add
         EXPORTING
           name    = 'FSSAI_MAIL.HTML'
           content = buffer_x.
    *get binary ZIP file
       CALL METHOD zip_tool->save
         RECEIVING
           zip = buffer_zip.
       CLEAR: t_data_tab[],bin_size.
       CALL FUNCTION 'SCMS_XSTRING_TO_BINARY'
         EXPORTING
           buffer        = buffer_zip
         IMPORTING
           output_length = bin_size
         TABLES
           binary_tab    = html_tab.
    Thanks & Regards,
    N. HARISH KUMAR

  • About download file into unix file

    Hi expert,
    i use the openset to write file into unix file server.
    but why there are some space at the end of every line.
    by the way, i works very well in windows server
       DATA: DATA_TRANSFER(70).
        Data: DATA_TRANSFER type string.
        data: fine_riga1(1) TYPE X VALUE '0D0A'.
        DATA: gt_data TYPE STANDARD TABLE OF ty_data.
        Constants: ascii_tab type x value ','.
        field-symbols: <f> type any, <delim> type any.
        "Assign delimiter field such as tab or comma.
        assign ASCII_tab to <delim>.
        CLEAR VN_CNT.
        concatenate DSNU 'employee' PN-BEGDA SY-UZEIT into P_UNIX.
        OPEN DATASET P_UNIX in legacy text MODE FOR OUTPUT. " IN TEXT MODE encoding UTF-8.
        IF SY-SUBRC <> 0.
          WRITE: / 'Error on file open:', P_UNIX.
        ELSE.
          LOOP AT TI_DATA .
            CLEAR DATA_TRANSFER.
            concatenate TI_DATA-TYPE
                              TI_DATA-PERNR
                              TI_DATA-ZAUSW
                              TI_DATA-ENAME
                              TI_DATA-TERID
                              INTO DATA_TRANSFER separated by cl_abap_char_utilities=>HORIZONTAL_TAB.
            CONDENSE DATA_TRANSFER NO-GAPS.
            TRANSFER DATA_TRANSFER TO P_UNIX.
            ADD 1 TO VN_CNT.
            CLEAR DATA_TRANSFER.
          ENDLOOP.
          CLOSE DATASET P_UNIX.
        ENDIF.
        WRITE: / P_UNIX,
               / 'Transfered', VN_CNT, 'records'.
    Best Regards,
    Kevin

    Hi,
    Try this way...
    TRANSFER dobj TO dset [LENGTH len]
                                          [NO END OF LINE].
    Addition 1
    ... LENGTH len
    Effect
    This addition determines how many characters or how many bytes of data object dobj are written to the file. len is expected to be a data object of type i that contains the number of characters or bytes. In text files, the content of len specifies the number of characters that are written from the storage. For binary files, legacy text file, and legacy binary files, len specifies the number of bytes that are written to the file. The first len characters or bytes are transferred and alignment gaps are included in the structures. If the addition LENGTH is not specified, all characters or bytes are transferred.
    If the value of len is less than or equal to 0, no characters or bytes are transferred. If the file is opened as a (legacy) text file, however, a line end marker is inserted into the file by default. If the value of len is greater than the number of characters or bytes in dobj, hexadecimal 0 or blank characters are transferred to the file instead of the missing bytes or characters, depending on whether the file was opened as a (legacy) text file or a (legacy) binary file.

  • Convert XML file into PDF file

    <b>XML to PDF</b>i want to Convert XML file into PDF file pl. any one can suggests API's

    Hi,
    There are many ways to convert XML files to PDFs through java.
    One of the easiest way is by using iText.jar which have classes for conversion.
    The following are the required steps
    1. Create a document object for the XML file ( Using DOM or SAX parser).
    2. Parse the xml document and extract the content to write in PDF.
    3.Create a itext Document object.
    4.Get a PdfWriter instance for the PDF file.
    5.Write in the pdf the extracted text using the document object.
    Refer <a href="http://itextdocs.lowagie.com/examples/com/lowagie/examples/general/HelloWorld.java">here</a> for a simple pdf writer example.
    Refer <a href="http://java.sun.com/developer/codesamples/xml.html">here</a> for examples of XML Parsers.
    Regards,
    Uma

  • How to chunk the XML files into smaller files using peoplecode.

    We are trying to load the Invoices through our XMLDoc PeopleCode that we have written long back.
      Previously the file is not that big and we are able to load them successfully. But now each file is more than 200MB and we are getting the below error when initiated the process..
      Process Request shows status of 'INITIATED' or 'PROCESSING' but no longer running “.
      I tried to chunk the file manually to 50MB it is able to run it properly but chuncking manually is not possible for all the files as it is time taking process..
      Is there any way that we can check on Webserver/Appserver whether whats happening and how to handle this error..
    Or any sample code to divide the big file into smaller files..
      Please let me know your thoughts..

    Good morning Ashok,
    Your data is in a SQL*Loader supported datatype, so basically it should not be a problem.
    Have you checked the Database Utilities guide (for Oracle9i for instance: http://www.lc.leidenuniv.nl/awcourse/oracle/server.920/a96652/toc.htm) on how to handle this?
    I'll also repeat my previous question, have you ever been able to load data into the database using SQL*Loader (either using ASCII values or any other datatype)?
    For the OWB part, have you read "Importing Data Definitions" (typically chapter 4)? More specifically, "Specifying Field Properties" in "About Flat File Sources and Targets"?
    In "SQL*Loader Properties" it says the following:
    Type Describes the data type of the field for the SQL*Loader. You can use the Flat
    File Sample Wizard to import the following data types: CHAR, DATE, DECIMAL
    EXTERNAL, FLOAT EXTERNAL, INTEGER EXTERNAL, ZONED , AND ZONED
    EXTERNAL. For complete information on SQL*Loader field and data types, refer to
    Oracle9i Utilities. Currently, only portable datatypes are supported.
    If you check the database utitlities guide (chapter 6 Field List Reference) and look for "SQL*Loader Datatypes", you'll find (packed) decimal under the Nonportable Datatypes. This implies that OWB does not support it.
    This does not mean you can't use SQL*Loader, you'll only have to define everything separate from OWB and call it separately as well.
    Good luck, Patrick

  • I need to combine 2 swf files into 1 file

    I have a flash template that is controled by basicly 3 files website.swf, text.xml and index.html (there are a lot of supporting files)  When i put a video.swf in the xml file it runs with the website.swf as long as I don't turn on the sound on the video.swf because it will not stop.  So I needed some controls on the video.swf which is the skinunderall.swf, but the file comes in 2 pieces and will not intergrate on the website.swf.  I have about 18 video.swf files and they all need to be controlled by the user on the site.  Is there anyway to combine video.swf and the skinunderall.swf to ONE file with the controls?  I will settle for a start stop button, however once the file starts I can't touch it--it seems.  But I have turn the video.swf into a link and it was clickable.
    I read the captive thing but it seems to be out of date.  Oh yeah and I am a page one (begining) coder.
    Any help?

    Hi,
    "combine 2 swf files into 1 file" is a pretty abstract question. The short answer is - yes, you can, but you need an appropriate  software tool for that. But really it's not clear (for me) how all your files work together exactly. The only what I can derive from your explanation, is that you need to add an interactive control to some SWF files with embedded video, loadable into the main "envelope".
    In general all what you need are:
    - you must have some named mc within your "main" SWF, which will load your video SWF's into itself by loadMovie() function.
    - you need to have some controls (buttons, etc.) in your "main" movie. which will control this mc playback - mc.play(), mc.stop(), etc.
    I'm almost sure it's resolvable problem, but can you upload this template to let us see how it all works now? If you don't wish to disclose it all publically, then you may write to me personally. You can find email address at the bottom of the webpage in my signature.
    FlashDigger
    www.flashdig.com

  • How to update link and import data of relocated incx file into inca file?

    Subject : <br />how to update link and import data of relocated incx file into inca file.?<br />The incx file was originally part of the inca file and it has been relocated.<br />-------------------<br /><br />Hello All,<br /><br />I am working on InDesignCS2 and InCopyCS2.<br />From indesign I am creating an assignment file as well as incopy files.(.inca and .incx file created through exporing).<br />Now indesign hardcodes the path of the incx files in inca file.So if I put the incx files in different folder then after opening the inca file in InCopy , I am getting the alert stating that " The document doesn't consists of any incopy story" and all the linked story will flag a red question mark icon.<br />So I tried to recreate and update the links.<br />Below is my code for that<br /><br />//code start*****************************<br />//creating kDataLinkHelperBoss<br />InterfacePtr<IDataLinkHelper> dataLinkHelper(static_cast<IDataLinkHelper*><br />(CreateObject2<IDataLinkHelper>(kDataLinkHelperBoss)));<br /><br />/**<br />The newFileToBeLinkedPath is the path of the incx file which is relocated.<br />And it was previously part of the inca file.<br />eg. earlier it was c:\\test.incx now it is d:\\test.incx<br />*/<br />IDFile newIDFileToBeLinked(newFileToBeLinkedPath);<br /><br />//create the datelink<br />IDataLink * dlk = dataLinkHelper->CreateDataLink(newIDFileToBeLinked);<br /><br />NameInfo name;<br />PMString type;<br />uint32 fileType;<br /><br />dlk->GetNameInfo(&name,&type,&fileType);<br /><br />//relink the story     <br />InterfacePtr<ICommand> relinkCmd(CmdUtils::CreateCommand(kRestoreLinkCmdBoss)); <br /><br />InterfacePtr<IRestoreLinkCmdData> relinkCmdData(relinkCmd, IID_IRESTORELINKCMDDATA);<br /><br />relinkCmdData->Set(database, dataLinkUID, &name, &type, fileType, IDataLink::kLinkNormal); <br /><br />ErrorCode err = CmdUtils::ProcessCommand(relinkCmd); <br /><br />//Update the link now                         <br />InterfacePtr<IUpdateLink> updateLink(dataLinkHelper, UseDefaultIID()); <br />UID newLinkUID; <br />err = updateLink->DoUpdateLink(dl, &newLinkUID, kFullUI); <br />//code end*********************<br /><br />I am able to create the proper link.But the data which is there in the incx file is not getting imported in the linked story.But if I modify the newlinked story from the inca file,the incx file will be getting update.(all its previous content will be deleted.)<br />I tried using <br />Utils<IInCopyWorkflow>()->ImportStory()<br /> ,But its import the incx file in xml format.<br /><br />What is the solution of this then?<br />Kindly help me as I am terribly stuck since last few days.<br /><br />Thanks and Regards,<br />Yopangjo

    >
    I can say that anybody with
    no experience could easily do an export/import in
    MSSQLServer 2000.
    Anybody with no experience should not mess up my Oracle Databases !

  • How to convert a .class file into .java file without .jad using DeJDecompil

    Hi all,
    I am using DeJDecompiler and working with swing applications.If I try to convert a .class file into .java file,it is converting into .jad file only.Fine but if I try to save that file into .java file,It is giving lot of errors in that program.When I went into that program the total style of the program is changed and TRY-CATCH block is not recognised by the dejdecompiler,hence If I try to include some methods in the existing .java file thus got,I could not do.Kindly help me.
    If I get the .java file without error then I can process the rest of the functionality.
    Thanks in advance
    With kind Regs
    Satheesh.K

    Not so urgent today then!
    http://forum.java.sun.com/thread.jsp?thread=553576&forum=31&message=2709757
    I'm still not going to help you to steal someone�s code.

  • How do i merge multipule pdf files into one file?

    how do i merge multipule pdf files into one file?

    One method:
    Open Acrobat XI Pro - use this "click path":
    File :: Create :: Combine Files into a Single File
    Be well...

  • How do I merge 2 pdf files into one file?

    How do I merge 2 pdf files into one file?

    I use PrimoPDF (free download) to create pdf files. To merge two docs/pdfs/etc., print the first to a new pdf using Primo. Close it, then print the second and save it to the same new pdf. Primo gives you the option to 'append' or 'overwrite' the original file. By using 'append', you are just adding it to the back of the existing file. You can do this repeatedly to resort or combine existing pages into a new pdf.
    Also, I'm using Adobe Reader X.

  • How to include external .js file into .ear file using NetBean 5.5.1?

    is it possible to include external .js file into .ear file using NetBean 5.5.1? if not, then where should I placed the external .js file and how to write the src="xxx" element? (that is , how to write the path of "xxx"?)
    I am using JBOSS 4.2.2 GA as server
    thx!!

    Even this is also not possible because, the code in that package is developed by DWR and i am just adding it to my lib folder and importing the respective classes. In the same manner i need to include the *.js* file in the JSP.It took me about 3 minutes reading through the [DWR Getting Started|http://getahead.org/dwr/getstarted] page to learn that you don't have to do any of that. Perhaps you should read that page?

Maybe you are looking for

  • Connection ==null and Connection is closed, difference

    Hi experts, I wonder what are the differences between "Connection==null" and "Connection is closed"? I closed a connection on one JSP page after a bean has retrieved data. Then, on the same page I call another bean to connect to the database. Because

  • Cisco jabber client for anroid

    Dear All; I have created android user under cucm and it works fine only one time if disconnected never connected until i restart all the phone services then it reconnect. I also tested the same on different android phone problem is same.  Kindly sugg

  • Error on Setup of Reader XI

    While downloading Reader XI, I received an error: Setup has detected that you already have a more functional product installed. Setup terminated. What is happening that it does not installed??

  • Summary Column and repeating frames

    I have a report that shows customer orders(1 per page). If a customer orders 3 pizzas and 2 of them are identical, same size, same toppings, crust i want the quanitity column to sum as 2. So for this example instead of having 3 rows with two of them

  • Numbering Series in XL Reporter

    Hi Experts, Can anyone suggest/provide a guide on how to create such a report. I'm trying to design a report from XL Reporter which will display Items from specific vendor transacted in AR Invoice and Credit Memo and I can choose specific numbering s