String and arraylist

i have this code that retrieves files from a folder and displays them as an array. what i want to do is drop the .xxx extension from the files.
i use this code and it works fine
               String junk = "1220145678999345.abc";
               System.out.println(junk);
               junk = junk.substring(0,junk.length()-4);
               System.out.println(junk);but when i try to set the String junk = files; its cant convert???
here is my code, can anyone make a suggestion on how
     public static void main(String args[])
          String folderName = "\\C:\\unload";
          String processedFolderName = "\\C:\\unload_processed";
          File f = new File(folderName);
          File files[] = f.listFiles();
          try
               for(int i = 0; i < files.length; i++)
                    if(files.isFile())
                         System.out.println(files[i]);
                         BufferedReader inStream = new BufferedReader(new FileReader(files[i]));
                         String line = inStream.readLine();
                         File list = files[i];//list of files in array
                         for(int c = 0; c < list.length(); c ++)
                              while(line != null)
                                   //System.out.print(line + "\n");
                                   line = inStream.readLine();
                              }//while     
                         }//for     
                         inStream.close();                     
                    }//if
               }//for
               String junk = "1220145678999345.abc"; //would like to set this to files[i] but it wont let me - how do i resolve this???
               System.out.println(junk);
               junk = junk.substring(0,junk.length()-4);
               System.out.println(junk);
          }//try
          catch(FileNotFoundException e)
               System.out.println("FileNotFoundException: " + e.getMessage());
               e.printStackTrace();
          }//catch
          catch(IOException e)
               System.out.println("IOException: " + e.getMessage());
               e.printStackTrace();
          }//catch          
     }//main

File list = files;//list of files in array
for(int c = 0; c < list.length(); c ++) {
This doesn't make sense.
"list" is actually the file that's stored at position i of the list of files. Length returns the file size.
For every byte c in the file, you read the entire file and... do nothing with the data.

Similar Messages

  • How to Convert the Stream of strings into ArrayList Integer

    I have a String st = "12 54 456 76ASD 243 646"
    what I want to do is print it like this from the ArrayList<Integer>:
    12
    54
    456
    243
    646
    It should catch the "76ASD" exception as it contain String Character.
    This is how I am doing, which it seems to work but when it reaches the 76ASD it catches the exception so it is not adding the rest to the Arraylist, therefore I could not print in sequence.
      public static void main(String[] args) {
            // TODO code application logic here
            getDatas(testString);
            for (int i = 0; i < at.size(); ++i) {
                System.out.println(at.get(i));
        private static ArrayList<Integer> getDatas(String aString) {
            StringTokenizer st = new StringTokenizer(aString);
            try {
                while (st.hasMoreTokens()) {
                    String sts = "";
                    sts = st.nextToken();
                    at.add(Integer.parseInt(sts));
            } catch (Exception e) {
                System.out.println("Error: " + e);
            return at;
        }Please guide me where I am going
    Thanks

    paulcw wrote:
    This is one of the few cases where I'd say catching an exception as part of the design is acceptable. When parsing, either something parses, or it doesn't. Using parseInt, we're parsing the string and using the result of the parse. By using a regular expression, we're parsing it twice, in two different ways, which may get out of sync. Not only that, if you have a more complicated case, like negative numbers and decimals, the regex gets really ugly.
    I agree this is exactly the case where it is appropriate to try, catch, handle, move on. I sometimes wish there were an Integer.isValid(String) method, but even if there were, we'd call it, and if it returned true, we'd then call parseInt anyway, which would repeat the same work that isValid did. All it would buy us would be an if test instead of a try/catch.

  • Saving NSDatePicker to a string and saving that to NSUserDefaults...

    Saving NSDatePicker to a string and saving that to NSUserDefaults I have it saved to a string then I have code that should save it to NSUSerDefaults so that when the program starts it is saved as the string not null. Here is the code [CODE]#import "MainView.h"
    #import "DateView.h"
    @implementation MainView
    -(void)awakeFromNib
    [self removeFromSuperview];
    [self addSubview:dateView];
    [dateView setdateandtime];
    [dateView permsavedattime];
    @end [/CODE] [CODE]#import "DateView.h"
    #include "MainView.h"//Use #import this is to see if #include Works
    @implementation DateView
    -(IBAction)showuserdefaultdate
    [self userdefaultdate];
    //dateoutput.text =tddate;
    -(void)permsavedattime
    tddate=[prefs stringForKey:@"testing"];
    tdtime=[prefs stringForKey:@"timetesting"];
    dateoutput.text =[[NSString alloc] initWithFormat:@"%@",tddate];
    -(void)userdefaultdate
    prefs =[NSUserDefaults standardUserDefaults];
    [prefs setInteger:tddate forKey:@"testing"];
    [prefs setObject:tdtime forKey:@"timetesting"];
    -(void)setdateandtime
    [Today setDate:[NSDate date] animated:YES];
    //formatting date style
    dateformatter = [ [ NSDateFormatter alloc ] init ];
    [ dateformatter setDateStyle:NSDateFormatterLongStyle];
    [ dateformatter setTimeStyle:NSDateFormatterNoStyle ];//makes it so the time is not included
    //[ formatter setTimeStyle:NSDateFormatterLongStyle ];//set to anystyle besides
    //NoStyle if you dont want time included.
    [Time setDate:[NSDate date] animated:YES];
    //formatting date style
    timeformatter = [ [ NSDateFormatter alloc ] init ];
    [ timeformatter setDateStyle:NSDateFormatterNoStyle];//makes it so it doesn't get the date
    [ timeformatter setTimeStyle:NSDateFormatterShortStyle];//makes it so the time is just hour and minute and A.M. or P.M.
    //[ formatter setTimeStyle:NSDateFormatterLongStyle ];//set to anystyle besides
    //NoStyle if you dont want time included.
    -(IBAction)recieveDate
    tddate= [dateformatter stringFromDate:Today.date];//Asigning the date to the string
    dateoutput.text =tddate;
    -(IBAction)recievetime
    tdtime= [timeformatter stringFromDate:Time.date];//Asigning the date to the string
    timeoutput.text =tdtime;
    -(IBAction)canceltime
    [Time setDate:[NSDate date] animated:YES];
    tdtime= [timeformatter stringFromDate:Time.date];//Asigning the date to the string
    timeoutput.text =tdtime;
    -(IBAction)canceldate
    [Today setDate:[NSDate date] animated:YES];
    tddate= [dateformatter stringFromDate:Today.date];//Asigning the date to the string
    dateoutput.text =tddate;
    @end[/CODE] What am I missing? It keeps coming up Null I need it saved right so I can send it through email

    softwarespecial wrote:
    why can't I have the prefs saved in the .h
    You can save that address in an ivar if you want to, but there's no purpose to that. The standardUserDefaults object is a +shared class object+. It's like a dictionary object that's maintained for your program by the NSUserPreferences class. You can read from or write to it at any time for the duration of your program. So whenever you get the shared object's address [NSUserDefaults standardUserDefaults], you're just getting the address of that same object each time.
    In case the above doesn't make sense, I ran across a good explanation by Danneman in the last message on this page: [http://www.iphonedevsdk.com/forum/iphone-sdk-development/18716-set-settings-va riable-code.html].
    When I did that as you so wisely pointed out it didn't work but when I saved it at each point I needed it it works.
    When you change two things at once it's easy to forget the first and assume the second change solved the problem. Actually, I don't think saving prefs in your ivar had anything to do with your bug. What fixed it was getting a pointer to the shared std defaults object in this method:
    -(void)permsavedattime
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults]; <-- get the shared object
    tddate=[prefs stringForKey:@"testing"];
    tdtime=[prefs stringForKey:@"timetesting"];
    dateoutput.text =[[NSString alloc] initWithFormat:@"%@",tddate];
    Without the first line of the above, I'm fairly sure that your prefs ivar was nil. I didn't see any code that initialized that ivar prior to the first time userdefaultdate ran. It looked to me like permsavedattime ran at start up, well before prefs was set in userdefaultdate. If you're interested in backtracking, restore the file to the way it was when you posted, then add a NSLog() like this:
    -(void)permsavedattime
    // NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults]; <-- get the shared object
    NSLog(@"prefs=%@", prefs);
    tddate=[prefs stringForKey:@"testing"];
    tdtime=[prefs stringForKey:@"timetesting"];
    dateoutput.text =[[NSString alloc] initWithFormat:@"%@",tddate];
    I wish to save lets say five different things to NSUSerDefaults would I be able to do it all with my NSUserDefaults prefs or would I have to create a another one for some of them?
    You know the answer to your second question now, right? The important point is that you're never creating the shared object, you're just asking for its address whenever you need it.
    Btw, there's another user defaults method you should know about: The synchronize method writes the data to disk. You might want to do that when your app is ready to exit. E.g., in the app delegate:
    - (void)applicationWillTerminate:(UIApplication *)application {
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    [prefs synchronize];
    Although the docs suggest synchronize when the app is about to exit, I'm not sure it's necessary. I think the system might write the defaults out to disk anyway when the app terminates, but not sure about this. +User Defaults Programming Topics for Cocoa+ says:
    On Mac OS X v10.5 and later, in applications in which a run-loop is present, synchronize is automatically invoked at periodic intervals. Consequently, you might synchronize before exiting a process, but otherwise you shouldn’t need to.
    The above is in the iPhone edition, so I think it applies.
    It might also be a good idea to update the data and call resetStandardUserDefaults in didReceiveMemoryWarning. I'm not clear about the need for reset either though, since the system may do that for you as well. But on a memory warning, you would definitely want to update the user default data if some of it is stored in an object to be released. You can find out how your app behaves on a memory warning by selecting Hardware->Simulate Memory Warning from the iPhone Simulator menu.
    - Ray

  • Differnce between null string and an empty string??

    what is the major difference between null string and an empty string??
    I wrote the following simple program and I could see some different output.
    Other than that, any other differences that we should pay attention to???
    C:\>java TestCode
    Hello
    nullHello
    public class TestCode
         public static void main(String[] s)
         {     String s1 = "";
              String s2 = null;
              System.out.println(s1 + "Hello");
              System.out.println(s2 + "Hello");
    }

    There's a big difference between the two. A null String isn't pointing to an object, but an empty String is. For example, this is perfectly fine:
    public class TestCode
        public static void main(String[] args)
            String s = "";
            System.out.println(s.length());
    } It prints out 0 for the length of the String, just as it should. But this code will give you a NullPointerException:
    public class TestCode
        public static void main(String[] args)
            String s = null;
            System.out.println(s.length());
    } Since s isn't pointing to anything, you can't call its methods.

  • How to check empty string and null? Assign same value to multiple variables

    Hi,
    1.
    How do I check for empty string and null?
    in_value IN VARCHAR2
    2. Also how do I assign same value to multiple variables?
    var_one NUMBER := 0;
    var_two NUMBER := 0;
    var_one := var_two := 0; --- Gives an error
    Thanks

    MichaelS wrote:
    Not always: Beware of CHAR's:
    Bug 727361: ZERO-LENGTH STRING DOES NOT RETURN NULL WHEN USED WITH CHAR DATA TYPE IN PL/SQL:
    SQL> declare
      2    l_str1   char (10) := '';
      3    l_str2   char (10) := null;
      4  begin
      5  
      6    if l_str1 is null
      7    then
      8      dbms_output.put_line ('oh STR1 is null');
      9    elsif l_str1 is not null
    10    then
    11      dbms_output.put_line ('oh STR1 is NOT null');
    12    end if;
    13  
    14    if l_str2 is null
    15    then
    16      dbms_output.put_line ('oh STR2 is null');
    17    elsif l_str2 is not null
    18    then
    19      dbms_output.put_line ('oh STR2 is NOT null');
    20    end if;
    21  end;
    22  /
    oh STR1 is NOT null
    oh STR2 is null
    PL/SQL procedure successfully completed.
    SQL> alter session set events '10932 trace name context forever, level 16384';
    Session altered.
    SQL> declare
      2    l_str1   char (10) := '';
      3    l_str2   char (10) := null;
      4  begin
      5  
      6    if l_str1 is null
      7    then
      8      dbms_output.put_line ('oh STR1 is null');
      9    elsif l_str1 is not null
    10    then
    11      dbms_output.put_line ('oh STR1 is NOT null');
    12    end if;
    13  
    14    if l_str2 is null
    15    then
    16      dbms_output.put_line ('oh STR2 is null');
    17    elsif l_str2 is not null
    18    then
    19      dbms_output.put_line ('oh STR2 is NOT null');
    20    end if;
    21  end;
    22  /
    oh STR1 is null
    oh STR2 is null
    PL/SQL procedure successfully completed.
    SQL> SY.

  • What is difference between Null String and Empty String ?

    Hi
    Just i have little confusion that the difference bet'n NULL String and Empty String ..
    Please clear my doubte.
    Thankx

    For the same reason I think it's okay to say "null
    String" and "empty String "as long as you know they
    really mean "null String reference" and "empty String
    object" respectively. Crap. It's only okay to say that as long as *the one you're talking to" knows what it really means. Whether you know it or not is absolutely irrelevant. And there is hardly any ambiguity about the effects that a statement like "assign an object to a reference" brings. "Null String" differs in that way.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Difference between null string and empty string??

    what is the major difference between null string and an empty string??
    I wrote the following simple program and I could see some different output.
    Other than that, any other differences that we should pay attention to???
    C:\>java TestCode
    Hello
    nullHello
    public class TestCode
         public static void main(String[] s)
         {     String s1 = "";
              String s2 = null;
              System.out.println(s1 + "Hello");
              System.out.println(s2 + "Hello");
    }

    The difference is that an empty String is just empty but a null String has no value (i.e. it is not instantiated) this has signifigance since all Strings are objects.

  • Varchar2, empty strings and NULL

    Hi all,
    When inserting an empty string into a column of type varchar2 - is a NULL value stored in the column by the database? I've seen conflicting reports, and I know that the SQL 1992 spec specifies that empty strings not be treated as a NULL value, but that Oracle has traditionally treated zero length strings stored in a varchar2 column as NULL.
    So, is there a way to store an empty string in a varchar2 column as an empty string and not a NULL value?
    TIA,
    Seth

    It can be even more complicated or annoying than NULL not equal to ASCII NULL.
    example:
    create table test_null
    (fld1 varchar2(10),
    fld2 varchar2(10),
    fld3 varchar2(20));
    insert into test_null values (chr(0),null, 'chr(0) and null');
    insert into test_null values (null, null, 'null and null');
    insert into test_null values ('', chr(0), ''''' and chr(0)');
    insert into test_null values ('', null, ''''' and null');
    select * from test_null;
    FLD1       FLD2       FLD3
                          chr(0) and null
                          null and null
                          '' and chr(0)
                          '' and null
      1  DECLARE
      2  BEGIN
      3   for c1 in (select fld1, fld2, fld3 from test_null) loop
      4      if c1.fld1 = c1.fld2 then
      5         dbms_output.put_line(c1.fld3||' Are equal'||
      6                '  Length fld1 = '||to_char(length(c1.fld1))||
      7                ' Length fld2 = '||to_char(length(c1.fld2)));
      8      else
      9         dbms_output.put_line(c1.fld3||' Are NOT equal'||
    10                '  Length fld1 = '||to_char(length(c1.fld1))||
    11                ' Length fld2 = '||to_char(length(c1.fld2)));
    12      end if;
    13      dbms_output.put_line(' ');
    14   end loop;
    15*  END;
    SQL> /
    chr(0) and null Are NOT equal  Length fld1 = 1 Length fld2 =
    null and null Are NOT equal  Length fld1 =  Length fld2 =
    '' and chr(0) Are NOT equal  Length fld1 =  Length fld2 = 1
    '' and null Are NOT equal  Length fld1 =  Length fld2 =
    PL/SQL procedure successfully completed.

  • Difference between String and final String

    Hi friends,
    This is Ramana. Can u suggest me in this Question
    What is the difference between String and final String? Means
    String str="hai";
    final String str="hai";
    Regards,
    Ramana.

    *******REPEAT POST***********
    We already answered your question why post in a different section?
    http://forum.java.sun.com/thread.jspa?threadID=5201549

  • Difference in a string and the text retrieved from JTextBox

    Hello,
    I am facing a peculiar problem. Please see the following code fragment:
    m.replaceAll(";\ngo;);
    where m is a matcher. This is working fine. But whenever I am doing
    m.replaceAll(myTextBox.getText());
    and placing ";\ngo;" in the text Field is not working as before. This is because that getText() returns a string in text form(doesnot take the newline into consideration). Any idea how to solve this?
    Regards,
    Saurav

    Here is the following code:
    File fin = new File(file);
    File fout = new File("C:\\Temp\\temp123.txt");
    FileInputStream fis = new FileInputStream(fin);
    FileOutputStream fos = new FileOutputStream(fout);
    BufferedReader in = new BufferedReader(new InputStreamReader(fis));
    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fos));
    Pattern p = Pattern.compile(find);
    Matcher m = p.matcher("");
    String aLine = null;
    while((aLine = in.readLine()) != null) {
    m.reset(aLine);
    String result = m.replaceAll(replace);
    out.write(result);
    out.newLine();
    in.close();
    out.close();
    What I intend to do is that the user will provide a fileName from the GUI and also the text to find and the text to repalce with. Both of them will be in a JTextBox. Now
    suppose I want to replace ";" in the line "Hello;" with ";\nHow are u?" so that the line looks like
    "Hello;
    How are u?"
    But what is happening is that the line looks like
    "Hello;\nHow are u?" after replacement.
    This happens because getText() doesnot considers that as a special character...
    I tried to harcode the replace string and it worked perfectly....
    Thats the problem.....I need the same behaviour with getText().
    Regards,
    Saurav

  • Input a string and assign to a variable in the console window

    i'm absolutely and completely new to java
    i need to be able to input a string and then assign it to a variable, entirely using the console window, basically i'm looking for the Java alternative to C++'s "cin"
    i've tried the System.in. method but nothing seems to work
    i know this should be simple, but i cant find it anywhere
    cheers

    i've tried the System.in. method That thing is not a method: it's an object, an intstantiation of the InputStream
    class. If you read the API documentation for that class you'll notice that it
    isn't much more sophisticated than C's file IO. You can wrap an
    object if this class in a more high level class (see InputStreamReader
    and BufferedReader).
    The latter allows you to read an entire line of characters. If you really want
    to go fancy you can wrap the first class in a Scanner which is only
    available in Java 1.5
    kind regards,
    Jos

  • Can I call a function from a dll in LabVIEW that returns:double*string and int.?

    I have a function from a dll that return a double* string and an integer. How can I call this function from LabVIEW? There is a possibility to work in LabVIEW with a double* string?

    pcbv wrote:
    > Hello all,<br><br>The header of the function is:
    >
    > "HRESULT WRAPIEnumerateDevices(WRAPI_NDIS_DEVICE **ppDeviceList, long *plItems);"
    >
    > where WRAPI_NDIS_DEVICE have this form:
    >
    > typedef struct WRAPI_NDIS_DEVICE<br>{<br>
    > WCHAR *pDeviceName;<br>
    > WCHAR *pDeviceDescription;<br><br>}
    > WRAPI_NDIS_DEVICE;<br><br>
    >
    > The function is from WRAPI.dll, used for communication with wireless card.
    > For my application I need to call in LabVIEW this function.
    Two difficulties I can see with this.
    First the application seems to allocate the array of references
    internally and return a pointer to that array. In that case there must
    be another function which then deallocates that array again.
    Then you would need to setup the function call to have a pointer to an
    int32 number for the deviceList parameter and another pointer to int32
    one for the plItems parameter.
    Then create another function in your DLL similar to this:
    HRESULT WRAPIEnumExtractDevice(WRAPI_NDIS_DEVICE *lpDeviceList, long i,
    CHAR lpszDeviceName, LONG lenDeviceName,
    CHAR lpszDeviceDesc, LONG lenDeviceDesc)
    if (!lpDeviceList)
    return ERROR_INV_PARAMETER;
    if (lpDeviceList[i].pDeviceName)
    WideCharToMultiByte(CP_ACP, 0,
    pDeviceList[i].pDeviceName, -1,
    lpszDeviceName, lenDeviceName,
    NULL, NULL);
    if (lpDeviceList[i].pDeviceName)
    WideCharToMultiByte(CP_ACP, 0,
    pDeviceList[i].pDeviceDescription, -1,
    lpszDeviceDesc, lenDeviceDesc,
    NULL, NULL);
    return NO_ERROR;
    Pass the int32 you got from the first parameter of the previous call as
    a simple int32 passed by value to this function (and make sure you don't
    call this function with a higher index than (plItems - 1) returned from
    the first function.
    Rolf Kalbermatter
    Rolf Kalbermatter
    CIT Engineering Netherlands
    a division of Test & Measurement Solutions

  • Strange problem in converting between XML to string and vice versa

    i have an application that needs to send an XML document
    over the wire. For this reason, I need to convert the
    doc into a String at the sending side and back to Doc
    at the receiving side. This document is stored in a "CLOB"
    column in a table in the database. I use XDK to retrieve
    this entire row (including the CLOB - hence this is an XML
    document which has a column that itself is an xml document in
    string format - this is just the clob read in by XDK).
    Thus the row looks like
    <ROWSET>
    <ROW>
    <col1> A <col1>
    <CLOB_COL> ..clob value of an xml doc..</CLOB_COL>
    </ROW>
    </ROWSET>
    When I convert this document into String and back, one of the "<"
    tags in the clob column document gets changed to "&lt;" and hence
    the parsing fails! I have used the latest label of the XDK build
    to get the latest parser jar but still i have the same problem.
    I am using the following routines for the conversion.
    /* for converting document to string */
    public static String convertToString(XMLDocument xml) throws
    IOException
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    xml.print(pw);
    String result = sw.toString();
    return result;
    /* for converting string to document */
    public static XMLDocument convertToXml(String xmlStr)
    throws
    IOException,SAXException
    ByteArrayInputStream inStream = new
    ByteArrayInputStream(xmlStr.getBytes());
    DOMParser parser = new DOMParser();
    parser.setPreserveWhitespace(false);
    parser.parse(inStream);
    return parser.getDocument();

    How do you get the XML document? Do you use XSU? You can use:
    String str = qry.getXMLString();
    to get the result XML document in String.
    XSU will escape all of the < and >. Or the the XML document in
    one of the column will make the result XML doc not well-formed.
    Not quite understand your problem. You can send me your test
    case.
    i have an application that needs to send an XML document
    over the wire. For this reason, I need to convert the
    doc into a String at the sending side and back to Doc
    at the receiving side. This document is stored in a "CLOB"
    column in a table in the database. I use XDK to retrieve
    this entire row (including the CLOB - hence this is an XML
    document which has a column that itself is an xml document in
    string format - this is just the clob read in by XDK).
    Thus the row looks like
    <ROWSET>
    <ROW>
    <col1> A <col1>
    <CLOB_COL> ..clob value of an xml doc..</CLOB_COL>
    </ROW>
    </ROWSET>
    When I convert this document into String and back, one of the "<"
    tags in the clob column document gets changed to "<" and hence
    the parsing fails! I have used the latest label of the XDK build
    to get the latest parser jar but still i have the same problem.
    I am using the following routines for the conversion.
    /* for converting document to string */
    public static String convertToString(XMLDocument xml) throws
    IOException
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    xml.print(pw);
    String result = sw.toString();
    return result;
    /* for converting string to document */
    public static XMLDocument convertToXml(String xmlStr)
    throws
    IOException,SAXException
    ByteArrayInputStream inStream = new
    ByteArrayInputStream(xmlStr.getBytes());
    DOMParser parser = new DOMParser();
    parser.setPreserveWhitespace(false);
    parser.parse(inStream);
    return parser.getDocument();

  • ByteArray to String and String to ByteArray  error at readUTF from datainpu

    hi everybody this is my first post I hope I can find the help I need I have been doing some research and couldnt find the solution thanks in advanced
    The Objective:
    im building a client server application with java and I need to send a response from the server to the client via Socket
    so the response is like this : <Signal : ByteArray> where Signal is a String so the client can Identify the Type of response
    and the ByteArray is an Array of bytes containing the Information I need
    The Problem:
    I have an Array of bytes containing the info to send and I need to pass this byte[] to a String add some String that let me Identify the data in the client side then remove the identifier in the client side and convert the resulting String back to an array of bytes this doesnt work
    The Code:
    Server Side (Creating the Byte Array):
    public byte[] createData(){
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    DataOutputStream dos = new DataOutputStream(baos);               
                    dos.writeUTF(requestedFile.getName());
                    dos.flush();
                    byte[] data = baos.toByteArray();
                    return data;
    }Server Side (Converting the byte[] to String and Add some Identifier)
    byte[] data= createData(); //Obtain the data  in a byte[]
    String response = new String(data);  //Convert the Data to String
    String Identifier= "14"; // to identify in the client side the data received this will be removed later
    response = Identifier+response;  // add the identifier to the String
    sendToClient( response.getBytes() );  //obtain bytes from the complete Response and send them to clientClient Side ( Receive the response that is a byte array containing the identifier plus the info <Identifier : info> )
                int index=response.indexOf(":")+1;  //find the index of the : so i can delete the identifier
                response=response.substring(index); // delete the identifier
                byte[] data = response.getBytes(); // obtains the bytes for the info ONLY cause the string no longer has identif
                receiveData ( data ); // send the data to be read by this method Client Side (Receive the Info sent from the server and read it)
                public void receiveData ( byte[] data ) {
                   ByteArrayInputStream bais = new ByteArrayInputStream ( data );
                   DataInputStream dis= new DataInputStream ( bais );
                   setTotalSize ( dis.readUTF( ) ); // here is the error  it catches an EndOfFileException without read the info
                }im tried sending other values like long and int and i was able to read them but the problem is with the Strings at the ReadUTF()
    Im tried to be the most clear as possible please help me this is driving me nuts
    and I would really appreciatte all your comments thanks

    lemaniak wrote:
    The Objective:
    im building a client server application with java and I need to send a response from the server to the client via Socket
    so the response is like this : <Signal : ByteArray> where Signal is a String so the client can Identify the Type of response
    and the ByteArray is an Array of bytes containing the Information I need
    The Problem:
    I have an Array of bytes containing the info to send and I need to pass this byte[] to a String add some String that let me Identify the data in the client side then remove the identifier in the client side and convert the resulting String back to an array of bytes this doesnt workFirst of all, well done: a nicely explained problem. I wish more people were as clear as you.
    Second: I'm no expert on this stuff, so I may well be wrong, but I did note the following:
    1. I can't see anywhere where you're putting out the ":" to separate your signal.
    2. You seem to be doing an awful lot of conversions from Strings to bytes and vice-versa, but only your filename is specified as a UTF-8 conversion. Could you not do something like:
    dos.writeUTF("14:" + requestedFile.getName());or indeed, more generically
    dos.writeUTF(signal + ":" + messageBody);from inside a createMessage() method.
    3. You haven't included the sendToClient() code, but your createData() looks suspiciously like what I would put in a method like that.
    From what I understand, you usually want mirror-images of your streams at your sending and receiving ends, so if your client is expecting an DataInputStream wrapping a ByteArrayInputStream to be read via readUTF(), your server better be sending a ByteArrayOutputStream wrapped in a DataOutputStream created, in its entirety, by writeUTF().
    But after your UTF conversion, you're adding your signal and then using String.getBytes(), which uses the default character set, not UTF.
    HIH (and hope I'm right :-))
    Winston

  • How to read a C structure with string and int with a java server using sock

    I ve made a C agent returning some information and I want to get them with my java server. I ve settled communication with connected socket but I m only able to read strings.
    I want to know how can I read strings and int with the same stream because they are sent at the same time:
    C pgm sent structure :
    char* chaine1;
    char* chaine2;
    int nb1;
    int nb2;
    I want to read this with my java stream I know readline methode to get the first two string but after two readline how should I do to get the two int values ?
    Any idea would be a good help...
    thanks.
    Nicolas (France)

    Does the server sent the ints in little endian or big endian format?
    The class java.io.DataInputStream (with the method readInt()) can be used to read ints as binary from the stream - see if you can use it.

Maybe you are looking for

  • My safari closed without warning.

    Safari closed without warning. Does anyone know what seems to be a problem? Here is the error code. Many thanks! Process:         Safari [32931] Path:            /Applications/Safari.app/Contents/MacOS/Safari Identifier:      com.apple.Safari Version

  • Plz explain the code

    REPORT zfi_vendor_ageing NO STANDARD PAGE HEADING LINE-COUNT 58 line-size 168 MESSAGE-ID zh_msg. D A T A B A S E T A B L E S D E C L A R A T I O N TABLES: lfa1, " Vendor Master (General) t001, " Company Codes rfpdo. I N T E R N A L T A B L E S D E C

  • How to Get last page number in report 10g

    I want to get last page number in report but Current page number found from srw.get_page_num(n) but i want to get last page number for conditional formating like this srw.get_page_num(current_page)=last_page pls help me how can get last page number;

  • Which data base tables contain SCM customer code

    Friends, I am writing an user exit for VA01/VA02/VA3/VA32. I am getting the customer number from VBAK-KUNNR when I execute any of the above transactions. According to functional sepecification, we can find SCM code in the data base table ADRC. (we ca

  • Workflow starts then cancel, where can I see the error and why it's canceled?

    Hi, I have a workflow for a document library that starts when a new document is created.  i click on the workflow status at the document library list, and it shows  Internal Status: Canceled     and I never got the email that the workflow supposed to