Splitting text form file

Hello,
This is the problem, I have a text file with mobile messages, here's an example of these messages.
25 100
SEND 2228161 Hello Pete
RECEIVE 2228161 Hello Chris, how are you?
SEND 2227765 I hate text speak
RECEIVE 2228876 wot u on bout
SEND 2227975 The quick brown fox jumped over the lazy dog
SEND 2328161 Simple Simon met a pieman going to the fair
SEND 2226543 Mary had a little lamb, its fleece was white as snow
SEND 2226543 And everywhere that Mary went the lamb was sure to go
I have to read the text file, for which the code I have succeeded in doing, the first line of the text file are integers, which I have to assign to to variables say sizeOfMessage and limitOfBox. The code I've written so far reconizes the SEND and RECEIVE messages, using if (line.startsWith("SEND")), this I've tested it works. Now here is where I am pulling my hair out, I need to read the line, evaluate the size of the message excluding the SEND and telephone number, if it is greater than the sizeOfMessage value, split the the message up, then store the fragmented message including the SEND and telephone message into an array. Here is the code so far:-
tokens = new StringTokenizer(line, "");
                while (tokens.hasMoreTokens())
                    //get next token
                     System.out.println(tokens.nextToken());
                    // split on the white space with eiher RECEIVE or SEND before it
                    String[] storeTokens = line.split("(SEND|RECEIVE)\\s");
                    if (line.startsWith("SEND"))
                        System.out.println("SEND message");
                        if ((storeTokens[1].length()) > 25)
                            String[] tempTokens = line.split("(?<=SEND)\\s");
                   }         How do I achieve this?
Any help would be appreciated
Thanks

Here's a quick example. Hope this helps.
/** testfile.txt **********************************
25 100
SEND 2228161 Hello Pete
RECEIVE 2228161 Hello Chris, how are you?
SEND 2227765 I hate text speak
RECEIVE 2228876 wot u on bout
SEND 2227975 The quick brown fox jumped over the lazy dog
SEND 2328161 Simple Simon met a pieman going to the fair
SEND 2226543 Mary had a little lamb, its fleece was white as snow
SEND 2226543 And everywhere that Mary went the lamb was sure to go
SEND 2226543 There was a labyrinth in the forest where the lamb was lost
import java.util.*;
import java.util.regex.*;
import java.io.*;
public class MindGames{
  int sizeOfMessage, limitOfBox;
  ArrayList<String> inputLines;
  ArrayList<ArrayList<String>> messages;
  public MindGames(String infilename){
    String line = null;
    inputLines = new ArrayList<String>();
    messages = new ArrayList<ArrayList<String>>();
    try{
      BufferedReader br = new BufferedReader(new FileReader(infilename));
      while ((line = br.readLine()) != null){
        inputLines.add(line);
    catch (Exception e){
      e.printStackTrace();
    String[] temp = (inputLines.remove(0)).split("\\s+"); //remove first line
    sizeOfMessage = Integer.parseInt(temp[0]);
    limitOfBox = Integer.parseInt(temp[0]);
    inputLines = gather(inputLines);
  public void reformatLines(){
    ArrayList<String> aline;
    for (String s : inputLines){
      String[] elements = s.split("\\s+", 3);
      aline = new ArrayList<String>();
      String[] folded = makeFold(elements);
      for (String m : folded){
        aline.add(m);
      messages.add(aline);
  /* gather msgs for same number */
  ArrayList<String> gather(ArrayList<String> lines){
    ArrayList<String> retval = new ArrayList<String>();
    int i = 0;
    String[] current, next;
    String[] dummy = {"", "", ""};
    while (i < lines.size()){
      current = lines.get(i++).split("\\s+", 3);
      if (i < lines.size()){
        next = lines.get(i++).split("\\s+", 3);
      else{
        next = dummy;
      while (next[1].equals(current[1]) && next[0].equals(current[0])){
        current[2] = current[2] + " " + next[2];
        if (i < lines.size()){
          next = lines.get(i++).split("\\s+", 3);
        else{
          next = dummy;
      retval.add(current[0] + " " + current[1] + " " + current[2]);
      if (! next.equals(dummy)){
        --i;
    return retval;
  /* the regex for this version honors word boundary and spaces btw them */
  String[] makeFold(String[] rawSplit){
    ArrayList<String> foldedMsg = new ArrayList<String>();
    String msg = rawSplit[2];
    // short msg | can fold at word boundary | extraordinary long word
    String regex
      = "^.{0," + sizeOfMessage + "}$|.{1," + sizeOfMessage
      + "}(?=\\s|$)|[^\\s]{1," + sizeOfMessage + "}";
    String s;
    Pattern pat = Pattern.compile(regex);
    Matcher mat = pat.matcher(msg);
    while (mat.find()){
      s = mat.group();
      foldedMsg.add(rawSplit[0] + " " + rawSplit[1] + " " + s);
    return foldedMsg.toArray(new String[1]);
  public void testOutput(){
    for (ArrayList<String> as : messages){
      for (String str : as){
        System.out.println(str);
  public static void main(String[] args){
    MindGames mg = new MindGames("testfile.txt");
    mg.reformatLines();
    mg.testOutput();
/*** output for inputting testfile.txt ***************
SEND 2228161 Hello Pete
RECEIVE 2228161 Hello Chris, how are you?
SEND 2227765 I hate text speak
RECEIVE 2228876 wot u on bout
SEND 2227975 The quick brown fox
SEND 2227975  jumped over the lazy dog
SEND 2328161 Simple Simon met a pieman
SEND 2328161  going to the fair
SEND 2226543 Mary had a little lamb,
SEND 2226543  its fleece was white as
SEND 2226543  snow And everywhere that
SEND 2226543  Mary went the lamb was
SEND 2226543  sure to go There was a
SEND 2226543  labyrinth in the forest
SEND 2226543  where the lamb was lost
*********************************************************/

Similar Messages

  • Splitting HTML forms into several files

    I have an HTML form that has a lot of text inputs. I want to split this form into several pages using JSTL and Struts tags in the following manner:
    main file
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="h" %>
    <h:form action = ...>
    <c:import url=' file1' />
    <c:import url=' file2' />
    </h:form>
    file 1
    <h:text name=' ...' />
    <h:text name= '...' />
    file2
    <h:text name=' ...' />
    <h:text name= '...' />
    The problem here is that the <h:form> is on the "main file" and therefore I get an error in file1 and file2. Is there a way to pass the "prefix=h" variable from the main file to file1 and file2?
    Can anyone help find a solution for this problem?
    thanks,
    sgs.

    Instead of
    <c:import url=' file1' />
    <c:import url=' file2' />
    Can you test with ..
    <%@ include file="file1.jsp" %>
    <%@ include file="file2.jsp" %>
    My guess is that it should work since your stuts form tags in the 2 files will be ultimately compiled as one jsp [in the main one].
    -Rohit

  • Splitting text file

    I have the below clas for splitting text files, but I am getting an error. Could someone please help? Thanks
    public void splitFile(String file) {
              try {
                   BufferedReader in = new BufferedReader(new FileReader(file));
                   final int numOutputFiles = constants.getNUM_PRINTERS();
                   int loopCounter=0;
                   Object currentOutputFile = null;
                   String sourceFile = in.readLine();
                   PrintWriter out0 = new PrintWriter(new FileOutputStream(constants.getPRINTER1_FILENAME()));
                   PrintWriter out1 = new PrintWriter(new FileOutputStream(constants.getPRINTER2_FILENAME()));
                   PrintWriter out2 = new PrintWriter(new FileOutputStream(constants.getPRINTER3_FILENAME()));
                   PrintWriter [] fileHandles = {out0, out1, out2};
                   while (sourceFile != null) {
                        loopCounter++;
                        if (loopCounter == numOutputFiles) {
                             loopCounter=1;
                        ERROR-->currentOutputFile = fileHandles[loopCounter-1].println(sourceFile); <--ERROR
                        //currentOutputFile.write(sourceFile);          
                   out0.close();
                   out1.close();
                   out2.close();
              } catch (Exception ex) {
                   logger.error(EXCEPTION_MESSAGE,"Error splitting file: "+ex.getMessage());
                   ex.printStackTrace();
         }The error I get is on the line above in bold, "Type mismatch: cannot convert to void from Object" .
    Thanks!!

    also, how can I get the PrintWriter file names to be dynamic instead of declaring 3 of them like I have it now? Lets say I need 5 files now, but in the future, I may need 2 files. So the "out" variable would have the out1 and out2 only.

  • Fire Fox sent not all the data in text form. Reached only piece of information. Where can I find the cache of sent text?

    Fire Fox sent not all the data in text form. Reached only piece of information. Where can I find the cache sent the text?
    For example, I posted an article on a news site, but found that only a small part of my article was posted.

    I'm not sure whether Firefox saved that information. There is a chance that it is in the session history file, especially if you haven't closed that tab yet. To check that:
    Open your currently active Firefox settings folder (AKA your Firefox profile folder) using
    Help > Troubleshooting Information > "Show Folder" button
    Find all files starting with the name sessionstore and copy them to a safe working location (e.g., your documents folder). In order to read a .js file, it is useful to rename it to a .txt file. Or you could drag it to Wordpad or your favorite word processing software.
    The script will look somewhat like gibberish, but if you search for a word in your article that doesn't normally appear in web pages, you may be able to find your data.
    Any luck?
    For the future, you might want to consider this add-on, although I don't know how long it saves data after you submit a form: [https://addons.mozilla.org/en-US/firefox/addon/lazarus-form-recovery/].

  • Set maximum size in Text Form Field Options for a field in bi publisher RTF

    Hi All,
    How to set maximum size in Text Form Field Options for a field in bi publisher RTF.
    I have a RTF whch is having a field in that i need to add some validation condition but after adding certain condition in Add help text tab ,it is not accepting after certain length, how i can increase the length to unlimited,please help me on this
    Thnaks

    Form fields have some restrictions if your are using version lower than 11g.
    They can accommodate only 393 chars. You can add the text in both status bar and help key, which can in total consume 393 chars.
    If your code logic is more than that, it can be split into multiple form fields as Avinash suggested or you can use sub template logic and handle coding over there. Again in sub template code can be within/outside form fields.
    So there is no option for user to increase the size of form field.

  • How to read a text delimited file using 2 dimentional array in java ??

    hi,
    I am new to java programming.. I have to do a task where in i have to read a text delimeted file in an array.. For example.. If the file is as follows
    Name place Value
    adi goa 20
    shri mumbai 30
    riya bangalr 45
    I want it to be read in java so as to get an array[row][columns]
    This is something i am currently upto, but cant get any further.
    import java.io.BufferedReader;
    import java.io.FileReader;
    public class generateGML{
    public static void main(String[] argv)
    throws Exception{
    BufferedReader fh = new BufferedReader(new FileReader("filename.txt"));
    String s;
    while ((s=fh.readLine())!=null){
    String[] columns = s.split("\t");
    String name = columns[0];
    String place = columns[1];
    String value = columns[2];
    It reads columns,But I want it two dimentionally,as in something like matrix[row_num][column_num].
    Can anyone please suggest me..

    You could do the following:
    String[][] array = new String[rows][];
    int row_num = 0;
    while ((s=fh.readLine())!=null) {
       array[row_num++] = s.split("\t");
    }However, you need to know ahead of time how many rows to allocate. If you allocate more than needed, you'll need to copy to a new array, or you'll need to keep track of how much is actually populated. If you allocate less than needed, you'll get an ArrayIndexOutOfBoundsException.
    Another (likely better) approach is:
    Do you really need it as a 2-dimensional array? Can you make a List of objects that have a name, place, and value? Then you don't need to know how big of a list to allocate ahead of time, assuming you use a list that grows itself (like ArrayList or LinkedList). Your code would be much easier to read if you could say:
    String name = list.get(10).getName();instead of
    String name = array[10][0];

  • How to read a text/html file in java regardless of its encoding?

    Hi All,
    How to read a text/html file in java regardless of its encoding?
    1. Is there any way to identify that a file (read using FileInputStream/or any other means with java.io package) has been saved with which type of encoding i.e. whether the file is using ANSI encoding or Unicode encoding or other?
    2. Is there any standard way to read an encoded file (i.e. files having UTF-16 format for Asian locales character support) and un-encoded file (i.e. files having ordinary ANSI format) correctly without knowing the user input?
    The problem is that while creating an instance of 'InputStreamReader' (ISR) we can pass the encoding type used (otherwise it takes the system's default encoding type), and the ISR expects the file to be in the same encoding format otherwise it reads it as some junk. But we don't know which file the user is going to pass whether it is Unicode (for Asian locales file should be in Unicode) with or ANSI coded (for non-Asian / English locales user generally uses ANSI encoding).
    Regards,
    Sam

    1. There is no reliable way of guessing the encoding of a file without that information. Thats why XML for example has very strict rules wrt. it's encoding (short form: use UTF-8 or UTF-16, if you use anything else, you'll have to specify it)
    2. you might be able to make an educated guess if the possible range of encodings is limited, but it will probably never be 100% certain
    3. The HTML file might have a header entry "<meta http-equiv..." that tells you about it's encoding. You could try to read the start of the file and see if you find that, then if you found it re-read the entire file.
    regards

  • Combining form files

    I have 286 separate pdf form files that I need to combine to one pdf file so that I can export the text into a spreadsheet. Problem is that when I combine the files, Acrobat replaces the data on the forms with the data from the first file. For example, one of the fields is 'Name'. When i combine the files, Acrobat fills in the name from the 1st file to all 286 pages of the combined pdf. Obviously this is a big problem. Does anyone know of a remedy for this problem?

    Thank you so much! It looks like this function SHOULD do exactly what I need it do; but, there is a bug in the function. When I run it, it only enters the name of each file in the spreadsheet. Adobe is looking into it and gave me a case# to check back for a fix in 24-48 hrs. Hopefully they can fix the issue.   Thank you again!

  • Inserting text form a textfile into a JtextArea

    Hi,
    Im trying to insert text form a textfile into a JtextArea ex the textFile is called Words.txt
    JTextArea ta  = new JTextArea();
    ta.insert("Words.txt", 0);what im getting in the textarea is Words.txt and not the text in it.
    So what shall i do to place the text in the textarea??
    Matt

    Shall i pass the the name of the file ??Not sure where you would get that idea as a String is, well, a String and NOT a Reader.
    Did you read the javadoc for Reader? Well, luckily I did and one type of Reader is a FileReader, which, amazingly enough, reads characters from a file. So, when you give the JTextArea (a type of JTextComponent) the Reader, it will read characters until its done, inserting them into its Document. Putting this all together, you get:
    // yes, finally the string you pass refers to a file name
    textArea.read(new FileReader("Words.text"),null);

  • Splitting an input file using Transformation agent

    Hi, I am trying to use transformation agent (adobe output central pro v5.5) to take and input file and split it into many output files based on a text string in the file.
    However instead of splitting the file it, each output file containts all the input records upto the next file boundary. What I need is just the records between the file boundaries.
    Any ideas what I have got wrong, or could this be a feature of the Trans Agent?
    my TDF file is;
    O " N 1500 N N N N O
    F "^$PAGE 1" 1 8 -5
    E data1 * "" 1 0 * 1 60 0 0 ""
    #startscript Head
    ^job invoice_arch.pdf
    #endscript
    #startscript *
    #for data1
    @data1
    #endfor
    #endscript
    thanks in advance
    Stephen

    Hi there,
    If you are still interested in splitting a data file, please drop me a email and I will forward a document that I wrote to achive this.
    Andrew Purdy
    Enterprise Solutions
    [email protected]

  • Upload text delimited file

    could someone please provide a sample code of how to upload a text "|" delimited file into SAP internal structure?  i used GUI_upload with field_separator but didn't work.  many thanks.

    HI Voo,
    i think this is the FM you are looking for..
    see the sample functionality ..
    DATA: BEGIN OF itab OCCURS 0,
            vbeln LIKE vbak-vbeln,
            ernam LIKE vbak-ernam,
          END OF itab.
    DATA itab2 LIKE TABLE OF KCDE_CELLS WITH HEADER LINE.
    CALL FUNCTION 'KCD_CSV_FILE_TO_INTERN_CONVERT'
      EXPORTING
        i_filename            = 'D:dataupl.txt'
        i_separator           = '|'
      tables
        e_intern              = itab2
    * EXCEPTIONS
    *   UPLOAD_CSV            = 1
    *   UPLOAD_FILETYPE       = 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.
    LOOP AT itab2.
      SPLIT itab2-value AT '|' INTO itab-vbeln itab-ernam.
      APPEND itab.
      CLEAR itab.
    ENDLOOP.
    And the file: upl.txt
    12345|text
    12346|text2
    12347|text3
    regards
    satesh

  • Syndicator Server: possible to split the export file in multiple file?

    Hello,
    is it possible to split the export files into multiple files e. g. at 5000 records?
    Perhaps there is a possibility in the mdss.ini? Or a setting in the mapping?
    Thank your for your responses!
    Melanie

    Hi Melanie,
    - If you are syndicating in the Xml format you have the option to syndicate one xml for every record. or multiple records one xml.
    For this you have to make a simple setting in the Syndicator-> Map properties->XML file output->(multiple files/single file)
    Other way around is:
    - If you are syndiacting in any other format say text then the output file goes as one file for all records present in the MDM repository, for this you can use the search options.
    - Create a search on some field value which will select a set of records from the lot.
    - Then you can syndicate only those records which satisfies the  search criteria.
    - In this way it is possible to syndicate in parts
    Hope It Helped,
    Kindly Reward Points if found useful
    Thanks & Regards
    Simona Pinto

  • How to save and open Text/csv file over APS

    Hi,
    I want to save(and open later) data from database block in text/csv file format over Application server, I did a lot of search here on Forms but didn't found a reasonable solution, Some one plz help me.
    Thanks and Regards, Khawar.

    As long as you are using the Report Generation Toolkit, there is no need to use ActiveX for the purpose of saving the Excel file -- Save Report will do that for you.  You can then export (as text) all of the Excel data and use the Write Spreadsheet File to make the .CSV file.  Here is how I would rewrite the final bits of your code --
    I cleaned up the wires around Excel Easy Table a bit.  You'll see I made a VI Icon for Replace Filename, which does (I think) a nicer job of self-documenting than showing its Label.  To make the filename, add the correct extension (.xlsx for Excel, .csv for CSV), use Build Path to combine Folder and Filename, and wire to Save Report.
    The next two functions add the Extract Everything and Write to Spreadsheet, using a Comma as a separator, which makes a CSV copy for you.
    Bob Schor

  • Append text in file. and save it

    Append text in file.
    hi!
    i am new j2me Programer.
    1.i want to add(APPEND) the text in the file. i take this code form internet but i could succed Please help me.
    2.i want to save it in other directory like if i made folder on mobile device with name c:\Old i want to save file in that how could i ?
    kindly mention the Mistake.
    package FileConnection;
    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    import java.io.*;
    import javax.microedition.io.*;
    * @author QTracker
    public class FileConnection extends MIDlet implements CommandListener {
    private boolean midletPaused = false;
    private Command exit, start;
    private Display display;
    private Form form;
    public FileConnection ()
    display = Display.getDisplay(this);
    exit = new Command("Exit", Command.EXIT, 1);
    start = new Command("Start", Command.EXIT, 1);
    form = new Form("Write To File");
    form.addCommand(exit);
    form.addCommand(start);
    form.setCommandListener(this);
    private void initialize() { }
    public void startMIDlet() { }
    public void resumeMIDlet() {/
    public void switchDisplayable(Alert alert, Displayable nextDisplayable) {
    Display display = getDisplay();
    if (alert == null) {
    display.setCurrent(nextDisplayable);
    } else {
    display.setCurrent(alert, nextDisplayable);
    public Display getDisplay () {
    return Display.getDisplay(this);
    public void exitMIDlet() {
    switchDisplayable (null, null);
    destroyApp(true);
    notifyDestroyed();
    public void startApp() {
    display.setCurrent(form);
    public void pauseApp() {
    midletPaused = true;
    public void destroyApp(boolean unconditional) {
    public void commandAction(Command c, Displayable d) {
    if (c == exit)
    destroyApp(false);
    notifyDestroyed();
    else if (c == start)
    try
    OutputConnection connection = (OutputConnection)
    Connector.open("file:\\c:\\myfile.txt;append=true", Connector.WRITE );
    OutputStream out = connection.openOutputStream();
    PrintStream output = new PrintStream( out );
    output.println( "This is a test." );
    out.close();
    connection.close();
    Alert alert = new Alert("Completed", "Data Written", null, null);
    alert.setTimeout(Alert.FOREVER);
    alert.setType(AlertType.ERROR);
    display.setCurrent(alert);
    catch( ConnectionNotFoundException error )
    Alert alert = new Alert(
    "Error", "Cannot access file.", null, null);
    alert.setTimeout(Alert.FOREVER);
    alert.setType(AlertType.ERROR);
    display.setCurrent(alert);
    catch( IOException error )
    Alert alert = new Alert("Error", error.toString(), null, null);
    alert.setTimeout(Alert.FOREVER);
    alert.setType(AlertType.ERROR);
    display.setCurrent(alert);
    }

    | Moderator advice: | Please read the announcement(s) at the top of the forum listings and the FAQ linked from every page. They are there for a purpose. |
    | | Please don't post in threads that are long dead and don't hijack another poster's thread. |
    | | Please don't solicit off forum communication by email. |
    | Moderator action: | The other four posts you made have been deleted. |
    db

  • How can I Split the PDF File into different pages?

    Hi,
    My requirment is to split the pdf file , which is obtained by using FM "convert_otf" , into seperate PDF file for each employee data(PERNR).
    Please suggest me the way to slipt the PDF file that has to be downloaded into the presentation server.

    Hi,
    Ok, looking at that programm didn't actually help me very much to understand what's going on, or where you have the CONVERT_OTF call... Regardless, if the suggestion by Raymond is not feasible in your scenario, the thing I'd try to do is - splitting the spool (OTF) contents before calling CONVERT_OTF into individual documents (feeding it to convert FM piecemeal)... The link to OTF format and commands documentation is here.
    Again, it's difficult to give a good algorithm without knowing the exact OTF contents (could you perhaps somehow export the display of spool in RAW format and attach here?) but it would boil down to approximately following:
    1) set the &first_page per PERNR = 1;
    2) run through OTF lines until the &end_page for PERNR has been identified somehow (hopefully there are Begin/End Form OTF commands '//' in that spool... and they correspond to the split of spool you need...);
    3) extract the otf contents from &first_page to the EP command of &end_page into separate OTF itab and, if necessary, add // (End of form) command at the end of itab;
    4) call CONVERT_OTF on the table and download;
    5) set the &first_page per PERNR = &end page + 1;
    6) repeat from 2) until end of spool OTF data
    Something like that... Depending how the Sapscript translates into OTF, you may also need to prepend a few commands found at the very beginning of the spool to each extracted invividual OTF document...
    I Hope you can get the gist of what I'm suggesting... splitting OTF is definetly easier than trying to split PDF, I feel. It's not ideal solution, because - what if the structure of OTF contents you would be realying on changes for some reason..?
    cheers
    Janis

Maybe you are looking for

  • Question about Ram upgrade on a Satellite Pro A200

    I want to purchase some internal memory for my A200 Satellite Pro Mod No,PSAE1E but I cannot find my model in the drop down lists, which memory do I need, I want to upgrade using two 1GB memory sticks, at present I have two 512MB sticks installed.

  • How can I rebuild an iTunes library, lost due to network HD failure?

    I had it installed on separate server disc, but disk failed. I'd like to start with new library, based on iCloud, and only using the purchased content initially. The boards seem to suggest issues with iCloud and iTunes Match, so I am reluctant to go

  • Use of BEFORE_EXPORT Method in transaction SOBJ

    Hello,    My Requirement:       I have to add database table entries to my task before releasing the transport request, if my Transport task contains eCATT object type.      So I have developed a function module which adds table entries to transport

  • Gather_table_stats in a batch process

    Hi everyone, we have a bit of a problem with several batch processes. Their basic structure of a batch process this 1. do some init tasks - record the batch process as running, load parameters etc. generally a very simple tasks (haven't seen those to

  • How can i get Itunes to let me back up my original iPad onto my pc

    How can I get iTunes to let me back up my original iPad onto my pc