Java OutputStream help

Hello all,
I am relatively new to using Java's Output and Input streams. I know the basics and I know how to use them but what is driving me crazy is I am not entirely sure how it works. For example I know the following code writes a file from an InputStream to an OutputStream:
InputStream in = new FileInputStream(inputFile);
OutputStream out = new FileOutputStream(outputFile);
byte[] buffer = new byte[1024];
int len;
while((len = in.read(buffer))>0) {
    out.write(buffer, 0, len);
}So if some one could be so kind as to explain a little about the following I would really appreciate it. (I don't know much about bytes)
byte[] buffer = new byte[1024];
Now I know this is an array of bytes but what role does this line of code play in writing to an OutputStream and why a size of 1024 and not 4000 or some other number?
out.write(buffer, 0, len);
I know under the java docs it says that len is the amount of bytes to write but isn't it just writing one byte at a time anyway? Lets say len had a value of one all the time, would that simply just write one byte at a time to the Output stream?
out.write(byte[] b, int off, int len);
Now under the java docs it explains that the byte array b is "the data" which I don't understand, is the OutputStream writing 1024 bytes to the byte array and then writing that byte array to the Output file? Why do I need a byte array in the first place?
I know i'm asking a lot of questions but believe me I've tried to figure it out on my own. I've spent the last 4 hours trying to figure out how this code works by reading the java docs and looking it up on google etc but I can't seem to find a good tutorial or explanation for the questions I've asked. So thank you for reading this and thank you in advance for any input, its most appreciated.

int[] sourceData = new int[1024]; // same as inputFile
for(int i = 0; i < 1024; i++)
  sourceData[i] = (int)(Math.random() * 1024);
int[] buffer = new int[1024];
for(int i = 0; i < 1024; i++)
  buffer[i] = sourceData;
int[] destinationData = new int[1024]; // same as outputFile
for(int i = 0; i < 1024; i++)
destinationData[i] = buffer[i];
}If you can understand what this code is doing, then you got it--despite the fact that I'm using int[] instead of byte[].                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

Similar Messages

  • Java Access Helper Jar file problem

    I just downloaded Java Access Helper zip file, and unzipped, and run the following command in UNIX
    % java -jar jaccesshelper.jar -install
    I get the following error message, and the installation stopped.
    Exception in thread "main" java.lang.NumberFormatException: Empty version string
    at java.lang.Package.isCompatibleWith(Package.java:206)
    at jaccesshelper.main.JAccessHelperApp.checkJavaVersion(JAccessHelperApp.java:1156)
    at jaccesshelper.main.JAccessHelperApp.instanceMain(JAccessHelperApp.java:159)
    at JAccessHelper.main(JAccessHelper.java:39)
    If I try to run the jar file, I get the same error message.
    Does anyone know how I can fix this?
    Thanks

    Cross-posted, to waste yours and my time...
    http://forum.java.sun.com/thread.jsp?thread=552805&forum=54&message=2704318

  • Java Access Helper problem

    I just downloaded Java Access Helper zip file, and unzipped, and run the following command in UNIX
    % java -jar jaccesshelper.jar -install
    I get the following error message, and the installation stopped.
    Exception in thread "main" java.lang.NumberFormatException: Empty version string
    at java.lang.Package.isCompatibleWith(Package.java:206)
    at jaccesshelper.main.JAccessHelperApp.checkJavaVersion(JAccessHelperApp.java:1156)
    at jaccesshelper.main.JAccessHelperApp.instanceMain(JAccessHelperApp.java:159)
    at JAccessHelper.main(JAccessHelper.java:39)
    If I try to run the jar file, I get the same error message.
    Does anyone know how I can fix this?
    Thanks

    sorry ab the multiple post, it was urgent for me to
    know the answer.
    I've JDK 1.4.2 and JAccessHelper should work with 1.3
    or later
    Can there be some kind of path problems?No, I doubt it. It's just some internal app failure - looks like it's trying to determine the running Java version, and is not doing a good job at it. But the failure has nothing per se to Java, it's that specific app - what are we supposed to know about that app though?

  • New to java(need help on access specifier)

    hi! i am new to java.plzzzzz help me i have to make a project on access specifier's i know all theroy.but
    i am unable to understand how i can define all specifiers practicly.i mean in a program.
    thanks.plzzzzzzzz help me

    the most common project i can think of is a payroll system..
    you can have real implementation of all the access specifiers
    good luck

  • Pascal to Java Please help me!

    I am truobled in creating a validation method for the user loging in....
    As I am perfect at Pascal can anyone translate the following pascla code to Java Please help me with this.
    PROGRAM USERLOGIN;
    TYPE
      USER_TYPE = RECORD
        USERNAME : STRING[15];
        PASSWORD : STRING[15];
    END;
        USFILE = FILE OF USER_TYPE;
    VAR
       USER: USER_TYPE;
       CKUSER: USER_TYPE;
       RECFILE : USFILE;
       I,J     : INTEGER;
    BEGIN
    WRITE('ENTER USERNAME:');READLN(CKUSER.USERNAME);
    WRITE('ENTER PASSWORD:');READLN(CKUSER.PASSWORD);
    FILESPEC :='USERFILE.USR';
    ASSIGN(RECFILE, FILESPEC);
    RESET(RECFILE);
      WHILE NOT EOF(RECFILE) DO
       BEGIN
         READ(RECFILE, USER);
         IF CKUSER.USERNAME = USER.USERNAME AND CKUSER.PASSWORD = USER.PASSWORD THEN
              LOGIN
        ELSE
              WRITE('USER NOT FOUND');
       END;
    END.Thank you

    Don't bother:
    http://forum.java.sun.com/thread.jsp?forum=54&thread=539277

  • How I can enable Java ssv helper plugin silently for win7 users with IE9

    here is what happens:
    when I deploy java 7.21 on win7 users, after deployment when users try to Open their IE they get a login screen and apparently it is related to Java ssv helper plugin. it is trying to enable it and needs admin account/password. I am trying to deploy this to about 3000 computers and I dont want all of them start calling helpdesk for this.
    your help is appreciated.

    The following article describes how to create a shared preference file. You can either create preferences that individual users can override, or create locked preferences that individual users cannot override.
    http://kb.mozillazine.org/Lock_Prefs
    (Note: I don't have any personal experience with these files, but another volunteer might post some additional tips and tricks.)

  • Java Progrramming HELP, Needed Urgently, T hanks

    hey guys,
    I have this lab I need to be done tomorrow, its been weeks lol of thinking and figuring things out can someone make it work ? Pleaseeeee !
    I feel like going out and yelling for help lol I have been trying to figure this out for weeks now.
    I am pasting my Lab and My Codes I did so far, And Please I really need this done today at any rate, all help would be kindly appreciated.
    A Java program is required that will produce a number of reports based on the data from the Product file. This file contains the product name, cost, quantity and UPC. The file name must be input. Valid data from the file will be loaded into an array.
    A menu will provide the following options: (Note there are changes from previous assignment.)
    1     Display of all valid product information including extended price and GST including totals sorted by name.
    2     Display of all invalid records sorted by name.
    3     Search and display a certain product by name.
    4     Sort by UPC and use a binary search and display a certain product by UPC. (valid records)
    9 Exit.
    Processing requirements:
    Input the data from a file and load the records into an object array. Use this object array to produce the above reports.
    Code a class definition exactly as given in the following UML.
    (For specific students: you may code the UPC as an integer but if not numeric throw an exception that is handled in main. Document your choice in your submission).
    Product
    ? Name : String
    ? UPC : String
    ? Cost : Real
    ? Quantity : Integer
    + Product (Name : String, UPC : String, Cost : Real, Quantity : Integer)
    + Calculate Extended Cost() : Real
    + Calculate GST(): Real
    Input Record:
    Product name: String
    UPC: String
    Cost: real
    Quantity: integer
    Output Reports
    1. Display of all product information including extended cost and GST including totals of these 3 fields.
    Following is a sample of the output required:
    ************************ Product Cost REPORT ****************************
    Product                    Cost Quantity Extended Cost     GST     Total Cost
    Diamond Necklace 12345678901x 54,321.99 188 10,212,534.12 510,626.71 10,723,160.83
    Tissues 98989898989x 1.99 2 3.98      0.20     4.18
    TOTALS                         10,212,538.10 510,626.91 10,723,165.01
    2. Display of all invalid records and the count.
    Following is a sample of the output required:
    Invalid UPC Records = 1
    Count Record
    1          Tiara Diamond, 12345678901x, 36020.00, 2
    3. Search and display a certain product by name. Display appropriate message if not found.
    Following is a sample of the output required:
    Enter product name: CrownJewels
    CrownJewels 99999999991x     100,000.00 1 100,000.00 5,000.00 $105,000.00
    6. Display the product information sorted by name
    Following is a sample of the output required:
    ************************ Product Cost REPORT ****************************
    Product                    Cost Quantity Extended Cost     GST     Total Cost
    CrownJewels 99999999991x 100,000.00 1 100,000.00 5,000.00 $105,000.00
    Diamond Necklace 12345678901x 54,321.99 188 10,212,534.12 510,626.71 $10,723,160.83
    Pearls      88888888881x 10,000.00 1 10,000.00 500.00 $10,500.00
    RubyRing      77777777771x 10,000.00 1 10,000.00 500.00 $10,500.00
    Tissues      98989898989x 1.99 2 3.98 0.20     $4.18
    TOTALS          (complete these values)           xxx           xxx      xxx
    Java coding requirements for this assignment
    Main methods required
    1.     Load array with all records. Display exception messages only for records that have invalid data in any of the fields. Return array of valid records and logical size.
    2.     Validate the UPC. Display each report when requested from the menu.
    3.     Justify the data in the columns. Right justify numeric fields; left justify the alpha fields.
    4.     A method for each report required in the menu.
    Class methods
    5.     Use the object method for the extended cost.
    6.     Use the object method for the GST.
    You may use additional methods in the main program but do not add any methods in the class definition.
    Use DecimalFormat for rounding.
    Create an array to hold the objects. Assume that we only need to process a file of a maximum of 500 records but the file may be larger than 500 records.
    A Universal Product Code consists of 12 digits. The first digit (from the left) is the UPC type. The next five digits are the Manufacturer code. The next five digits are the product code which is assigned by the manufacturer. The final digit is the check digit. A person can determine the check digit of a Universal Product Code by doing the following:
    Step 1: Sum all of the digits in the odd positions together.
    0+4+0+1+5+9 = 19
    Step 2: Multiply the sum from Step 1 by 3.
    3 * 19 = 57
    Step 3: Sum all of the digits in the even positions together.
    6+2+0+1+8 = 17
    Step 4: Sum together the results from Step 2 and Step 3.
    17 + 57 = 74
    Step 5: Subtract the sum from the next highest multiple of 10.
    80 - 74 = 6 [check digit]
    TEST DATA:
    Step 1: Create 5 or MORE additional records that will test all conditions. Include these in your documentation. Identify what field is tested in your test data. (Example: error in each field of the record, rounding up, rounding down, valid UPC, invalid UPC, formatting of report, file too large
    Step 2: Use the file attached.
    GODDDDDDDDDDDDDD lol pasting it made me go crazy,
    these are my codes so far, HOwever the problem is ONLY DISPLAY MENU SHOWS, nothing else even though i have enough codes that it can show something,
    My codes are as follows:
    I am working on Eclipse.
    import java.util.Arrays;
    import java.util.Scanner;
    import java.io.*;
    import java.util.*;
    import java.io.IOException;
    * Name : Sana Ghani
    * Date : July 10
    public class lab56
         public static Scanner file;
         public static Scanner parse;
         public static Scanner input = new Scanner(System.in);
         public static Scanner searchInput = new Scanner(System.in);
         public static void main(String[] args) throws Exception
              Product1[] validProduct = new Product1[500];
              int logicalSize = 0;
              int menuChoice=0;
              String FileName = getFileName();
              displayMenu();
              switch(menuChoice)
              case 1:
                   displayAllValidRecords(validProduct, logicalSize);
                   try
                   // Open an output stream
                   OutputStream fout = new FileOutputStream ("myfile.txt");
                   // Print a line of text
                   new PrintStream(fout).println ("hello world!");
                   // Close our output stream
                   fout.close();          
                   // Catches any error conditions
                   catch (IOException e)
                        System.err.println ("Unable to write to file");
                        System.exit(-1);
                   break;
              case 2:
                   break;
              case 3:
                   binarySearchByName( validProduct,logicalSize);
                   break;
              case 4:
                   break;
              case 5:
                   break;
              menuChoice = displayMenu();
         public static void display(Product1[]validProduct, int logicalSize)throws Exception
              String Product, UPC;
              double Cost;
              int Quantity;
              for(int index =0; index<logicalSize; index++)
                   Product = validProduct[index].GetName();
                   UPC = validProduct[index].GetUPC();
                   Cost=validProduct[index].GetCost();
                   Quantity=validProduct[index].GetQuantity();
                   System.out.println(Product+"\t\t"+UPC+"\t\t"+Cost+"\t\t"+Quantity);
         public static String getFileName()
              String fileName;
              Scanner input = new Scanner(System.in);
              System.out.print("Please enter a file name: ");
              fileName = input.next();
              return fileName;
         public static int displayMenu()
              int menuChoice;
              boolean validFlag = false;
              do
                   System.out.println("\n\n*************************************");
                   System.out.println(" Product Display Menu ");
                   System.out.println("*************************************");
                   System.out.println("(1)Display All Records");
                   System.out.println("(2)Display All Invalid Records");
                   System.out.println("(3)Search by Product Name");
                   System.out.println("(4)Sort by Product Name");
                   System.out.println("(5)Exit");
                   System.out.println("*************************************");
                   System.out.print("Enter your choice(1-5): ");
                   menuChoice = input.nextInt();
                   if ((menuChoice >= 1) && (menuChoice <= 5))
                        validFlag = true;
                   if (!validFlag)
                        System.out.println("You have chosen " + menuChoice + ", " + menuChoice +
                        " is not valid. Please try again");
              }while(!validFlag);
              return menuChoice;
         public static String loadArray(Product1 [] ValidProduct, String fileName)throws Exception
              int logicalSize=0;//will always have to declare
              String record;//will always have to declare
              String Product, UPC;//variable names from
              double Quantity;
              double Cost;
              Scanner file = new Scanner(new File(fileName));//open
              record = file.nextLine();//read a line
              record = file.nextLine();//read a line
              for(int index = 0; index < ValidProduct.length && file.hasNext(); index++)//check to see if the file has data
                   record = file.nextLine();
                   parse = new Scanner(record).useDelimiter(",");
                   String Name = parse.next();
                   UPC = parse.next();
                   Cost = parse.nextDouble();
                   Quantity=parse.nextDouble();
                   ValidProduct[index] = new Product1 ( Name, UPC, Cost, (int) Quantity);
    //               create the object-- call the constructor and pass info
                   logicalSize++;
              return logicalSize+".txt";
         public static double roundDouble(double value, int position)
              java.math.BigDecimal bd = new java.math.BigDecimal(value);
              bd = bd.setScale(position,java.math.BigDecimal.ROUND_UP);
              return bd.doubleValue();
         * This method will print report about valid records
         public static void displayAllRecords( Product1[]valid, int ValidProduct,
                   Product1[] invalid, int InvalidProduct)
    //          Print valid records
              displayAllValidRecords(valid, ValidProduct);
    //          Print invalid UPC records
              displayAllValidRecords(invalid, InvalidProduct);
         public static void displayOneRecord(Product1[]valid, int index)
              double extendedCost, GST, SumofGST = 0, // Total Extended Cost
              totalCost, SumOfTotalCost = 0; // Total Extended Cost + GST
    //          Print title
              System.out.println(leftJustify("Product", 50) +
                        leftJustify("UPC", 15) +
                        rightJustify("Cost", 10) +
                        rightJustify("Quantity", 5) +
                        rightJustify("Extended Cost", 15) +
                        rightJustify("GST", 5) +
                        rightJustify("Total Cost", 13));
              extendedCost = valid[index].CalculateExtendedCost();
              extendedCost = roundDouble(extendedCost, 2);
              GST = valid[index].CalculateGST();
              GST = roundDouble(GST, 2);
              totalCost = extendedCost + GST;
              totalCost = roundDouble(totalCost, 2);
    //          justify method ensures all values are of the same size
              System.out.println(//leftJustify(i+"",3) + ": " +
                        leftJustify(valid[index].GetName(), 50) +
                        leftJustify(valid[index].GetUPC(), 15) +
                        rightJustify(valid[index].GetCost()+"", 10) +
                        rightJustify(valid[index].GetQuantity()+"", 5) +
                        rightJustify(extendedCost+"", 10) +
                        rightJustify(GST+"", 10) +
                        rightJustify(totalCost+"", 10));
         * This method will print report about valid records
         public static void displayAllValidRecords( Product1[]valid, int validCounter)
              double extendedCost, sumOfExtendedCost = 0, // Total Extended Cost
              GST, sumOfGST = 0, // Total GST
              totalCost, sumOfTotalCost = 0; // Total Extended Cost + GST
              System.out.println("************************ XYZ Product " +
                        "Cost REPORT ****************************" +
    //          Print title
              System.out.println(leftJustify("Product", 50) +
                        leftJustify("UPC", 15) +
                        rightJustify("Cost", 10) +
                        rightJustify("Qty", 5) +
                        rightJustify("Extended Cost", 15) +
                        rightJustify("GST", 5) +
                        rightJustify("Total Cost", 13));
    //          Print Records
              for(int i=0; i<validCounter; i++)
                   extendedCost = valid.CalculateExtendedCost();
                   extendedCost = roundDouble(extendedCost, 2);
                   GST = valid[i].CalculateGST();
                   GST = roundDouble(GST, 2);
                   totalCost = extendedCost + GST;
                   totalCost = roundDouble(totalCost, 2);
    //               justify method ensures all values are of the same size
                   System.out.println(//leftJustify(i+"",3) + ": " +
                             leftJustify(valid[i].GetName(), 50) +
                             leftJustify(valid[i].GetUPC(), 15) +
                             rightJustify(valid[i].getClass()+"", 10) +
                             rightJustify(valid[i].GetQuantity()+"", 5) +
                             rightJustify(extendedCost+"", 10) +
                             rightJustify(GST+"", 10) +
                             rightJustify(totalCost+"", 10));
                   sumOfExtendedCost += extendedCost;
                   sumOfGST += GST;
                   sumOfTotalCost += totalCost;
         private static void sortByName(Product1 [] ValidProduct, int logicalSize) throws Exception
              Product1 temp;
              for (int outer = logicalSize-1; outer > 1; outer --)
                   for (int inner = 0; inner < outer; inner ++)
                        if (ValidProduct[inner].GetName().compareToIgnoreCase(ValidProduct[inner+1].GetName())>0)
                             temp = ValidProduct[inner];
                             ValidProduct[inner] = ValidProduct[inner + 1];
                             ValidProduct [+ 1] = temp;
         public static void binarySearchByName(Product1 [] ValidProduct, int logicalSize)
              int high = logicalSize - 1;
              int low = 0;
              int mid = 0;
              int count = 0;
              int compare = 0;
              boolean found = false;
              System.out.print("Enter a product name");
              String product = input.nextLine();
              while (high >= low && !found)
                   count += 1;
                   mid = (high + low) / 2;
                   compare = ValidProduct[mid].GetName().compareToIgnoreCase(product);
                   if (compare == 0)
                        System.out.println("Found: " + ValidProduct[mid].GetName());
                        found = true;
                   else if (compare < 0)
                        low = mid + 1;
                   else
                        high = mid - 1;
              if (!found)
                   System.out.println(product + " not found.");
              System.out.println(count + " steps");
              System.out.println();
         public static String leftJustify(String field, int width)
              StringBuffer buffer = new StringBuffer(field);
              while (buffer.length() < width)
                   buffer.append(' ');
              return buffer.toString();
         public static String rightJustify(String field, int width)
              StringBuffer buffer = new StringBuffer(field);
              while (buffer.length() < width)
                   buffer.append(' ');
              return buffer.toString();
         public static void displayValidRecords(Product1 [] ValidProduct, int logicalSize) throws Exception {
              long longMAX_POSSIBLE_UPC_CODE = 999999999999L;
              // set input stream and get number
              Scanner stdin = new Scanner(System.in);
              System.out.print("Enter a 12-digit UPC number: ");
              long input =stdin.nextLong();
              long number = input;
              // determine whether number is a possible UPC code
              if ((input < 0)|| (input > longMAX_POSSIBLE_UPC_CODE)) {
                   // not a UPC code
                   System.out.println(input +"is an invalid UPC code");
              else {   
                   // might be a UPC code
                   // determine digits
                   int d12 = (int) (number % 10);
                   number /= 10;
                   int d11 = (int) (number % 10);
                   number /= 10;
                   int d10 = (int) (number % 10);
                   number /= 10;
                   int d9 = (int) (number % 10);
                   number /= 10;
                   int d8 = (int) (number % 10);
                   number /= 10;
                   int d7 = (int) (number % 10);
                   number /= 10;
                   int d6 = (int) (number % 10);
                   number /= 10;
                   int d5 = (int) (number % 10);
                   number /= 10;
                   int d4 = (int) (number % 10);
                   number /= 10;
                   int d3 = (int) (number % 10);
                   number /= 10;
                   int d2 = (int) (number % 10);
                   number /= 10;
                   int d1 = (int) (number % 10);
                   number /= 10;
                   // compute sums of first 5 even digits and the odd digits
                   int m = d2 + d4 d6 d8 + d10;
                   int n = d1 + d3 d5 d7 + d9 + d11;
                   // use UPC formula to determine required value for d12
                   int r = 10 - ((m +3*n) % 10);
                   // based on r, can test whether number is a UPC code
                   if (r == d12) {
                        // is a UPCcode
                        System.out.println(input+" is a valid UPC code");
                   else {   
                        // not a UPCcode
                        System.out.println(input+" is not valid UPC code");
    Any help would be great thanks !!
    Take care,

    1) It's your problem that you waited until the last minute before you went for help...not ours. We'll give your problem the same attention as anyone elses...therefore your problem isn't any more urgent than any other problem here.
    2) I don't intend on doing your entire assignment. Nor do I intend on reading all of it. If you need help with a specific requirement, then post the information/code relevant to that requirement. I don't know how to help you when you bury the problem inside a 9 mile long essay.
    3) Post code in tags so it's formatted and readable. (there's a *code* button up above that makes the tags for you).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Java outputstream java.lang.OutOfMemoryError: Java heap space

    Hi All,
    I am trying to publish a large video/image file from the local file system to an http path, but I run into an out of memory error after some time...
    here is the code
    public boolean publishFile(URI publishTo, String localPath) throws Exception {
            InputStream istream = null;
            OutputStream ostream = null;
            boolean isPublishSuccess = false;
            URL url = makeURL(publishTo.getHost(), this.port, publishTo.getPath());
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            if (conn != null) {
                try {
                    conn.setDoOutput(true);
                    conn.setDoInput(true);
                    conn.setRequestMethod("PUT");
                    istream = new FileInputStream(localPath);
                    ostream = conn.getOutputStream();
                    int n;
                    byte[] buf = new byte[4096];
                    while ((n = istream.read(buf, 0, buf.length)) > 0) {
                        ostream.write(buf, 0, n); //<--- ERROR happens on this line.......???
                    int rc = conn.getResponseCode();
                    if (rc == 201) {
                        isPublishSuccess = true;
                } catch (Exception ex) {
                    log.error(ex);
                } finally {
                    if (ostream != null) {
                        ostream.close();
                    if (istream != null) {
                        istream.close();
            return isPublishSuccess;
        }HEre is the error i am getting...
    Exception in thread "Thread-8773" java.lang.OutOfMemoryError: Java heap space
    at java.util.Arrays.copyOf(Arrays.java:2786)
            at java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:94)
            at sun.net.www.http.PosterOutputStream.write(PosterOutputStream.java:61)
            at com.test.HTTPClient.publishFile(HTTPClient.java:110)
            at com.test.HttpFileTransport.put(HttpFileTransport.java:97)Edited by: ashchawla on Jan 17, 2010 9:21 AM

    It seems that the HttpURLConnection tries to buffer all the data you want to send and doesn't stream the data as it comes.
    This means that you will need at least as much memory as the size of your file (more likely you'll need quite a bit more). This is definitely not ideal for sending huge files, so you might want to look at other HTTP clients, if they are better at handling huge files.
    Try the Apache Commons HTTPClient. I've heard good things about it.
    Thanks for crossposting. You will not get any more help from me. Not here, not on SO.

  • Java expert help me. A NullPointerException !!! I can't solve it.

    I have complied 3 files (SerialBean.java;SerialBuffer.java;ReaderSerial.java) as my package successfully, it is named serial. The package extends javax.comm.*; I wanna do some serial work.
    Then I maked an application :SerialExample1
    --------------------------------------code----------------------------------
    ----------------------------SerialExmaple1.java-----------------------------
    import serial.*;
    import java.io.*;
    import javax.comm.*;
    public class SerialExample1
    public static void main(String args[])
    SerialBean sB=new SerialBean(1);
    sB.Initialize();
    sB.WritePort("Hi,Chrono");
    sB.ClosePort();
    It is good enough to deliver the String "Hi,Chrono".
    Then I maked another windows application :SerialExample2
    ------------------------------------code-------------------------------------
    -----------------------------Frame1.java-------------------------------------
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import com.borland.jbcl.layout.*;
    import serial.*;
    import java.io.*;
    import javax.comm.*;
    public class Frame1 extends JFrame
    private JPanel contentPane;
    private XYLayout xYLayout1 = new XYLayout();
    private Button button1 = new Button();
    private TextField textField1 = new TextField();
    private SerialBean sB=new SerialBean(1);
    //Construct the frame
    public Frame1()
    enableEvents(AWTEvent.WINDOW_EVENT_MASK);
    try
    jbInit();
    catch(Exception e)
    e.printStackTrace();
    //Component initialization
    private void jbInit() throws Exception
    //setIconImage(Toolkit.getDefaultToolkit().createImage(Frame1.class.getResource("[Your Icon]")));
    contentPane = (JPanel) this.getContentPane();
    button1.setLabel("button1");
    button1.addActionListener(new Frame1_button1_actionAdapter(this));
    contentPane.setLayout(xYLayout1);
    this.setSize(new Dimension(400, 300));
    this.setTitle("Frame Title");
    textField1.setText("textField1");
    contentPane.add(button1, new XYConstraints(54, 52, -1, -1));
    contentPane.add(textField1, new XYConstraints(195, 57, -1, -1));
    //Overridden so we can exit when window is closed
    protected void processWindowEvent(WindowEvent e)
    super.processWindowEvent(e);
    if (e.getID() == WindowEvent.WINDOW_CLOSING)
    System.exit(0);
    void button1_actionPerformed(ActionEvent e)
    sB.Initialize();
    sB.WritePort("Hi Chrono");
    sB.ClosePort();
    class Frame1_button1_actionAdapter implements java.awt.event.ActionListener
    private Frame1 adaptee;
    Frame1_button1_actionAdapter(Frame1 adaptee)
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e)
    adaptee.button1_actionPerformed(e);
    ---------------------------SerialExample2.java--------------------------------
    import javax.swing.UIManager;
    import java.awt.*;
    public class SerialExample2
    private boolean packFrame = false;
    //Construct the application
    public SerialExample2()
    Frame1 frame = new Frame1();
    //Validate frames that have preset sizes
    //Pack frames that have useful preferred size info, e.g. from their layout
    if (packFrame)
    frame.pack();
    else
    frame.validate();
    //Center the window
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    Dimension frameSize = frame.getSize();
    if (frameSize.height > screenSize.height)
    frameSize.height = screenSize.height;
    if (frameSize.width > screenSize.width)
    frameSize.width = screenSize.width;
    frame.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
    frame.setVisible(true);
    //Main method
    public static void main(String[] args)
    try
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    catch(Exception e)
    e.printStackTrace();
    new SerialExample2();
    It is a bad code!!! I compiled them seccessfully but It can't work .The java system gave
    some wrong messages
    Exception occurred during event dispatching:java.lang.NullPointerException     at serial.SerialBean.WritePort(SerialBean.java:115)     at Frame1.button1_actionPerformed(Frame1.java:66)     at Frame1_button1_actionAdapter.actionPerformed(Frame1.java:82)     at java.awt.Button.processActionEvent(Button.java:329)     at java.awt.Button.processEvent(Button.java:302)     at java.awt.Component.dispatchEventImpl(Component.java:2593)     at java.awt.Component.dispatchEvent(Component.java:2497)     at java.awt.EventQueue.dispatchEvent(EventQueue.java:339)     at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:131)     at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:98)     at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)     at java.awt.EventDispatchThread.run(EventDispatchThread.java:85)-----------------------------------------------------------------------------------
    I tried to debug it in Frame1.java:66 and SerialBean.java:115 but I can not find any error.
    How to deal with it?
    Here are the code about package serial
    -----------------------------------code--------------------------------------------
    ----------------------------SerialBean.java----------------------------------------
    package serial;
    import java.io.*;
    import java.util.*;
    import javax.comm.*;
    * This bean provides some basic functions to implement full dulplex
    * information exchange through the srial port.
    public class SerialBean
    static String PortName;
    CommPortIdentifier portId;
    SerialPort serialPort;
    static OutputStream out;
    static InputStream in;
    SerialBuffer SB;
    ReadSerial RT;
    * Constructor
    * @param PortID the ID of the serial to be used. 1 for COM1,
    * 2 for COM2, etc.
    public SerialBean(int PortID)
    PortName = "COM" + PortID;
    * This function initialize the serial port for communication. It startss a
    * thread which consistently monitors the serial port. Any signal capturred
    * from the serial port is stored into a buffer area.
    public int Initialize()
    int InitSuccess = 1;
    int InitFail = -1;
    try
    portId = CommPortIdentifier.getPortIdentifier(PortName);
    try
    serialPort = (SerialPort)
    portId.open("Serial_Communication", 2000);
    } catch (PortInUseException e)
    return InitFail;
    //Use InputStream in to read from the serial port, and OutputStream
    //out to write to the serial port.
    try
    in = serialPort.getInputStream();
    out = serialPort.getOutputStream();
    } catch (IOException e)
    return InitFail;
    //Initialize the communication parameters to 9600, 8, 1, none.
    try
    serialPort.setSerialPortParams(9600,
    SerialPort.DATABITS_8,
    SerialPort.STOPBITS_1,
    SerialPort.PARITY_NONE);
    } catch (UnsupportedCommOperationException e)
    return InitFail;
    } catch (NoSuchPortException e)
    return InitFail;
    // when successfully open the serial port, create a new serial buffer,
    // then create a thread that consistently accepts incoming signals from
    // the serial port. Incoming signals are stored in the serial buffer.
    SB = new SerialBuffer();
    RT = new ReadSerial(SB, in);
    RT.start();
    // return success information
    return InitSuccess;
    * This function returns a string with a certain length from the incomin
    * messages.
    * @param Length The length of the string to be returned.
    public String ReadPort(int Length)
    String Msg;
    Msg = SB.GetMsg(Length);
    return Msg;
    * This function sends a message through the serial port.
    * @param Msg The string to be sent.
    public void WritePort(String Msg)
    int c;
    try
    for (int i = 0; i < Msg.length(); i++)
    out.write(Msg.charAt(i));
    } catch (IOException e) {}
    * This function closes the serial port in use.
    public void ClosePort()
    RT.stop();
    serialPort.close();
    ----------------------------ReadSerial.java--------------------------------------
    package serial;
    import java.io.*;
    * This class reads message from the specific serial port and save
    * the message to the serial buffer.
    public class ReadSerial extends Thread
    private SerialBuffer ComBuffer;
    private InputStream ComPort;
    * Constructor
    * @param SB The buffer to save the incoming messages.
    * @param Port The InputStream from the specific serial port.
    public ReadSerial(SerialBuffer SB, InputStream Port)
    ComBuffer = SB;
    ComPort = Port;
    public void run()
    int c;
    try
    while (true)
    c = ComPort.read();
    ComBuffer.PutChar(c);
    } catch (IOException e) {}
    ------------------------------SerialBuffer.java-------------------------------------
    package serial;
    public class SerialBuffer
    private String Content = "";
    private String CurrentMsg, TempContent;
    private boolean available = false;
    private int LengthNeeded = 1;
    * This function returns a string with a certain length from the incomin
    * messages.
    * @param Length The length of the string to be returned.
    public synchronized String GetMsg(int Length)
    LengthNeeded = Length;
    notifyAll();
    if (LengthNeeded > Content.length())
    available = false;
    while (available == false)
    try
    wait();
    } catch (InterruptedException e) { }
    CurrentMsg = Content.substring(0, LengthNeeded);
    TempContent = Content.substring(LengthNeeded);
    Content = TempContent;
    LengthNeeded = 1;
    notifyAll();
    return CurrentMsg;
    * This function stores a character captured from the serial port to the
    * buffer area.
    * @param t The char value of the character to be stored.
    public synchronized void PutChar(int c)
    Character d = new Character((char) c);
    Content = Content.concat(d.toString());
    if (LengthNeeded < Content.length())
    available = true;
    notifyAll();
    Help me !!!

    First thing to say is that you really should check if the initialisation was successful in
    button1_actionPerformed()You should be checking the return value on the SerialBean Initialize() method. If the initialisation has failed, then the null pointer exception will be thrown because there will be no stream to write to.
    I would also recommend rewriting the catches in the SerialBean Initialize() method to dump the stack trace from the caught exception and any additional information that the exception holds for example:
    } catch (PortInUseException e) {
        e.printStackTrace();
        return InitFail;
    }This will give you a lot more information to work with if it is an initialisation problem.

  • MS Access and Java JDBC help!

    Hello, I having trouble with a java GUI.
    I have a MS Access named Database.mdb with a table named Customer which I want my GUI to access.
    I want my GUI to be able to flick through the records using the field I have made for them.
    I already have connected the database using windows xp's "System DSN" and have no problem creating tables using sql statements in my code
    Who can help me? any information would be great.
    Thanks

    I'm doing an inventory software application too...but my application is an automatic software inventory, is automatic your application??
    My result is the software that are intalled in a machine..is your project too?
    Sorry, my english is not very good...

  • Why the same name of process comes out in AIX , in java. please help me.

    Hello.
    I have two questions related to Jvm.
    I've developed Job scheduler program which is doing somthing as the DB schedule is set in the way of Multi
    thread. Currently , I'm in the process of testing this one. It is good , if in the normal case. However, When
    doing Shell, if the application have so a lot to do the Shell, it has a little problem.
    My developing environment is
    OS : AIX 5.3
    JRE : IBM J9 VM (build 2.4, JRE 1.6.0 IBM J9 2.4 AIX ppc-32 jvmap3260sr7-20091214_49398
    (JIT enabled, AOT enabled)
    nofiles(descriptors) 2000
    maxuproc 4096 Maximum number of PROCESSES allowed
    per user True
    In order to execute Shell in My Scheduler program , I tested Runtimeexec() or ProcessBuilder.
    The result of mine in the test , when the executed Shell got over 300 is
         1. The jvm processes that I execute at the first time are shown up , after Shell go to the finish, the
    processes are all in the disappearance again , and at last The processes that I executed at the first time are
    remaining. It's like the process is duplicated process in the maximum of 70.
    When I do shell about 200 to be executed simultaneously, Duplicated jvm about 3 appeared momentarily, then
    disappeared, and also under 120, No duplicated case is found when under 120.
    ps -ef result is below , when shell is excuted
    UID PID PPID C STIME TTY TIME CMD
    jslee 626906 1 0 11, May - 2:20 java -
    DD2_JC_HOME=/source/jslee/JOB -Dfile.encoding=euc-kr jobserver.JobServerMain
    jslee 1421522 626906 0
    19:36:16 - 0:00 java -DD2_JC_HOME=/source/jslee/JOB -Dfile.encoding=euc-kr jobserver.JobServerMain
    ....Skip.....
    jslee 4374620 626906 0 19:34:06 - 0:00 java -DD2_JC_HOME=/source/jslee/JOB -
    Dfile.encoding=euc-kr jobserver.JobServerMain
    (the process list about 60)
    *the first question : Why a lot of duplicated jvm are shown up when in alot of shell to be executed ?
    *the second question : As you can see above , How can I solve out the problem.
    *Is there some option that I can set up when starting Jvm?
    ---Next question---
    My developing environment is
    OS : SunOS 5.8
    JRE : Java(TM) SE Runtime Environment (build 1.6.0_18-b07)
    Java HotSpot(TM) Server
    VM (build 16.0-b13, mixed mode)
    nofiles(descriptors) 256
    As shown obove , the value of descriptors is 256 .
         My scheduler program executed 300 shell at the same time, in result my program was abnormalily
    terminated after doing shell about 180.
    the Exception info is
    java.io.IOException: Cannot run program "sh": error=24, exceeding the number of opened files
         at
    java.lang.ProcessBuilder.start(Unknown Source)
         at java.lang.Runtime.exec(Unknown Source)
         at
    java.lang.Runtime.exec(Unknown Source)
         at java.lang.Runtime.exec(Unknown Source)
    or
    java.net.SocketException: exceeding the number of opened files     at java.net.PlainSocketImpl.socketAccept
    (Native Method)
    &#46608;&#45716;
    java.io.IOException: exceeding the number of opened files     at
    java.io.UnixFileSystem.createFileExclusively(Native Method)
         at java.io.File.checkAndCreate(Unknown
    Source)
         at java.io.File.createTempFile(Unknown Source)
    *question : If I continuously request to open a file that go over system limit, is it possible for JVM to be
    terminated?
    *question : Is there a method that obtains state of System limit in the java library.
    *question : what is the best solution to cope with ?
    Please help me
    =

    struts-config.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
    <struts-config>
      <form-beans>
           <form-bean name="registrationForm" type="ndlinh.struts.lab.RegistrationForm" />
      </form-beans>
      <action-mappings>
           <action path="/register"
                   type="ndlinh.struts.lab.RegistrationAction" // action class
                   name="registrationForm" // form bean name
                   validate="false"
                   scope="request"
                   input="registration.jsp" >
                <forward name="success" path="/jsp/success.jsp"  />
                <forward name="failure" path="/jsp/failure.jsp"  />
           </action>
      </action-mappings>
    </struts-config>HTH

  • Pricing : ABAP to Java conversion help needed

    Hi all.
    I am basically an ABAP developer. My recent assignment needs some java coding.
    It will be very helpful if we anybody helps me in finding the corresponding pricing fields in java.
    The abap code is as follows
    check : xkomv - kgrpe  = '  '.
    check: xkomv - xkbetr ne 0.
    check : komp - kpein ne 0.
    if komp - netwr < 0.
      komp - netpr = 0 - komp - netpr.
    endif.
    xkwert  = (        (  ( komp - netpr * ( 100000 + xkomv - xkbetr))     / 100000)
    komp-mglme / komp-kumza * komp - kumne / 1000 / komp - kpein )
      - komp-netwr.
    Please help in converting this abap code to its corresponding java code.
    Thanks and Regards
    Deepika

    Here is the code I have developed: Please check and let me know if there are any changes
    import java.math.BigDecimal;
    import com.sap.spe.pricing.customizing.PricingCustomizingConstants;
    import com.sap.spe.pricing.transactiondata.PricingTransactiondataConstants;
    import com.sap.spe.pricing.transactiondata.userexit.IPricingConditionUserExit;
    import com.sap.spe.pricing.transactiondata.userexit.IPricingItemUserExit;
    import com.sap.spe.pricing.transactiondata.userexit.ValueFormulaAdapter;
    public class ZS2S_IPC_ZDCP extends ValueFormulaAdapter {
          public BigDecimal overwriteConditionValue(
                IPricingItemUserExit item,
                IPricingConditionUserExit condition) {
                BigDecimal kompKumza = new BigDecimal(String.valueOf(condition.getFraction().getNumerator()));
                BigDecimal kompKumne = new BigDecimal(String.valueOf(condition.getFraction().getDenominator()));
                boolean xkomvKgrpe = condition.isGroupCondition();
                BigDecimal kompKpein = condition.getPricingUnit().getValue();    
                BigDecimal kompNetwr  = item.getNetValue().getValue();
                BigDecimal kompNetpr  = item.getNetPrice().getValue();
                BigDecimal xkomvKbetr = condition.getConditionRate().getValue();
                BigDecimal kompMglme = item.getBaseQuantity().getValue();
                  if ( xkomvKgrpe = true )
                      return PricingTransactiondataConstants.ZERO;
                  if ( kompKumza != PricingTransactiondataConstants.ZERO )
                    return PricingTransactiondataConstants.ZERO;
                if ( kompKumne != PricingTransactiondataConstants.ZERO )
                      return PricingTransactiondataConstants.ZERO;   
                if ( kompKpein != PricingTransactiondataConstants.ZERO )
                        return PricingTransactiondataConstants.ZERO;
                if (kompNetwr.compareTo(PricingTransactiondataConstants.ZERO) < 0 )
                      kompNetpr = (PricingTransactiondataConstants.ZERO).subtract(kompNetwr);
                 BigDecimal y = new BigDecimal("100000");
                BigDecimal a = y.add(xkomvKbetr);
                BigDecimal temp = kompNetpr.multiply(a);
                BigDecimal result1 = temp.divide(y, 2, BigDecimal.ROUND_HALF_UP);
                BigDecimal result2 = result1.multiply(kompMglme)
                                         .divide(kompKumza, 2 BigDecimal.ROUND_HALF_UP).multiply(kompKumne).divide(kompKpein, 2,  BigDecimal.ROUND_HALF_UP);
                BigDecimal Result = result2.subtract(kompNetwr);
              return Result;
    Edited by: Deepika Mallya on Aug 6, 2009 9:08 AM

  • Do week-long java courses help to understand java &  get a job?

    i tried searching for this topic before posting, but "courses" "classes" & "instruction" come up with a lot that has nothing to do with the topic at hand. :)
    like many others, i'm teaching myself out of a book (Deitel). so far i've been able to understand the material and create programs based on the exercises. however, i'm now into the meat of OOP with superclass, subclasses, how they interact and the like and i'm having a rough go of it. i can diagram and understand the abstract concept, but when i'm faced with an actual program example i have a difficult time following the interactions between classes.
    i'm considering taking one of those 5 day classes, but am wary of how much they will actually be able to cover in detail (not to mention the $$). has anyone here taken one of those classes and found them to be of great benefit to learning the OOP portion of Java? did it give you enough understanding to obtain an entry-level job?
    btw, i'm doing a pro bono project for a small company to get some real world experience. (i've heard that suggestion many times in regards to obtaining one's "experience" w/o a job)
    thank you all very much for your help.

    I took a week long course to learn Java. It worked I did learn the basics of Java but I did already know how to program in C and VB at the time. I found the AWT section of the class to be very valuable,cosidering I mostly write GUI. And the concepts of AWT mostly all apply to swing so that didn't set me back at all. Depending on the school it may help you to understand OOP. But be careful because most schools progress the class at the skill level of the majorty. So if you have 15 people in the class and 9 of them know nothing about programing your probably going to spend the week learning what a variable and a while loop do, you all pay the same tuition and they would rather 6 of you leave then 9 of you leave. If you have some prior programming knowledge I would recomend finding a class that caters to that.

  • InputStream / OutputStream Help

    I have in a series 10 commands to be executed on a server. so i am using Buffered OutputStream and DataOutputStream to write those commands to server.
    these commands have a set of protocol rule to be followed.
    for example i am creating a byte array and i am appending those protocol rules to the byte array and then finally to the stream and then writing to the socket of the server.
    everything works fine here.
    After that i must read the messages from the server.
    this is also fine but t�he problem is everytime i read different input for each command.
    i dont know why!!!!
    so my read function is as follows,
    import java.net.*;
    public class xxxxx
    InputStream instream;
    OutputStream outstream;
    public void OpenConnection() throws ConnectException,UnknownHostException
    try
         tcpipSocket = new Socket(tcpipparameters.getIpAddress(),tcpipparameters.getPortNumber());
    catch(IOException exception)
         System.out.println(exception.toString());
    try
         outstream = tcpipSocket.getOutputStream();
         instream = tcpipSocket.getInputStream();
         dos = new DataOutputStream(outstream);
         BufferedOutputStream bos= new BufferedOutputStream(dos);
         dis = new DataInputStream(instream);
         BufferedInputStream bis = new BufferedInputStream(dis);
    ////////// now i start the command execution on the server
    ///// The 1st Command --------------(The INIT Command)
         byte[] init = {0,6,0,2};
         init = createMessage.calculateCheckSum(init);
         int len = init.length;
         //dos.write(init,0,len);
         bos.write(init);
         bos.flush();
         int available;
         while((available = bis.available()) > 0)
              byte[] data = new byte[available];
              bis.read(data);
              for(int i = 0 ; i < data.length; i++)
                   System.out.print(data);
    ////////////////// The 2nd Command -------------------(IDENTIFY)
    byte[] identify = {0,16,0,20};
    // The protocol version number is inserted in to the IDENTIFY byte[]array
    int protocol_version_number = 512;
    byte[] protocol = {(byte)(protocol_version_number/256) ,(byte)(protocol_version_number%256) };
    byte[] temp = new byte[ identify.length +  protocol.length] ;
    System.arraycopy( identify, 0, temp, 0, identify.length ) ;
    System.arraycopy(protocol, 0, temp, identify.length, protocol.length ) ;
    identify = temp ;
    String PR_SName = "PRS2.0";
    identify = createString.stringData(identify,PR_SName);
    identify = createMessage.calculateCheckSum(identify);
    len = identify.length;
    bos.write(identify);
    bos.flush();
    int length1 = bis.available();
    System.out.println("length of the BufferedInputStream = " + length1);
    StringBuffer sb = new StringBuffer();
    for (int i=1; i<=length1; i++)
         char reply = (char)bis.read();
         sb.append(reply);
    System.out.println(sb.toString());
    ////////////////// The 3rd Command and So on................................
    catch(IOException exception)
         System.err.println("message = " + exception.getMessage());
    catch(InterruptedException e)
         System.err.println("Error =" + e);
    finally
         try
              //flush and close both "Instream" and "Outstream"
              dos.close();
              dis.close();
              instream.close();
              outstream.close();
         catch (IOException ex)
              ex.printStackTrace();
    every time the reading from the server is different.
    but i want to have the exact number of bytes to read everytime.
    so please correct me where i am wrong.
    With regards,
    Ashok
              public void CloseConnection()throws IOException
                        tcpipSocket.close();

    I would say the answer is in my previous replies to your question. I suggest you have another read of them.

  • Java Stream help!!

    I have in a series 10 commands to be executed on a server. so i am using Buffered OutputStream and DataOutputStream to write those commands to server.
    these commands have a set of protocol rule to be followed.
    for example i am creating a byte array and i am appending those protocol rules to the byte array and then finally to the stream and then writing to the socket of the server.
    everything works fine here.
    After that i must read the messages from the server.
    this is also fine but t�he problem is everytime i read different input for each command.
    and sometime i read the exact bytes
    i dont know why!!!!
    so my read function is as follows,
    import java.net.*;
    public class xxxxx
    InputStream instream;
    OutputStream outstream;
    public void OpenConnection() throws ConnectException,UnknownHostException
    try
    tcpipSocket = new Socket(tcpipparameters.getIpAddress(),tcpipparameters.getPortNumber());
    catch(IOException exception)
    System.out.println(exception.toString());
    try
    outstream = tcpipSocket.getOutputStream();
    instream = tcpipSocket.getInputStream();
    dos = new DataOutputStream(outstream);
    BufferedOutputStream bos= new BufferedOutputStream(dos);
    dis = new DataInputStream(instream);
    BufferedInputStream bis = new BufferedInputStream(dis);
    ////////// now i start the command execution on the server
    ///// The 1st Command --------------(The INIT Command)
    byte[] init = {0,6,0,2};
    init = createMessage.calculateCheckSum(init);
    int len = init.length;
    //dos.write(init,0,len);
    bos.write(init);
    bos.flush();
    int available;
    while((available = bis.available()) > 0)
    byte[] data = new byte[available];
    bis.read(data);
    for(int i = 0 ; i < data.length; i++)
    System.out.print(data);
    ////////////////// The 2nd Command -------------------(IDENTIFY)
    byte[] identify = {0,16,0,20};
    // The protocol version number is inserted in to the IDENTIFY byte[]array
    int protocol_version_number = 512;
    byte[] protocol = {(byte)(protocol_version_number/256) ,(byte)(protocol_version_number%256) };
    byte[] temp = new byte[ identify.length + protocol.length] ;
    System.arraycopy( identify, 0, temp, 0, identify.length ) ;
    System.arraycopy(protocol, 0, temp, identify.length, protocol.length ) ;
    identify = temp ;
    String PR_SName = "PRS2.0";
    identify = createString.stringData(identify,PR_SName);
    identify = createMessage.calculateCheckSum(identify);
    len = identify.length;
    bos.write(identify);
    bos.flush();
    int length1 = bis.available();
    System.out.println("length of the BufferedInputStream = " + length1);
    StringBuffer sb = new StringBuffer();
    for (int i=1; i<=length1; i++)
    char reply = (char)bis.read();
    sb.append(reply);
    System.out.println(sb.toString());
    ////////////////// The 3rd Command and So on................................
    catch(IOException exception)
    System.err.println("message = " + exception.getMessage());
    catch(InterruptedException e)
    System.err.println("Error =" + e);
    finally
    try
    //flush and close both "Instream" and "Outstream"
    dos.close();
    dis.close();
    instream.close();
    outstream.close();
    catch (IOException ex)
    ex.printStackTrace();
    public void CloseConnection()throws IOException
    tcpipSocket.close();
    every time the reading from the server is different.
    but i want to have the exact number of bytes to read everytime.
    so please correct me where i am wrong.
    With regards,
    Ashok

    You cannot ask the Java Socket system how many bytes you should read. It doesn't know.
    The number of bytes to be read has to be specified in some way in your protocol. Standard approaches include putting the number of bytes itself into the data stream, or using a terminator character.
    In another thread I commented that every usage of available() that I'd ever seen had been wrong. I'm not entirely glad to see that this remains true.
    Sylvia.

Maybe you are looking for

  • Easy RFC lookup from XSLT mapping using a java class (getting Error)

    Hi All, I am trying to implement the sample scenario for calling RFC from xslt with the help of wrapper class. I am getting following error. com.sap.aii.mapping.lookup.LookupException: Internal lookup service is not registered. Invoking the lookup se

  • How to use keycols with wildcard & TABLEEXCLUDE & MAPEXCLUDE .

    Hi All, I would like to use KEYCOLS for Table which dont have Indexes, and in same parameter file i would like to use wildcard for table which has indexes. so parameter file will has to update ONLY,when table without index will created. and wildcard

  • Remote Camera Trigger

    I spoke with some Adobe LR staff in Las Vegas at Photoshop World, and inquired about a remote camera trigger for LR. I posted frequently during the LR Beta for this very option. Phase One makes C1-Pro, the digital download and viewing software mandat

  • Finding iPAD in iTunes

    Trying to transfer files from a DVD to a documents app on my iPAD.  Instructions say to find the iPAD  in the list in iTunes, click on "Apps" in the iPAD menu bar, then file sharing.  I don't see an iPAD icon in iTunes - what am I missing?  Thanks

  • Restoring data from Itunes to Ipod

    I have the 5th generation Ipod Video. In trying to add some post cast and music to my ipod...I loaded the music,etc. on I tunes...then pluged my ipod in...it walked thru the loading process....and said that the update was complete. However, non of th