Loading large text files into java vectors and outof memmory

Hi there,
need your help for the following:
i'm trying to load large ammoubnts of data into a Vector in order to concatenate several text files and treat them, but i'm getting outofmemory error. I even tried using xml structure and saving to database but the error is still the same. Can you help?
thanks
here's the code:
public void Concatenate() {
try {
//for(int i=0;i<1;i++) {
vEntries =  new Vector();
for(int i=0;i<BopFiles.length;i++) {
MainPanel.WriteLog("reading file " + BopFiles[i] + "...");
FileInputStream fis = new FileInputStream(BopFiles);
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream in = new DataInputStream(bis);
String line = in.readLine();
Database db = new Database();
Connection conn = db.open();
while(line != null) {
DivideLine(BopFiles[i], line);
line = in.readLine();
FreeMemory(db, conn);
MainPanel.WriteLog("Num of elements: " + root.getChildNodes().getLength());
MainPanel.WriteLog("Done!");
} catch (Exception e) {
e.printStackTrace();
public void DivideLine(String file, String line) {
     if (line.toLowerCase().startsWith("00694")) {
          Header hd = new Header();
          hd.headerFile = file;
          hd.headerLine = line;
          vHeaders.add(hd);
     } else if (line.toLowerCase().startsWith("10694")) {
          Line entry = new Line();
          Vector vString = new Vector();
          Vector vType = new Vector();
          Vector vValue = new Vector();
          entry.name = line.substring(45, 150).trim();
          entry.number = line.substring(30, 45).trim();
          entry.nif = line.substring(213, 222).trim();
          entry.index=BopIndex;
          entry.message=line;
          entry.file=file;
          String series = line.substring(252);
          StringTokenizer st = new StringTokenizer(series, "A");
          while (st.hasMoreTokens()) {
               String token=st.nextToken();
               if(!token.startsWith(" ")) {
                    vString.add(token);
                    vType.add(token.substring(2,4));
                    vValue.add(token.substring(4));
               token=null;
          entry.strings= new String[vString.size()];
          vString.copyInto(entry.strings);
          entry.types= new String[vType.size()];
          vType.copyInto(entry.types);
          entry.values= new String[vType.size()];
          vValue.copyInto(entry.values);
          vEntries.add(entry);
          entry=null;
          vString=null;
          vType=null;
          vValue=null;
          st=null;
          series=null;
          line=null;
          file=null;
          MainPanel.SetCount(BopIndex);
          BopIndex ++;
public void FreeMemory(Database db, Connection conn) {
try {
//db.update("CREATE TABLE entries (message VARCHAR(1000))");
               db.update("DELETE FROM entries;");
               PreparedStatement ps = null;
               for( int i=0; i<vEntries.size(); i++ ) {
                    Line entry = (Line) vEntries.get(i);
                    String value = "" + entry.message;
                    if(!value.equals("")) {
                         try {
                              ps = conn.prepareStatement("INSERT INTO entries (message) VALUES('" + Tools.RemoveSingleQuote(value) + "');");
                              ps.execute();
                         } catch(Exception e) {
                              e.printStackTrace();
                              System.out.println("error in number->" + i);
               MainPanel.WriteLog("Releasing memory...");
     vEntries = null;
     vEntries = new Vector();
     System.gc();
          } catch (Exception e1) {
               e1.printStackTrace();

Well, i need to treat those contents, and calculate values withing those files, so wrinting files using FileInputstream wont do. for instance i need to get line 5 from file 1, split it, grab a value according to its class (value also taken) and compare it with another line of another file, adding those values to asingle file.
that's why i need vector capabilities, but since these files have more than 5 Mb each, an out of memory error is returned by loading those values into vector.
A better explanaition:
Each file has a line like
CLIENTNUM CLASS VALUE
so if the client is the same withing 2 files, i need to sum the lines into a single file.
If class is the same, then sum values, if not add it to the front.
we could have a final line like
CLIENTNUM CLASS1 VALUE1 CLASS2 VALUE2

Similar Messages

  • How to read some records from a text file into java(not all records)

    hello,
    how to read text files into java. i need only few records from the text file not all records at a time.
    If any one knows plz reply me
    my id is [email protected]

    this snipet reads a text file line by line from line 1 to 3
    try {
                  FileReader fr = new FileReader(directory);
                  BufferedReader br = new BufferedReader(fr);
                  int counter = 0;
                  while ((dbconn = br.readLine()) != null) {
                      switch(counter){
                          case 0:
                            status = dbconn;
                          break;
                          case 1:
                            userName = dbconn;
                          break;
                          case 2:
                            apword = dbconn;
                          break;
                      counter++;
                  br.close();
        }catch(IOException e){
        }

  • How do I import an InDesign tagged text file into multiple pages and export as .ps or .pdf using Jav

    I have an InDesign tagged text file I've translated from .xml. I need to automate the following steps:
    1 - access specific InDesign template (eg. ABC_template.ind)
    2 - import tagged text file into InDesign
    3 - autoflow text to END of document (normally around 3-5 pages)
    4 - save document as either .ps or .pdf file
    5 - where the input file stub name matches the output stub name (eg., OrigName.txt outputs as OrigName.pdf).
    I would like to completely automate this whole process using JavaScript (because I don't know anyone that knows AppleScript). I've automated the first part using a perl script. I've been trying to find sample snipits of JavaScript that would do one or more of the items listed above, but am having a hard time finding what I need.
    Please, I'm desperate!! Can any of you InDesign scripting guru's out there help me??
    Thanks in advance!!
    LindaD

    Hi Linda,
    I might be able to help you out. You can contact me by email (click on my user name for the address), or if you post your email here.

  • How can I use sql loader to load a text file into a table

    Hi, I need to load a text file that has records on lines tab delimited into a table. How would I be able to use the sql loader to do this? I am using korn shell to do this. I am very new at this...so any kind of helpful examples or documentation would be very appreciated. I would love to see some examples to help me understand if possible. I need help! Thanks alot!

    You should check out the documentation on SQL*Loader in the online Oracle document titled Utilities. Here's a link to the 9iR2 version of it: http://otn.oracle.com/docs/products/oracle9i/doc_library/release2/server.920/a96652/part2.htm#436160
    Hope this helps.

  • How to load content of my text file into a Vector?

    Hi!
    Two questions.
    Let say I have used BufferedReader(new FileReader(c:/java/MyText.txt)) to read from MyText.txt file. I want to know how to load content of this file (every line describe each photo in my photo-set) into a Vector? And how to associate lines of MyText.txt as an elements of the Vector?
    I am trying to do something, but no results.
    try{
    BufferedReader reader = new BufferedReader(new FileReader("c:/java/Applications/MyText.txt"));
    String str=reader.readLine();
    JList myList = new JList();
    StringTokenizer st = new StringTokenizer(str,"\n");
    Vector vr = new Vector(25);
    while(st.hasMoreTokens()){
    String nextToken = st.nextToken();
    vr.addElement(nextToken);
    myList.setListData(vr);
    TA1.setText(TA1.getText()+
    (String)myList.getSelectedValue());
    }catch(IOException evt) {};

    BufferedReader reader = new BufferedReader(new FileReader("c:/java/Applications/MyText.txt"));
    Vector photos = new Vector(0,0);
    while(reader.ready())
       photos.addElement(reader.readLine());
    }good luck,
    Felipe

  • Loading large text files in JTextArea

    JTextArea can't seem to load an 8MB text file, as doing so will throw an OutOfMemoryError. The problem is, 8MB really isn't that much data, and there are files in our system which are much bigger than that. And I'm at a loss to find why a mere 8MB is causing Java to run out of its 64MB of memory.
    So I'm starting to try another approach.
    Here's the idea:
        public void doStuff() {
            Reader reader = dataStore.retrieve(...);
            RandomAccessFile tempFile = new RandomAccessFile(...);
            FileChannel tempChannel = tempFile.getChannel();
            // CODE OMITTED: copying reader to tempChannel as Java chars.
            // Now, map the file into memory.
            CharBuffer charBuffer = tempChannel.map(FileChannel.MapMode.READ_WRITE, 0, fileLength).asCharBuffer();
            Document doc = new CharBufferDocument(charBuffer);
            textArea.setDocument(doc);
        }This should work in theory. The problem I'm having is figuring out how to make this custom document.
    Here's what I have so far:
        public class CharBufferDocument extends PlainDocument {
            private CharBufferDocument(CharBuffer charBuffer) {
                super(new CharBufferContent(charBuffer));
        class CharBuffeclass CharBufferContent implements AbstractDocument.Content {
            private CharBuffer charBuffer;
            private CharBufferContent(CharBuffer charBuffer) {
                this.charBuffer = charBuffer;
            public Position createPosition(int offset) throws BadLocationException {
                return new FixedPosition(offset);
            public int length() {
                return charBuffer.length();
            public UndoableEdit insertString(int where, String str) throws BadLocationException {
                throw new UnsupportedOperationException("Editing not supported");
            public UndoableEdit remove(int where, int nitems) throws BadLocationException {
                throw new UnsupportedOperationException("Editing not supported");
            public String getString(int where, int len) throws BadLocationException {
                Segment segment = new Segment();
                getChars(where, len, segment);
                return segment.toString();
            public void getChars(int where, int len, Segment txt) throws BadLocationException {
                char[] buf = new char[len];
                // Sync this, as the get method moves the cursor.
                synchronized (this) {
                    charBuffer.get(buf, where, len);
                    charBuffer.rewind();
                txt.array = buf;
                txt.offset = where;
                txt.count = len;
        class FixedPosition implements Position {
            private int offset;
            private FixedPosition(int offset) {
                this.offset = offset;
            public int getOffset() {
                return offset;
        }When I run this, I get a text area which only shows one character. What's happening is that my getChars(int,int,Segment) method is being called from Swing's classes, and only being asked for one character!
    Does anyone have any idea how this is supposed to work? It seems that if Swing only ever asks for the first character, I'm never going to be able to display 8,000,000 characters. :-)

    Not too sure though how to go about reading the last 5 lines say.One solution would be to read in an increasingly large block (estimate the typical line size * 5 + some bonus) of the file starting at position file size[i] - block size. As long as the block doesn't contains 5 complete lines (count newline chars), increase it by a given size and try again. Should still be faster than scanning the whole file from start to end.

  • Loading a text file into a global variable issue - really a global var?

    From all the documentation and examples I can find, it appears that it would be
    correct to create a global array variable [outside of any functions] to load image names into,
    then use these images for a slideshow. I want to make the app dynamic, in that changing the text file gives a new set of images.
    The global variable goes null [no values] after the load event listener. Why is that?
    Isn't global, well global, and alive for the duration of the SWF?
    PARAMS.TXT:
    monthNames=January,February,March,April,May,June,July,August,September,October,November,De cember&dayNames=Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday
    CODE:
    var dNames:Array = new Array();
    var mNames:Array = new Array();
    var request:URLRequest = new URLRequest("images/params.txt");
    var variables:URLLoader = new URLLoader();
    variables.dataFormat = URLLoaderDataFormat.VARIABLES;
    variables.addEventListener(Event.COMPLETE, completeHandler);
    try
    variables.load(request);
    catch (error:Error)
    trace("Unable to load URL: " + error);
    trace("2 mNames 2: " + mNames[2]);
    trace("2 dNames 3: " + dNames[3]);
    stop();
    function completeHandler(event:Event):void
    var loader:URLLoader = URLLoader(event.target);
    dNames = loader.data.dayNames.split(",");
    mNames = loader.data.monthNames.split(",");
    trace(loader.data.dayNames);
    trace("1 mNames 2: " + mNames[2]);
    trace("1 dNames 3: " + dNames[3]);
    OUTPUT:
    2 mNames 2: undefined
    2 dNames 3: undefined
    Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday
    1 mNames 2: March
    1 dNames 3: Wednesday
    How do I access these values after loading from the external file, after the load?
    Thanks in advance.

    The statement you quoted from whatever Adobe documentation is correct.
    If you want to load the data into the arrays before anything else happens, then have anything else that happens execute via the completeHandler function... after the data is loaded and processed into the arrays.
    the command: loadFile() executes before the trace("2:" +images[4]); command.  The loadFile function is processed and the loading process BEGINS... but starting the loading does not delay the main processing from continuing down the line--the loading itself becomes a secondary/background task.  The command was to execute the loadFile function and the processing of that function was completed.  If you don't believe so, then add a trace...
    function loadFile():void
         vars.dataFormat = URLLoaderDataFormat.VARIABLES;
         vars.addEventListener(Event.COMPLETE, onComplete, false, 0, true);
         vars.load(new URLRequest("images/fnames.txt"));
         trace("started loading");
    If you add that trace, you should see that the loadFile function execution is completed and the next line in your code is then processed... trace(2....)
    The addEventlistener does not stop anything.  The addEventListener code is assigning a monitor, not a traffic controller... it is telling the monitor to indicate when the data has finished loading.  It is not telling anything to stop program execution.
    So if you want to wait until the data is loaded before you do anything else... it goes....
    function onComplete(evt:Event):void
         var urlVars:URLVariables = evt.target.data;
         images = vars.data.images.split(",");
         tnails = vars.data.thumbnails.split(",");
         ................HERE.................

  • Loading XML Configuration File into Java

    I have a stored procedure wrapper to a Java method (within a jar file) that has been loaded into the database. I need to load an XML configuration file in this method and parse it but get the following error.
    <Line 2, Column 192>: XML-24538: (Error) Can not find definition for element 'LODConfigs'
    When I run the method standalone through netbeans it parses fine and is able to load the file. I've confirmed that it is able to read the file but I am lost as to what could be the problem. Any suggestions would be welcome.
    The header of the file is
    <?xml version="1.0" encoding="UTF-8" ?>
    <LODConfigs xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.oracle.com/spatial/network/lodLODConfigs.xsd"
    xmlns="http://xmlns.oracle.com/spatial/network">
    <LODConfig globalNetworkName="$DEFAULT$" networkName="$DEFAULT$">
    <networkIO>
    </networkIO>
    </LODConfig>
    </LODConfigs>

    Just a guess really, (and this is an old question now - so you may have moved on).. is your XML parser attempting to use the schema location to pull the XML schema from the internet?
    If so, that might run fine in netbeans, but hit java permission limits in Oracle. Have you tried running it in netbeans with the network cable unplugged.
    If that fails with the same error as the Oracle JVM, that might give a clue as to the problem and you can troubleshoot the permissions from there.

  • Splitting large video files into small chunks and combining them

    Hi All,
    Thank you for viewing my thread. I have searched for hours but cannot find any information on this topic.
    I need to upload very large video files. The files can be something like 10GB in size, currently .mpeg format but they may be .mp4 format later on too.
    Since the files will be uploaded remotely using using internet from the clients mobile device (3G or 4G in UK) I need to split the files into smaller chunks. This way if there is a connection issue (very likely as the files are large) I can resume the upload without doing the whole 10gb again.
    My question is, what can I use to split a large file like 10Gb into smaller chunks like 200mb, upload the files and then combine them again? Is there a jar file that I can use. i cant install stuff like ffmpeg or JMF on the clients laptops.
    Thank you for your time.
    Kind regards,
    Imran

    There is a Unix command called split that does just that splits a file into chunks of a size you specify. When you want to put the bits bact together you use the command cat.
    If you are comfortable in the terminal you can look at the man page for split for more information.
    Both commands are data blind and work on binary as well as text files so I would think this should work for video but of course check it out to see if the restored file still works as video.
    regards

  • Loading a text file into Terminal App

    Hi,
    I  am  trying  to  load  a  textfile  into  my  Terminal  App  using  the  Import  utility  under  the  Shell  drop  down  menu.
    But  when  I  try  choosing  the  text  files  after  clicking  Import,  I  am   unable  to  select  a  text  file  because  they  are 
    all  greyed  out. Only  folders  seems  to  be  selectable.
    Please  help.

    I have no idea what you are trying to do. What does "load a textfile" mean?
    The Import… command is for importing a Terminal settings file (exported using the Export Settings… command on another computer or user).

  • How to load external text file into a Form?

    Hi,
    I made a menu with 1-5 in a Form and 5 external text files. I want the user who is able to view the text content of the text file when he chooses one of them from the menu. And the text file screen has a "Back" command button to let him go back.
    How can I do it and can it support other languages such as Chinese and Japanese?
    Thanks for help.
    gogo

    Sorry, I made the mistake about the subject, it should be loading local file, not external file through http.
    I wrote a method but it throwed an exception when the midlet was run.
    private void loadText()
    try {
    InputStream is = this.getClass().getResourceAsStream("/text.txt");
    StringBuffer sb = new StringBuffer();
    int chr;
    while ((chr = is.read()) != -1)
    sb.append((char) chr);
    is.close();
    catch (Exception e)
    System.out.println("Error occurs while reading file");
    I put the text.txt file in the same folder with the main file (extends midlet). How can I load the text content and display it on StringItem?
    Thanks for any help.
    gogo

  • Loading large text files to find duplicates

    Hi there,
    I have several files with 500 chars long at each line, and for each one i need to get a number (at index 213, 222), to make sure only one exists.
    I also need to take the last 250 lines to manipulate them according to the number given.
    The problem is that i've tried to store those results either in a vector or in a a table (using hsqldb), but in both case i get out of memory error while processing more than 74000 results.
    So what to do?
    Here's the code:
         public void Concatenate() {
              try {
                   vClients =  new Vector();
                   GroupIdentical = Main.getProp("javabop.group.identical", "N");
                   if(GroupIdentical.equalsIgnoreCase("s")) vNifs =  new Vector();
                   for(int i=0;i<BopFiles.length;i++) {
                        BoPPanel.WriteLogPane("A ler ficheiro " + BopFiles[i] + "...");
                        FileInputStream fis = new FileInputStream(BopFiles);
                        BufferedInputStream bis = new BufferedInputStream(fis);
                        DataInputStream in = new DataInputStream(bis);
                        String line = in.readLine();
                        //BoPPanel.SearchPane.append("\n Ficheiro " + BopFiles[i] + "\n\n");
                        while(line != null) {
                             if(line.toLowerCase().startsWith("10694")) {
                                  GetEntry(BopFiles[i], line);
                                  //BoPPanel.SearchPane.append(line + "\n");
                             } else if (line.toLowerCase().startsWith("00694")) {
                                  Header hd = GetHeader(BopFiles[i], line);
                                  vHeaders.add(hd);
                             line = in.readLine();
                        fis.close();
                        bis.close();
                        in.close();
                        System.gc();
                   BoPPanel.WriteLogPane("Numero de elementos obtidos nos ficheiros: " + vClients.size());
                   BoPPanel.WriteLogPane("Concatena��o conclu�da!");
                   //if(GroupIdentical.equalsIgnoreCase("s")) FindDuplicated();
              } catch (Exception e) {
                   e.printStackTrace();
                   Main.WriteLogFile(e.getMessage());
         public Header GetHeader(String file, String line) {
              Header hd = new Header();
              hd.headerFile = file;
              hd.headerLine = line;
              vHeaders.add(hd);
              return hd;
         public void Saveintable(int num, int nif, String file, int index, String series, String line) {
              try {
                   Database db = new Database();
                   Connection conn = db.open();
                   //db.update("DROP TABLE Save");
                   //db.update("CREATE TABLE Save ( num INTEGER, nif INTEGER, file VARCHAR(100), index INTEGER, series VARCHAR(150), line VARCHAR(500))");
                   //db.update("DELETE FROM Save;");
                   String sqlInsert="INSERT INTO Save (num, nif, file, index, series, line) "
                        + " VALUES (?,?,?,?,?,?)";
                        PreparedStatement prep = conn.prepareStatement(sqlInsert);
                        prep.setInt(1, num);
                        prep.setInt(2, nif);
                        prep.setString(3, file);
                        prep.setInt(4, index);
                        prep.setString(5, series);
                        prep.setString(6, line);
                        prep.executeUpdate();
                        //prep.close();
                        //conn.close();
              } catch(Exception e) {
                   e.printStackTrace();
         public void GetEntry(String file, String line) {
              String series = line.substring(252).trim();
              String numberstr = line.substring(30, 45).trim();
              String nifstr = line.substring(213, 222).trim();
              int num=0;
              if(!numberstr.equals("")) num=Integer.parseInt(numberstr);
              int nif=0;
              if(!nifstr.equals("")) nif=Integer.parseInt(nifstr);
              if(GroupIdentical.equalsIgnoreCase("s") && !nifstr.equals("")) vNifs.add(nifstr);
              Saveintable(num, nif, file, BopIndex, series, line);
              BoPPanel.SetCount(BopIndex);
              BopIndex ++;

    here's the example fo 2 lines:
    10694000000000200000000000000H000000001000504AAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAA                                                                                                                     195501231504PRT50YYYYYYYYY                     3 04000000000029000A                                                           
    10694000000000300000000000000H000000001000153BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB                                                                                                                       195110151105PRT501XXXXXXXXX                     2 04000000000079680A                                                            I need to take out the numbers YYYYYYYYY and XXXXXXXXXXX and see if they match (there are 4 files with a total of 840000 lines and i need to concatenate all info from the files in only one and if they are the same i need to sum the values ending with A (29000A and 79680A).
    Now imagine this for those 840000 lines....

  • How to load word .doc-files into java applications?

    Hi,
    I want to load a word .doc-file (or any other type of document) into a java application, as part of the application.
    Is there any java special library to do it?
    Any solution or hint?
    Thank you.

    No, there is no existing Java library to do it that I am aware of. You could write your own, however, as the Word 97 binary file format is published. I am not sure that the Word 2000, or XP formats are as well, but since they put out the 97 presumably they'd do the same with the rest -- although I am suprised that Micro$$$oft even published the 97 format.
    A library such as this would take quite some time write, due to the extensive format, but here's a link to a copy of it just so you can see what it'd take: http://www.redbrick.dcu.ie/~bob/Tech/wword8.html
    Also keep in mind that Micro$$$oft has never remained binary compatable between versions. In short, this means that you'd have to parse each version's documents differently. Not a fun task.
    If a Java library to read Micro$$$oft file formats already does exist, I'm willing to bet that it costs $$$ mucho dinero $$$.
    Hey, aren't proprietary file formats just wonderful?

  • How to load a text file int JEditorPane and highlight some words (Urgent !)

    I want to load a text file into a JEditorPane and then highlights some keywords such as while,if and else.I am using an EditorKit in order to style the JEditorPane. I have no difficulty while giving the input through the keyboard but lots of exceptions are thrown if i try to load the string from a file.

    Hi,
    I think the setCharacterAttributes(int offset, int length, AttributeSet s, boolean replace) will solve the problem.
    You can create your own Styled Document and set it to the Editor Pane.

  • Loading a text file on startup into a hashtable

    I am trying to load to seperate textfiles into the same hashtable.
    The textfiles are something like an employee and employee number everything goes in at the same time. How do i load these text files into the hashtable. Also any good tutorials or code samples on hashtables would be greatly appreciated.
    Thanks In Advance

    You read the text files, one line at a time, and break up each line in whatever way you need to. Then you choose the bits to put in the hashtable (key and value) for each line and put those bits into the hashtable.
    http://java.sun.com/docs/books/tutorial/essential/index.html
    http://java.sun.com/docs/books/tutorial/collections/index.html

Maybe you are looking for

  • How do I close a PDF document automatically when the browser is closed?

    I have a web app writen in HTML/ASP. In order to acccess this app, our users have to enter a password and user id. Once on the main page of the app, they can click on a link which opens the reader in another window. Quite often, when finished with th

  • Opening excel file in macbook

    while opening an excel file created in other computer which is not apple, there are always some strange characters that can be read. how can i solve this problem

  • Macbook External Screen Mirror?

    Hey guys, I finally have everything I need to coonect my Sony 40" 1080p television to the macbook. I have a mini-dvi to dvi adapter and a dvi to hdmi cable. I was seeing how it works and when I turn on mirror mode for the display I can see everything

  • Will boot camp support windows XP? thanks.

    hello. does anyone kow if boot camp will support windows XP? thanks.

  • BW Extractors for NON-BW Data Warehouse

    Hi, I am working on a client who wishes to use a custom developed Data Warehouse. Is there any way to use SAP's standard extractors to extract data to these non-sap dw systems (or download the data in flat file format from extractor after run)? We ar