Unable to read big files into string object  and java.lang.OutOfMemory Prob

Hi All,
I have an application that uses applet and servlet communication. On the client side I am reading an large xml file of 12MB size (using JFileChooser) and converting the file to an string object using below code. But I am getting java.lang.OutOfMemory on the client side . But the same below code works fine for small xml files which are less than 4MB sizes:
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF8"), 1024*12);
String s, s2 = new String();
while((s = in.readLine())!= null)
     s2 += s + "\n";
I even tried below code but still java.lang.OutOfMemory is coming:
while (true)
     int i = in.read();
     if (i == -1)
          break;
     sb.append(i);
Please let me know what am I doing wrong here ...
Thanks & Regards,
Sony.

Using a String is bad for the following reason:
When you initially create the String, it has a certain memory size (allocated length if you will). As you keep appending to this String, then memory reallocation will occur over and over, slowing your program down dramatically (ive seen with a 16k x 8 Char file taking 30 secs to read into memory using Strings in this way)
A Better way would be if you knew the number of characters in the XML file (Using some File size method for example) Then you can use a StringBuffer, which will pre allocate enough space (or try to, it may just be that you cannot create a string as large as you need). You can use toString() method to get the resultant in a String Object (the extra allocated space at the end of the Buffer will be removed)
StringBuffer strBuf = new StringBuffer(xxxx);
Where xx is the length (int). Assuming that you are only allowed to enter an int to the constructor then (platform depedant) an int is 2^31 at maximum (or whatever) which allows 2.14e9 characters, therefore an xml file being totally filed would allow a size of ~2048 MB to be read in.
Try it and see.

Similar Messages

  • Unable to read big files into string object & java.lang.OutOfMemory Problem

    Hi All,
    I have an application that uses applet and servlet communication. On the client side I am reading an large xml file of 12MB size (using JFileChooser) and converting the file to an string object using below code. But I am getting java.lang.OutOfMemory on the client side . But the same below code works fine for small xml files which are less than 4MB sizes:
    BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF8"), 1024*12);
    String s, s2 = new String();
    while((s = in.readLine())!= null)
    s2 += s + "\n";
    I even tried the below code but still java.lang.OutOfMemory is coming:
    while (true)
    int i = in.read();
    if (i == -1)
    break;
    sb.append(i);
    Please let me know what am I doing wrong here ...

    Hi,
    I could avoid the java.lang.OutOfMemory error using below code. But using below code I could read small files of sizes less than 4MB
    but with large files of 12 MB the below code just simply hangs and I am unable to print the string object namely 's'.
    My purpose is to construct an String or StringBuffer object out the user uploaded xml file at the client side and pass that object to server for processing. So how can I construct such object avoid memory problem and increasing the performance of such operations.
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
    byte[] b = new byte[in.available()];
    in.read(b, 0, b.length);
    String s = new String(b, 0, b.length);
    in.close();
    Thanks & Regards,
    Sony.

  • Unable to Read XML files into PI 7.0

    Dear Friends,
    I am working on File to IDOC and IDoc to File scenario with a shared folder concept.
    we have tested all our transactions to and fro with out any problem. Two days back we faced sudden server shut down due to power issue.
    From that day we are facing problem in reading files into XI
    We are not facing any problem during outbound transactions from SAP  on the same business system, where inbound folder path is also mentioned.
    I have checked in Monitoring under communication channel..
    it is showing comm channal is correctly configured...
    is there any way i can check where it is going wrong..
    Any thoughts and suggestions is highly rewarded.
    Thanks & Regards,
    Suman

    Hi Santhosh,
    We have given full folder permissions for all users. Processed read file option  is not enabled in my Sender CC.
    Thanks for quick response.
    Regards,
    Suman

  • Reading XML file into Dynamic Node and Display its output as Table.

    Hi All,
    Following is the output of XML file:
       <Company>
         <Employee>
              <Name>John</Name>
              <Age>23</Age>
              <***>Male</***>
              <Location>Frankfurt</Location>
         </Employee>
         <Employee>
              <Name>Tina</Name>
              <Age>21</Age>
              <***>Female</***>
              <Location>Boston</Location>
         </Employee>
         <Department>
              <Name>Sales</Name>
              <HQ>Chicago</HQ>
              <Emplyoees>2300</Employees>
         </Department>     
    I'm able to read the output through DOM parser. But How do I convert this into dynamic node and display this in Web dynpro as Table?
    Any pointers in this regard will be great help?
    Thanks
    Srikant

    Hi Maksim,
    I've used your example and its now helping as there is kind of agreement on that I'll be knowing the structure of Xml and I can fill the nodes.
    But suppose if you have Xml has following structure :
    <?xml version="1.0" encoding="utf-8"?><DATA>
    <item><MAILERID TYPE="C" SIZE="000030">21</MAILERID><ORG_CODE TYPE="C" SIZE="000004">1232</ORG_CODE><EVENTID TYPE="C" SIZE="000015">CONTRACT</EVENTID><SUBSCR_VALUE TYPE="C" SIZE="000001">0</SUBSCR_VALUE></item>
    <item><MAILERID TYPE="C" SIZE="000030">21</MAILERID><ORG_CODE TYPE="C" SIZE="000004">1232</ORG_CODE><EVENTID TYPE="C" SIZE="000015">CREDIT</EVENTID><SUBSCR_VALUE TYPE="C" SIZE="000001">0</SUBSCR_VALUE></item>
    <item><MAILERID TYPE="C" SIZE="000030">21</MAILERID><ORG_CODE TYPE="C" SIZE="000004">1232</ORG_CODE><EVENTID TYPE="C" SIZE="000015">EMPRESS</EVENTID><SUBSCR_VALUE TYPE="C" SIZE="000001">0</SUBSCR_VALUE></item>
    <item><MAILERID TYPE="C" SIZE="000030">21</MAILERID><ORG_CODE TYPE="C" SIZE="000004">1232</ORG_CODE><EVENTID TYPE="C" SIZE="000015">PAYMENT</EVENTID><SUBSCR_VALUE TYPE="C" SIZE="000001">0</SUBSCR_VALUE></item>
    <item><MAILERID TYPE="C" SIZE="000030">21</MAILERID><ORG_CODE TYPE="C" SIZE="000004">1232</ORG_CODE><EVENTID TYPE="C" SIZE="000015">PRICE</EVENTID><SUBSCR_VALUE TYPE="C" SIZE="000001">0</SUBSCR_VALUE></item>
    </DATA>
    How we will do in this case?
    Can we have something similar using DOM? Also what is the best method for displaying data being sent in form of XML. And generalize it for cases like this.
    Thanks
    Srikant

  • Failed to create Salience object and java.lang.NoClassDefFoundError

    We are getting the below error while trying to use the text enrichment component in Endeca integrator clover server.
    2015-01-26 10:11:59,880 INFO 1343495 [pool-7-thread-1] Creating new Salience object from data paths: '/app/oracle/ofm/TextEnrichment/salience-5.1.1.7349/data'.
    2015-01-26 10:11:59,881 ERROR 1343495 [pool-7-thread-1] Failed to get Salience object from factory
    java.lang.NoClassDefFoundError: com/lexalytics/salience/Salience
      at com.endeca.clover.adapters.salience.SalienceFactory.createSalience(SalienceFactory.java:101)
      at com.endeca.clover.adapters.salience.SalienceFactory.getSalienceInstance(SalienceFactory.java:41)
      at com.endeca.clover.adapters.salience.SalienceRunnable.run(SalienceRunnable.java:92)
      at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
      at java.lang.Thread.run(Thread.java:680)
    2015-01-26 10:11:59,891 ERROR 1343495 [WatchDog_1343495] Component [Customer Background:CUSTOMER_BACKGROUND] finished with status ERROR.
    Failed to create Salience object.
    2015-01-26 10:11:59,891 ERROR 1343495 [WatchDog_1343495] Error details:
    org.jetel.exception.JetelRuntimeException: Component [Customer Background:CUSTOMER_BACKGROUND] finished with status ERROR.
      at org.jetel.graph.Node.createNodeException(Node.java:535)
      at org.jetel.graph.Node.run(Node.java:514)
      at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
      at java.lang.Thread.run(Thread.java:680)
    Caused by: java.lang.RuntimeException: Failed to create Salience object.
      at com.endeca.clover.adapters.salience.SalienceComponent.execute(SalienceComponent.java:166)
      at org.jetel.graph.Node.run(Node.java:485)
      at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:919)
      ... 1 more
    2015-01-26 10:11:59,930 INFO 1343495 [WatchDog_1343495] Execution of phase [0] finished with error - elapsed time(sec): 0
    2015-01-26 10:11:59,930 ERROR 1343495 [WatchDog_1343495] !!! Phase finished with error - stopping graph run !!!
    2015-01-26 10:11:59,930 INFO 1343495 [WatchDog_1343495] Post-execute finalization of connection:
    2015-01-26 10:11:59,930 INFO 1343495 [WatchDog_1343495] DBConnection driver[org.jetel.connection.jdbc.driver.JdbcDriverImpl@103cdbdc]:jndi[null]:url[jdbc:oracle:thin:@gitvm000212.us.oracle.com:1521:upslstg]:user[upsell_winref] ... OK
    2015-01-26 10:11:59,930 INFO 1343495 [WatchDog_1343495] -----------------------** Summary of Phases execution **---------------------
    2015-01-26 10:11:59,931 INFO 1343495 [WatchDog_1343495] Phase# Finished Status RunTime(sec) MemoryAllocation(KB)
    2015-01-26 10:11:59,930 INFO 1343495 [JobFinalizer_1343495] Finalisation
    2015-01-26 10:11:59,931 INFO 1343495 [WatchDog_1343495] 0 ERROR 0 139976
    2015-01-26 10:11:59,931 INFO 1343495 [WatchDog_1343495] ------------------------------** End of Summary **---------------------------
    2015-01-26 10:11:59,931 INFO 1343495 [WatchDog_1343495] WatchDog thread finished - total execution time: 0 (sec)
    2015-01-26 10:11:59,935 INFO 1343495 [JobFinalizer_1343495] RunTime: 296 ms
    2015-01-26 10:11:59,935 ERROR 1343495 [JobFinalizer_1343495]
    --------------------------------- Error details ----------------------------------
      Component [Customer Background:CUSTOMER_BACKGROUND] finished with status ERROR.
      Failed to create Salience object.
    2015-01-26 10:11:59,935 INFO 1343495 [JobFinalizer_1343495] Finished Status: ERROR
    This happens only on our stage and production instances. On our dev instance it works without problems. All 3 instances are setup the same, although our dev instance was created long time before the stage and prod instances. However, we cannot detect any differences between the machines.
    I've tried the solutions mentioned in the other similar thread: Failed to create Salience object but this doesnt solve the issue since the directory and variables were already correct.
    Anyone can help?

    Given that you are running this in Clover Server, one thing I can recommend is to shut that server down, move/truncate the logs, restart and retest, then look at the first error message you get when attempting to run the graph.  Java classloaders sometimes cache failed class clinit and report future attempts to load that class as a simple NoClassDefFoundError, masking the original/actual root cause.  With any luck you might find another, clearer error - maybe the native binary libraries are not being located.

  • OutOfMemoryError while attempting to read 60MB file into HashMap objects

    Hi,
    I've a 60MB file with about 60000 records that I'm trying to read into a HashMap of <String, String[]>. However, as far as I can see it can only manage reading in 12000 before it falls over with an OutOfMemoryError.
    My eclipse.ini contains the following entries:
    -Xms40m
    -Xmx512m
    I've changed Xmx512m to Xmx1024m but this hasn't made a difference.
    My program involves reading in the file, sorting it based on 2 attributes of a record and then outputting it in the sorted order.
    I've tried a few other methods around just reading in the attributes that I need, doing the sort with those, looking for the rows I need from the input file sequentially and then outputting this in the correct order but this seems to be taking forever, well over 12 hours!
    How else can I go about this? Thanks.

    Here is the code. Sorry, how do I go about compiling this class as it's looking for the CsvReader jar but can't find. Have tried the -cp option but doesn't seems to work. Thanks.
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.HashMap;
    import com.csvreader.CsvReader;
    public class Reader {
          * @param args
          * @throws IOException
         public static void main(String[] args) throws IOException {
              CsvReader reader = new CsvReader(new FileReader("C:\\temp\\gen_ppl.csv"), '|');
              HashMap<String, String[]> allCorpIDs = new HashMap<String, String[]>();
              while(reader.readRecord())
                   allCorpIDs.put(reader.get(0), reader.getValues());
    }

  • Question about reading a very big file into a buffer.

    Hi, everyone!
    I want to randomly load several characters from
    GB2312 charset to form a string.
    I have two questions:
    1. Where can I find the charset table file? I have used
    google for hours to search but failed to find GB2312 charset
    file out.
    2. I think the charset table file is very big and I doubted
    whether I can loaded it into a String or StringBuffer? Anyone
    have some solutions? How to load a very big file and randomly
    select several characters from it?
    Have I made myself understood?
    Thanks in advance,
    George

    The following can give the correspondence between GB2312 encoded byte arrays and characters (in hexadecimal integer expression).
    import java.nio.charset.*;
    import java.io.*;
    public class GBs{
    static String convert() throws java.io.UnsupportedEncodingException{
    StringBuffer buffer = new StringBuffer();
    String l_separator = System.getProperty("line.separator");
    Charset chset = Charset.forName("EUC_CN");// GB2312 is an alias of this encoding
    CharsetEncoder encoder = chset.newEncoder();
    int[] indices = new int[Character.MAX_VALUE+1];
    for(int j=0;j<indices.length;j++){
           indices[j]=0;
    for(int j=0;j<=Character.MAX_VALUE;j++){
        if(encoder.canEncode((char)j)) indices[j]=1;
    byte[] encoded;
    String data;
    for(int j=0;j<indices.length;j++) {
         if(indices[j]==1) {
                encoded =(Character.toString((char)j)).getBytes("EUC_CN");
                          for(int q=0;q<encoded.length;q++){
                          buffer.append(Byte.toString(encoded[q]));
                          buffer.append(" ");
                buffer.append(": 0x");buffer.append(Integer.toHexString(j));
                buffer.append(l_separator);
        return buffer.toString();
    //the following is for testing
    /*public static void main(String[] args) throws java.lang.Exception{
       String str = GBs.convert();
       System.out.println(str);*/

  • Convert a line read from text file into string

    how to convert a line from text file into string?
    i know how to convert to numbers,
    private int  parseLine1(String line) {
              StringTokenizer tokenizer = new StringTokenizer(line);
                  value1 = Integer.valueOf(tokenizer.nextToken()).intValue();
                  value2 = Integer.valueOf(tokenizer.nextToken()).intValue();
                 return value1;
                     }but what about charactrs?

    ok, here is my problem, i have a file with a bunch of Xs in it but position function doesn't return a correct value, what's going wrong?
    private int positioni(){
           int i=0;
           int j=0;
           int b=0;
           String line="";
            while(line!= null){
                for(int a=0; a<line.length(); a++){
                    if(line.charAt(a)=='X'){
                        i=a;}
                b++;
                j=b;
                t=line.length();
                line=read(gridFileN);
           return i;
    private String read(String ggridFileN){
             TextStreamReader ggridFile = new TextStreamReader(ggridFileN);
             return ggridFile.readLine();

  • Reading in text file into strings

    Hi,
    I'm new to the reading in data part of java and I can't work out a good way to read in a .txt file and then store each line of the txt file into strings.
    I think I'm probably just missing something obvious but if anyone can help :D!
    Thanks,
    Bex

    Look up Scanner in Java 1.5, or BufferedReader in Java 1.4.

  • Set encoding to read a file into a string

    in my Coding i Want to read a file into a string like this
    File myFile = new File (Dateipfad);
            System.out.println("folgende Datei wird nun verarbeitet: " + Dateipfad);
             java.io.BufferedReader myBis = new java.io.BufferedReader(new java.io.FileReader(myFile.getAbsolutePath()));
      myBis.StringBuffer buf = new StringBuffer();
             String line = myBis.readLine();
             while (line != null)
                    buf.append(line);
                    line = myBis.readLine();
      myBis.close();
    ] now i just want to set an encoding "ISO-8859-1", so that all �`s, �`s or �`s dont get lost.
    Can Anyone help me please ?!

    You must use java.io.InputStreamReader to set the required encoding.
    See the API for more details.
    http://java.sun.com/j2se/1.3/docs/api/java/io/InputStreamReader.html
    HTH,
    Manuel Amago.

  • Help reading .csv file into an arraylist

    i need to read a csv file into an arraylist and then print the arraylist to the screen.
    using:
    try {
                // Setup our scanner to read the file at the path c:\test.txt
                Scanner myscanner = new Scanner(new File("\\carsDB.csv"));    
    ArrayList<CarsClass> carsClass = new ArrayList<CarsClass>(" write all fields");   
                while (myscanner.hasNextLine()) {
    myscanner.add(" add car fields to the carClass");              // Write your code here.
    // loop to read them all to the screencsv file is like this:
    Manufacturer,carline name,displ,cyl,fuel,(miles),Class
    CHEVROLET,CAVALIER (natural gas),2.2,4,CNG,120,SUBCOMPACT CARS
    HONDA,CIVIC GX (natural gas),1.6,4,CNG,190,SUBCOMPACT CARS
    FORD,CONTOUR (natural gas),2,4,CNG,70,COMPACT
    FORD,CROWN VICTORIA (natural gas),4.6,8,CNG,140/210*,LARGE CARS
    FORD,F150 PICKUP (natural gas) - 2WD,5.4,8,CNG,130,STANDARD PICKUP TRUCKS 2WD
    FORD,F250 PICKUP (natural gas) - 2WD,5.4,8,CNG,160,STANDARD PICKUP TRUCKS 2WD
    FORD,F250 PICKUP (natural gas) - 2WD,5.4,8,CNG,150/210*,STANDARD PICKUP TRUCKS 2WD
    FORD,F150 PICKUP (natural gas) - 4WD,5.4,8,CNG,130,STANDARD PICKUP TRUCKS 4WD
    FORD,F250 PICKUP (natural gas) - 4WD,5.4,8,CNG,160,STANDARD PICKUP TRUCKS 4WD
    FORD,E250 ECONOLINE (natural gas) - 2WD,5.4,8,CNG,170,"VANS, CARGO TYPE"
    FORD,E250 ECONOLINE (natural gas) - 2WD,5.4,8,CNG,80,"VANS, CARGO TYPE"
    FORD,F150 LPG - 2WD,5.4,8,LPG,290/370*,STANDARD PICKUP TRUCKS 2WD
    FORD,F250 LPG - 2WD,5.4,8,LPG,260/290/370**,STANDARD PICKUP TRUCKS 2WD
    ok, so do i need to write a file carsclass.java or is the line:
    ArrayList<CarsClass> carsClass = new ArrayList<CarsClass>(" write all fields");
    going to define my carsclass objects? how do i write my fields for each of the 7 categories?
    i believe i can easily add to and print the arraylist, but i'm confused how to go about creating this arraylist in the first place. do i just create carclass.java and save them all as strings? i guess my question is mainly how should i structure this? any suggestions/help is appreciated.
    Edited by: scottc on Nov 15, 2007 5:55 PM

    String.split uses regular expressions.Ahh yeah ummm (slaps forehead) I'd forgotten that... so maybe StringTokeniser is more accessible for noob's. Sorry.
    Anyway... if all you want/need to so is store a bunch of String field values then how about using an array of String's instead of individual fields... maybe something like:
    forums\Car.java
    * Car Data Transfer Object. All fields are final, making objects of this class
    * thread safe(r).
    * @author keith
    package forums;
    import krc.utilz.stringz.Arrayz;
    public class Car
      // class attributes                       // variables //isn't actually wrong, it's just not quit right.
      private final String[] fields;            // final means values are write once, read many times, which is thread safe(r).
       * Initialises the new Cars fields to the given fields array.
       * @param fields - an array of any (reasonable) length
      public Car(String[] fields) {             // no need to comment a constructor as a constructor.
        this.fields = fields;                   // much better to provide javadoc comments explaining
      }                                         // what the method does and how to use it.
       * Returns this Car's fields as one long string.
      public String toString() {                // It's actually GOOD to be a lazy programmer.
        return Arrayz.join(", ", this.fields);  // I have reused my Arrayz.join in several projects.
                                                // I think you can use Array.toString (new in 1.6) instead.
    krc\utilz\stringz\Arrayz.java
    package krc.utilz.stringz;
    import java.util.List;
    import java.util.ArrayList;
    public class Arrayz
        * returns true if the given value is in the args list, else false.
        * @param value - the value to seek
        * @param args... - variable number of String arguments to look in
      public static boolean in(String value, String... args) {
        for(String a : args) if(value.equals(a)) return true;
        return false;
        * append the elements of array into one string, seperated by FS
        * @param a  - an array of strings to join together
        * @param FS - Field Seperator string, optional default=" "
        * @example
        *  String[] array = {"Bob","The","Builder"};
        *  System.out.println(join(array);
        *  --> Bob The Builder
        *  System.out.println("String[] array = {\""+join(array, "\",\"")+"\"};");
        *  --> String[] array = {"Bob","The","Builder"};
      public static String join(String FS, String[]... arrays) {
        StringBuffer sb = new StringBuffer();
        for (String[] array : arrays)
          sb.append(join(array, FS));
        return(sb.toString());
      public static String join(String[] array) {
        return(join(array, " "));
      public static String join(String[] a, String FS) {
        if (a==null) return null;
        if (a.length==0) return "";
        StringBuffer sb = new StringBuffer(a[0]);
        for (int i=1; i<a.length; i++) {
          sb.append(FS+a);
    return sb.toString();
    * append all the elements of the given arrays into one big array
    * @param String[]... arrays - to be concatenated
    * @return String[] - one big array
    public static String[] concatenate(String[]... arrays) {
    List<String> list = new ArrayList<String>();
    for(String[] array : arrays) {
    for(String item : array) {
    list.add(item);
    return(list.toArray(new String[0]));
    I guess that Arrayz class might be a bit beyond you at the moment so don't worry too much if you can't understand the code... there are no nasty surprises in it... just cut and paste the code, change the package name, and use it (for now).

  • Reading from file into an array

    Hello, new to Java and we need to modify a mortgage calculator to read interest rate from a file into an array and not have them hard coded in the program. I have read many post on how to perform this but am lost on where to put the new code and format. Here is my code and I hope I posted this right.
    import javax.swing.*;                                              // Imports the Main Swing Package                                   
    import javax.swing.event.*;
    import javax.swing.text.*;                                          // Used for  Text Box Caret Position
    import java.awt.*;                                                // Imports the main AWT Package
    import java.awt.event.*;                                         // Event handling class are defined here
    import java.text.NumberFormat;
    import java.text.*;                                              // Imports the Main Text Package
    import java.util.*;                                              // Imports the Main Utility Package
    public class mortgageCalculator1 extends JFrame implements ActionListener             // Creates class mortgageCalculator
        JLabel AmountLabel = new JLabel("   Enter Mortgage Amount:$ ");                   // Declares Mortgage Amount Label
        JTextField mortgageAmount = new JTextField(10);                                     // Declares Mortgage Amount Text Field
        JButton IntandTerm1B = new JButton("7 years at 5.35%");                    // Declares 1st Mortgage Term and Interest Rate
        JButton IntandTerm2B = new JButton("15 years at 5.50%");                    // Declares 2nd Mortgage Term and Interest Rate
        JButton IntandTerm3B = new JButton("30 years at 5.75%");                    // Declares 3rd Mortgage Term and Interest Rate
        JLabel PaymentLabel = new JLabel("   Monthly Payment: ");                     // Declares Monthly Payment Label
        JTextField monthlyPayment = new JTextField(10);                          // Declares Monthly Payment Text Field
        JButton exitButton = new JButton("Exit");                              // Declares Exit Button
        JButton newcalcButton = new JButton("New Calculation");                     // Declares New Calculation Button
        JTextArea mortgageTable = new JTextArea(35,65);                         // Declares Mortgage Table Area
        JScrollPane scroll = new JScrollPane(mortgageTable);                         // Declares ScrollPane and puts the Mortgage Table inside
        public mortgageCalculator1()                                        // Creates Method
             super("MORTGAGE CALCULATOR");                              // Title of Frame
             JMenuBar mb = new JMenuBar();                                   // Cretes Menu Bar
                JMenu fileMenu = new JMenu("File");                                 // Creates File Menu
             fileMenu.setMnemonic('F');                                      // Enables alt + f to Access File Menu
             JMenuItem exitItem = new JMenuItem("Exit");                     // Creates Exit in File Menu
             fileMenu.add(exitItem);                                   // Adds Exit to File Menu
                 exitItem.addActionListener(new ActionListener()                     // Adds Action Listener to the Exit Item
                     public void actionPerformed(ActionEvent e)                     // Tests to Verify if File->Exit is Pressed
                         System.exit(0);                                // Exits the Programs when File->Exit is Pressed
                mb.add(fileMenu);                                      // Adds the File Menu
                setJMenuBar(mb);                              
         setSize(600, 400);                                        // Sets Size of Frame
            setLocation(200,200);                                         // Sets the Location of the Window  
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);                                  // Command on how to close frame
         JPanel pane = new JPanel();                                   // Declares the JPanel
         pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));                          // Sets Panel Layout to BoxLayout
         Container grid = getContentPane();                               // Declares a Container called grid
         grid.setLayout(new GridLayout(4,3,5,5));                          // Sets grid Layout to GridLayout
         pane.add(grid);                                             // Adds the grid to the Panel
         pane.add(scroll);                                        // Addes the scrollPane to the Panel
            grid.setBackground(Color.yellow);                              // Set grid color to Yellow
         setCursor(new Cursor(Cursor.HAND_CURSOR));                         // Makes the cursor look like a hand
         mortgageAmount.setBackground(Color.black);                         // Sets mortgageAmount JPanel JTextField Background Color
            mortgageAmount.setForeground(Color.white);                         // Sets mortgageAmount JPanel JTextField Foreground Color
         mortgageAmount.setCaretColor(Color.white);                         // Sets mortgageAmount JPanel JTextField Caret Color
         mortgageAmount.setFont(new Font("Lucida Sans Typewriter", Font.PLAIN, 18));     // Sets mortgageAmount JPanel JTextField Font
         monthlyPayment.setBackground(Color.black);                         // Sets monthlyPayment JPanel JTextField Background Color
         monthlyPayment.setForeground(Color.white);                         // Sets monthlyPayment JPanel JTextField Foreground Color
            monthlyPayment.setFont(new Font("Lucida Sans Typewriter", Font.PLAIN, 18));     // Sets monthlyPayment JPanel JTextField Font
         mortgageTable.setBackground(Color.yellow);                         // Sets mortgageTable JTextArea Background Color
         mortgageTable.setForeground(Color.black);                         // Sets mortgageTable JTextArea Foreground Color
         mortgageTable.setFont(new Font("Arial", Font.PLAIN, 18));               // Sets JTextArea Font
         grid.add(AmountLabel);                                        // Adds the Mortgage Amount Label
         grid.add(mortgageAmount);                                   // Adds the Mortgage Amount Text Field
         grid.add(IntandTerm1B);                                        // Adds 1st Loan and Rate Button
         grid.add(PaymentLabel);                                    // Adds the Payment Label
         grid.add(monthlyPayment);                                    // Adds the Monthly Payment Text Field
           monthlyPayment.setEditable(false);                              // Disables editing in this Text Field
            grid.add(IntandTerm2B);                                        // Adds 2nd Loan and Rate Button
            grid.add(exitButton);
         grid.add(newcalcButton);                                    // Adds the New Calc Button
            grid.add(IntandTerm3B);                                        // Adds the Exit Button
         setContentPane(pane);                                          // Enables the Content Pane
         setVisible(true);                                          // Sets JPanel to be Visable
         exitButton.addActionListener(this);                                // Adds Action Listener to the Exit Button
         newcalcButton.addActionListener(this);                            // Adds Action Listener to the New Calc Button
            IntandTerm1B.addActionListener(this);                              // Adds Action Listener to the 1st loan Button
         IntandTerm2B.addActionListener(this);                              // Adds Action Listener to the 2nd loan Button
         IntandTerm3B.addActionListener(this);                               // Adds Action Listener to the 3rd loan Button
         mortgageAmount.addActionListener(this);                              // Adds Action Listener to the Mortgage  Amount Text Field
         monthlyPayment.addActionListener(this);                              // Adds Action Listener to the Monthly payment Text Field
        public void actionPerformed(ActionEvent e)                               // Tests to Verify Which Button is Pressed
            Object command = e.getSource();                                                 // Enables command to get data
            if (command == exitButton) //sets exitButton                         // Activates the Exit Button
                System.exit(0);  // Exits from exit button                         // Exits from exit button
            int loanTerm = 0;                                             // Declares loanTerm
            if (command == IntandTerm1B)                                   // Activates the 1st Loan Button
                loanTerm = 0;                                        // Sets 1st value of Array
            if (command == IntandTerm2B)                                   // Activates the 2nd Loan Button
                loanTerm = 1;                                        // Sets 2nd value of Array
            if (command == IntandTerm3B)                                   // Activates the 3rd Loan Button
             loanTerm = 2;                                        // Sets 3rd value of Array
                double mortgage = 0;                                   // Declares and Initializes mortgage
             double rate = 0;                                        // Declares and Initializes rate                                        
             double [][] loans = {{7, 5.35}, {15, 5.50}, {30, 5.75},};                 // Array Data for Calculation
                    try
                        mortgage = Double.parseDouble(mortgageAmount.getText());            // Gets user input from mortgageAmount Text Field
                      catch (NumberFormatException nfe)                          // Checks for correct number fformatting of user input
                       JOptionPane.showMessageDialog (this, "Error! Invalid input!");      // Outputs error if number is wrong format or nothing is entered
                       return;
             double interestRate = loans [loanTerm][1];                         // Sets interestRate amount
             double intRate = (interestRate / 100) / 12;                         // Calculates Interst Rate     
                double loanTermMonths = loans [loanTerm] [0];                    // Calculates Loan Term in Months
                int months = (int)loanTermMonths * 12;                          // Converts Loan Term to Months
                double interestRateMonthly = (intRate / 12);                                // monthly interst rate
             double payment = mortgage * intRate / (1 - (Math.pow(1/(1 + intRate), months)));    // Calculation for Monthly payment
                double remainingLoanBalance = mortgage;                              // Sets Reamaining Balance
                double monthlyPaymentInterest = 0;                                       // holds current interest payment
                double monthlyPaymentPrincipal = 0;                                    // holds current principal payment
                NumberFormat myCurrencyFormatter = NumberFormat.getCurrencyInstance(Locale.US);     // Number formatter to format output in table
                monthlyPayment.setText(myCurrencyFormatter.format(payment));
                mortgageTable.setText("Month\tPrincipal\tInterest\tEnding Balance\n" +                // Formats morgageTable Header
                                      "---------\t----------\t------------\t---------------------\n");
                    for (;months > 0 ; months -- )
                     monthlyPaymentInterest = (remainingLoanBalance * intRate);               // Calculation for Monthly Payment Toward Interest
                     //Calculate H = R x I
                     monthlyPaymentPrincipal = (payment - monthlyPaymentInterest);          // Calculation for Monthly Payment Toward Principal
                     //Calculate C = P - H
                  remainingLoanBalance = (remainingLoanBalance - monthlyPaymentPrincipal);     // Calculation for Reamining loan Balance
                  // Calculate R = R - C
                  // H = monthlyPaymentInterest
                  // R = remainingLoanBalance
                  // P = payment
                  // C = monthlyPaymentPrincipal
                  // I = interestRateMonthly
                  mortgageTable.setCaret (new DefaultCaret());                    // Sets Scroll position to the top left corner
                  mortgageTable.append(String.valueOf(months) + "\t" +               // Pulls in data and formats MortgageTable
                  myCurrencyFormatter.format(monthlyPaymentPrincipal) + "\t" +
                     myCurrencyFormatter.format(monthlyPaymentInterest) + "\t" +
                     myCurrencyFormatter.format(remainingLoanBalance) + "\n");
                           if(command == newcalcButton)                               // Activates the new calculation Button
                         mortgageAmount.setText(null);                         //clears mortgage amount fields
                      monthlyPayment.setText(null);                         //clears monthly payment fields
                            mortgageTable.setText(null);                              //clears mortgage table
    public static void main(String[] args)                               //This is the signature of the entry point of all the desktop apps
         new mortgageCalculator1();
    }

    OK, making a little progress but am still very confused.
    What I have is a file (int&term.dat) with three lines;
    5.75, 30
    5.5, 15
    5.35 ,7
    I have three JButtom that I what to read a seperate line and place the term in a term TextField and a rate in a Rate TextField
    I have added the following code and all it does now is output a black space to the screen; I am working with one Button and Just the rate for now to try and get it to work. I have been looking at the forums, reading the internet and several books to try and figure this out. I think I may be getting closer.
    public static void read()
        String line;
        StringTokenizer tokenizer;
        String rate;
        String term;
        try
            FileReader fr = new FileReader ("int&term.dat");
            BufferedReader inFile = new BufferedReader (fr);
            line = inFile.readLine();
            while (line != null)
            tokenizer = new StringTokenizer(line);
            rate = tokenizer.nextToken();
            line = inFile.readLine();
             inFile.close();
             System.out.println(new String());
             catch (FileNotFoundException exception)
                   System.out.println ("The file was not found.");
              catch (IOException exception)
                    System.out.println (exception);
    }

  • How to read a binaryfile into an object

    Hello,
    I want to read a binary file into an object. In this object, we have
    several variables which need to be filled. I did the following thing:
    ---Start code---
    import java.io.*;
    import java.lang.reflect.*;
    public class BinaryFile {
      private File file;
      private DataInputStream dis;
      public BinaryFile() {}
      // Open the file
    public void openFile(String file) throws FileNotFoundException {
        this.file = new File(file);
        if (! this.file.exists())
          throw new FileNotFoundException();
        dis = new DataInputStream(new FileInputStream(this.file));
      // Close the file
      public void closeFile() throws IOException {
        dis.close();
    public void readObject(int offset, Object o) throws EndOfFileException,
                           IOException {
        // Get the fields in the object
        Field[] fields = o.getClass().getFields();
        try {
          String type, naam;
          Class className;
          int lengte, arrayLengte;
          boolean isArray;
          for (int i = 0; i !< fields.length; i++) {
            naam = fields.getName(); // Get the name of the field
    className = fields[i].getType(); // Get the type
    type = className.getName(); // Get the name of the type
    isArray = className.isArray(); // Is it an array?
    arrayLengte = 1;
    fields[i].setAccessible(true); // For setting the values
    if (isArray) {                      // If it is an array,
    type = getType(type); // decode it
    // Get the size of the array
    arrayLengte = Array.getLength(fields[i].get(o));
    // Determine the type of the variable and fill it.
    // Char
    if (type.equalsIgnoreCase("char")) {
    lengte = 1;
    if (isArray)
    fields[i].set(o, readChars(arrayLengte * lengte));
    else
    fields[i].setChar(o, readChar());
    // Byte
    } else if (type.equalsIgnoreCase("byte")) {
    lengte = 1;
    if (isArray)
    fields[i].set(o, readBytes(arrayLengte * lengte));
    else
    fields[i].setByte(o, readByte());
    // Short
    } else if (type.equalsIgnoreCase("short")) {
    lengte = 2;
    if (isArray)
    fields[i].set(o, readShorts(arrayLengte * lengte));
    else
    fields[i].setShort(o, readShort());
    // Int
    } else if (type.equalsIgnoreCase("int")) {
    lengte = 4;
    if (isArray)
    fields[i].set(o, readInts(arrayLengte * lengte));
    else
    fields[i].setInt(o, readInt());
    // Float
    } else if (type.equalsIgnoreCase("float")) {
    lengte = 4;
    if (isArray)
    fields[i].set(o, readFloats(arrayLengte * lengte));
    else
    fields[i].setFloat(o, readFloat());
    // Long
    } else if (type.equalsIgnoreCase("long")) {
    lengte = 8;
    if (isArray)
    fields[i].set(o, readLongs(arrayLengte * lengte));
    else
    fields[i].setLong(o, readLong());
    // Double
    } else if (type.equalsIgnoreCase("double")) {
    lengte = 8;
    if (isArray)
    fields[i].set(o, readDoubles(arrayLengte * lengte));
    else
    fields[i].setDouble(o, readDouble());
    catch (IOException ioex) {
    throw ioex;
    catch (Exception ex) {
    ex.printStackTrace();
    // Methods for reading from the DataInputStream
    private char[] readChars(int lengte) throws IOException {
    char[] c = new char[lengte];
    for (int i = 0; i < c.length; i++)
    c[i] = dis.readChar();
    return c;
    private char readChar() throws IOException {
    return dis.readChar();
    private byte[] readBytes(int lengte) throws IOException {
    byte[] b = new byte[lengte];
    for (int i = 0; i < b.length; i++)
    b[i] = dis.readByte();
    return b;
    private byte readByte() throws IOException {
    return dis.readByte();
    private short[] readShorts(int lengte) throws IOException {
    short[] s = new short[lengte];
    for (int i = 0; i < s.length; i++)
    s[i] = dis.readShort();
    return s;
    private short readShort() throws IOException {
    return dis.readShort();
    private int[] readInts(int lengte) throws IOException {
    int[] i = new int[lengte];
    for (int j = 0; j < i.length; j++)
    i[j] = dis.readInt();
    return i;
    private int readInt() throws IOException {
    return dis.readInt();
    private double[] readDoubles(int lengte) throws IOException {
    double[] d = new double[lengte];
    for (int i = 0; i < d.length; i++)
    d[i] = dis.readDouble();
    return d;
    private double readDouble() throws IOException {
    return dis.readDouble();
    private float[] readFloats(int lengte) throws IOException {
    float[] f = new float[lengte];
    for (int i = 0; i < f.length; i++)
    f[i] = dis.readFloat();
    return f;
    private float readFloat() throws IOException {
    return dis.readFloat();
    private long[] readLongs(int lengte) throws IOException {
    long[] l = new long[lengte];
    for (int i = 0; i < l.length; i++)
    l[i] = dis.readLong();
    return l;
    private long readLong() throws IOException {
    return dis.readLong();
    // If it is an array, decode it. The type will be "[x" where x is
      // translated according to the table
      private String getType(String type) {
              BaseType Character  Type  Interpretation
              B  byte  signed byte
              C  char  Unicode character
              D  double  double-precision floating-point value
              F  float  single-precision floating-point value
              I  int  integer
              J  long  long integer
              L<classname>;  reference  an instance of class <classname>
              S  short  signed short
              Z  boolean  true or false
              [  reference  one array dimension
        int arrayIndex = type.indexOf("[");
        if (arrayIndex != type.lastIndexOf("[")) {
          System.out.println("Multiple arrays not supported!");
          return type;
    char tempType = type.charAt(arrayIndex + 1);
    switch (tempType) {
    case 'B':
    type = "byte";
    break;
    case 'C':
    type = "char";
    break;
    case 'D':
    type = "double";
    break;
    case 'F':
    type = "float";
    break;
    case 'I':
    type = "int";
    break;
    case 'J':
    type = "long";
    break;
    case 'S':
    type = "short";
    break;
    default:
    System.out.println("Couldn't define this type: " + type);
    type = type;
    break;
    return type;
    ---End code---
    Now the problem. I want to read the header of an executable. I turn to
    the file format as described in WINNT.H. If it is a char, it will read
    ok. For everything else, it doesn't work. A WORD (= short in java) for
    instance, doesn't come up with the real value.
    The purpose of this piece of code is to emulate the structs that are
    used in C.
    What is the problem here and what is the solution?

    before coding a long class, look at Serialization mechanism in java
    maybe (or maybe not) it should be a better soution ...

  • XML file into String

    Hello,
        I want to convert total xml file into string in UDF, i am getting an error. can anybody tell me the solution. what is the wrong in bellow code.
    String str =a+b;
    String strLine;
    StringBuffer sbr=new StringBuffer();
    try{
         FileInputStream fileInputStream = new FileInputStream(str);
             DataInputStream dataInputStream = new DataInputStream(fileInputStream);
             BufferedReader bufferedReader = new BufferedReader(new   InputStreamReader(dataInputStream));
             while ((strLine = bufferedReader.readLine()) != null)   {
             sbr.append(strLine);
         catch (Exception e){      e.printStackTrace();       }
    return sbr.toString();}

    check this link
    How to store big XML string  in ABAB DB
    regards,
    srinivas
    <b>*reward for useful answers*</b>

  • Reading .txt file into char array, file not found error. (Basic IO)

    Iv been having some trouble with reading characters from a text file into a char array. I havnt been learning io for very long but i think im getting the hang of it. Reading and writing raw bytes
    and things like that. But i wanted to try using java.io.FileReader to read characters for a change and im having problems with file not found errors. here is the code.
    try
    File theFile = new File("Mr.DocumentReadMe.txt");
    String path = theFile.getCanonicalPath();
    FileReader readMe = new FileReader(path);
    char buffer[] = new char[(int)theFile.length()];
    int readData = 0;
    while(readData != -1)
    readData = readMe.read(buffer);
    jEditorPane1.setText(String.valueOf(buffer));
    catch(Exception e)
    JOptionPane.showMessageDialog(null, e,
    "Error!", JOptionPane.ERROR_MESSAGE);
    The error is: java.io.FileNotFoundException: C:\Users\Kaylan\Documents\NetBeansProjects\Mr.Document\dist\Mr.DocumentReadMe.txt (The system cannot find the file specified)
    The text file is saved in the projects dist folder. I have tried saving it elsewhere and get the same error with a different pathname.
    I can use JFileChooser to get a file and read it into a char array with no problem, why doesnt it work when i specify the path manually in the code?

    Well the file clearly isn't there. Maybe it has a .txt.txt extensionthat Windows is kindly hiding from you - check its Properties.
    But:
    String path = theFile.getCanonicalPath();
    FileReader readMe = new FileReader(path);You don't need all that. Just:
    FileReader readMe = new FileReader(theFile);And:
    char buffer[] = new char[(int)theFile.length()];You don't need a buffer the size of the file, this is bad practice. Use 8192 or whatever.
    while(readData != -1)
    readData = readMe.read(buffer);
    }That doesn't make sense. Read the data into the buffer and repeat until you get EOF? and do nothing with the contents of the buffer? The canonical read loop in Java goes like this:
    while ((count = in.read(buffer)) > 0)
      out.write(buffer, 0, count); // or do something else with buffer[0..count-1].
    jEditorPane1.setText(String.valueOf(buffer));Bzzt. That won't give you the content of 'buffer'. Use new String(buffer, 0, count) at least.

Maybe you are looking for