How to convert string input streams

Can someone tell me how to convert string input streams...

There are multiple ways. I will list down few of them.

With the help of the old solution and standard java.

publicstaticString fromStream(InputStream in)throwsIOException

{

   BufferedReader reader =newBufferedReader(newInputStreamReader(in));

   StringBuilder out =newStringBuilder();

   String line;

   while((line = reader.readLine()) !=null) {

       out.append(line);

   }

   returnout.toString();

}

returnsb.toString();

If you use Google-Collections/guava-

InputStream stream = ...

String content = CharStreams.toString(newInputStreamReader(stream, Charsets.UTF_8));

Closeables.closeQuietly(stream);

If you use the common Apache library... then it is worthwhile.

StringWriter writer =newStringWriter();

IOUtils.copy(inputStream, writer, encoding);

String theString = writer.toString();

Quick way but only work during deserialization.

String result = (String)newObjectInputStream( inputStream ).readObject();

Note: ObjectInputStream is on deserialization and the flow of data must respect the Protocol of serialization to work, which may not always true in all cases.

Ultimately, the most effective solution and only in two lines using java class Scanner.

Tricky is to remember the \A regex that matches the beginning of the entry. It actually indicates Scanner to mark all of the flow, from start to beginning next (illogical).

publicstaticString convertToString(InputStream in) {

   java.util.Scanner s =newjava.util.Scanner(in).useDelimiter("\\A"); 

       

   returns.hasNext() ? s.next() :"";

}

Read more: http://www.techartifact.com/blogs/2013/11/how-to-readconvert-an-inputstream-to-a-string.html#ixzz2lvy5muix

Tags: Java

Similar Questions

  • How to convert string to number in TS?

    Hello

    Anyone know how to convert string to number in TS?

    I couldn't find the Num() function.

    Thank you

    Val()

  • OpenScript/Bank of data/how to convert string to int

    Hello

    As far as I know, the values read from the database is a type of Sting. Now, I want to convert a character number stored in the database of type int.
    For example, in "Test.csv" I stored the '9' in the column 'Number' character, then I use the following code to read the character and convert an int in one:
    getDatabank("Test").getNextDatabankRecord ();
    String Testnumber = "{{db." Test.Numberr}} '; Info (Testnumber);
    int number = Integer.parseInt (Testnumber);

    However, it seems this does not work, because he says "basic unexpected failure caused by: NumberFormatException occurred." For the input string: «{{db.» Test.Numberr}}.
    I think that this error can be caused by the conversion of character '9' int 9.
    Can someone tell me how to convert a character to be read from database in an int?

    Thank you very much!

    Kind regards
    Angyoung

    Hello

    You can use the same approach. Use eval()

    getDatabank("Test").getNextDatabankRecord();
    String Testnumber =eval("{{db.Test.Numberr}}") ;
    info(Testnumber);
    int number = Integer.parseInt(Testnumber);
    

    Kind regards
    Dembélé M

  • How to convert String to Date

    hell there everyone,

    I have a question which is:

    How to convert a string that we get by reading an XML in the instance of date value type?

    So there is a XML that modifiedDate as an attribute on a node of the XML and how I put this value in an instance variable date?

    the timeformat in the XML file is: mm/dd/yyyy hh: mm: = > 31/12/2010 23:57:46

    I chose this time format because I want to use the method . parse() which always causes an error, but that's another topic...,.

    hope I was clear on the issue,

    Thanks in advance for the help.

    First of all, you should watch the Date object constructor to find out how to specify different parameters.

    public void Date (yearOrTimevalue:Object, month:number, date:number = 1, hour:number = 0, minute:number = 0, second:number = 0, millisecond:number = 0)

    Then you need to determne how to break the string by using the String.Split method.  The first split() should be the space between the date and time, the second for the slashes in the date and the third for the colon in time.

    Then you come to take each of these paintings of substrings and feed them in the constructor as the Number() values.

    If you remain unsure how to do this, look at the different terms that I have identified in the help documents and you will find them all explained with examples.

  • How to convert string to datetime in the transformation of the Ombudsman

    Hello

    I am getting error below when inserting the data in the database using the database.

    Exception occurred when the link was invoked. Exception occurred during invocation of the JCA binding: "JCA binding run reference"insert"operations have to: DBWriteInteractionSpec Execute Failed Exception." insertion failed. The descriptor name: [InsertPayload.XxohInsertStgTable]. Created by Exception [EclipseLink-3001] (Eclipse - 2.3.1.v20111018 persistence Services - r10243): org.eclipse.persistence.exceptions.ConversionException Description of the Exception: object [2015-09-14 15:19:51], class [class java.lang.String], couldn't be converted [class java.sql.Timestamp]. Inner exception: LINK. JCA-11636 couldn't convert Timestamp Exception. Cannot convert a string value in the xml file to a java.sql.Timestamp. Although the databases accept strings representing the timestamps in a variety of formats, the adapter only accepts strings that represent xml ISO dateTime format. The input value must be in the format XS: DateTime to iso 8601, i.e. YYYY-MM - DDTHH:MM:SS.sss - 07:00. Please see the logs

    In the transformation of the mediator, the Source element is a string

    < xs: element name = "CREATED_DATE" type = "xs: String" > < / xs: element >

    Target is of type dateTime

    < xs: element name = "Creation_Date" type = "xs: DateTime" minOccurs = "0" nillable = "true" / >

    To avoid the above error, I used < xsl: value-of select ='xp20:format - dateTime (/CREATED_DATE, "[Y0001]-[M01]-[D01] [H01]: [m01]: [s01]")'/ > in the transformation, but its does not work. The value is blank display after processing.

    Please suggest me how to solve this problem.

    Thank you

    Sunita

    Unfortunately, the format required by the dateTime format is YYYY-MM - DDTHH:MM:SS.sss

    You can use the substring, and on the entry's concat function to create YYYY-MM - DDTHH:MM:SS.sss

    See formatting string to date in BPEL

  • How to convert user input on the page in capital letters?

    For the experienced:

    I use JDeveloper 10.1.3.4 to develop my application.

    The application has an Oracle database table named USERS. A column named USER_ID, must be uppercase when recording in the table.

    I dragged the create action of the corresponding VO named users to a page to create a commandButton control. When you click this button, the user is navigated to a page "Create an account" to fill in all the fields and save the entry in the USERS table.

    On the page "Create a new account", users of VO is slid to the page as a form of the ADF. The action of validation is dragged to the page as the "Save" button. User input is stored in the USERS table as a new row when the user clicks on the button "Save". But what the user types in the user name field can contain lower-case characters. This entry should be converted to uppercase before saved in the USERS table. I tried to convert the setter in the VO or EO, such as:
        public void setUserid(String value) {
            value.toUpperCase();   //I added this line.
            setAttributeInternal(USERID, value);
        }
    But this has no effect. Then I tried to make a change similar to the Get accessor method, such as:
        public String getUserid() {
            //return (String)getAttributeInternal(USERID);  // this is original code.
            //What I added:
           String uppperUserid = (String)getAttributeInternal(USERID);
            return upperUserid.toUpperCase();
        }
    But I get an error: {color: red} Houston-27019: getting the method for the attribute 'Userid' in users could not be resolved. {color}

    Can anyone help? Thank you very much!

    Newman

    check this one

    ADF faces: how to 'auto UpperCase' on InputText?

    Info. All custom converter...

    Re: all lowercase?

  • How to convert string data from the serial port to double?

    Hello!

    I am very new in LabView and attempt to read data from an OHAUS pioneer pa-313 electronic scale via RS232 serial port. I use the VISA. I can read the data and see it as a string to the screen, but when I try to convert it to a double, it is just the integer and decimal numbers have disappeared. Here's the question: what can be the problem? How can I get the decimals as well?

    What is your normal decimal point?. or?

  • How to convert string to [AVLayer]

    Hello world.

    I have this code:

    var myComp = "app.project.activeItem";
    var text = '.layer("4").effect("Unsharp Mask")("Amount")';
    var myLayer = myComp+text;
    
    alert(myLayer.value)               // doesn`t work
    

    How can I convert to string (myLayer) [AVLayer] object to get its property?

    This should help you closer:

    myComp = "app.project.activeItem"; var

    var myText = ".layer("4").effect (" unsharp mask ")("Amount").value";

    var myVal = eval (myComp + myText);

    Alert (myVal);

    Dan

  • How to convert string to number

    Hi everoyne, I need to make a program simple calculation of the GPA in 5 classes. Where A, B, C, D, F are the entries for each other...

    Here's what I've done so far.

    But it seems that it is not recognized when I assigns numeric values to each letter. So I would appreciate any help. I tested for the release of "GP" and input A (4) = CT. The answer for GP should be 4 x 3 = 12. But I get a number beyond that.

    I'm relatively new to Labview so sorry if this is a stupid question.

    -Daniel

    I would like to make a table of the clusters.  Each element of the array corresponds to a single course.  Inside of the bunch, I would have a string for the name of the course, an enum for the grade and a digital for the number of credit hours.  Use an enum for the grade, so you can make sure that the user space only in the values that you no longer the enum is actually a number.  No actual conversion.  Then you just use a loop FOR (autoindexing) including some shift registers to keep your totals, then divide the totals of the year by the credit hours.

  • reclassification how to convert string into array

    Hi all


    I do the code

    CREATE OR REPLACE
    TYPE 'SAMPLE '. "" SAMPLETABLETYPEVAR ".

    PLS-00311:

    but I got to l_data error how can I solve

    /***************************************************************/
    declare
    l_str DEFAULT LONG ' pankaj/dukare /';
    l_n NUMBER;
    SAMPLETABLETYPEVAR l_data: = SAMPLETABLETYPEVAR ();

    BEGIN

    LOOP
    l_n: = INSTR (l_str, "/");
    WHEN the OUTPUT (NVL (l_n, 0) = 0);
    l_data. EXTEND;
    l_data (l_data. (COUNTY): = LTRIM (RTRIM (SUBSTR (l_str, 1, l_n - 1)));
    l_str: = SUBSTR (l_str, l_n + 1);
    END LOOP;

    L_data RETURN;

    END;

    /********************************************************/

    Published by: user9524857 on July 1st, 2009 23:36

    using your code:

    SQL> select *
      2    from table (sample_split_string ('this is a long string', ' ')
      3  /
    
    COLUMN_VALUE
    ---------------------------------------------------------------------
    this
    is
    a
    long
    string
    
  • How to convert string to numeric number

    I have a list of dollar amounts which amounted to on a cfloop and the query:

    < cfset FileCount = 0 >
    < cfset FileDollar = 0 >

    < cfloop query = "TxtQuery" >
    < cfset FileDollar = #FileDollar # + "#Payment_Amt #" >
    < / cfloop >

    Here's the data (entry in the first column, payment_amt, combined with the title of the FileDollar column):

    Payment_amt (Text) FileDollar
    14645791.820 14645791.82
    5302608003.600 5317253795.42
    405642.240 5317659437.66
    11354914264.600 6672573702.3
    1532528.280 16674106230.5
    1532528.280 16675638758.8
    1532528.280 16677171287.1
    1532528.280 16678703815.4
    16470800280.000 33149504095.4

    It seems that once it hits the entrance of 11354914264.600 payment_amt, the FileDollar two decimal one.
    Is it possible to convert the numeric text field before it gets totaled?

    Thanks for the help. I eliminated the cfloop to add fields payment_amt and replaced by a Q Q (as you recommended) using a cast statement.


    SELECT SUM (CAST (Payment_amt AS decimal)) AS TOTAL_AMT
    to TxtQuery

    The TOTAL_AMT has correct total field now and is in decimal format.

    Thanks again for your help!

  • How to convert a string to a number?

    How to convert a numeric string to a number of TestStand?

    Use Val().

    Example Val (Locals.myString)

  • How to convert a single byte String?

    Purpose:

    Show a result byte on the BB 9900 screen.

    Question:

    How to convert a single byte String?

    Part of the code:

    byte value = con.cpu_config.elementAt (i)

    stop here

    String valuestring = new String (value);

    _rtf. SetText (valueString);

    If you know how to fix it, please share your idea.

    Thank you for your attention,

    String valuestring = new String (new byte [] {value}};)

    _data. Append (valueString);

    _rtf. SetText (_data.toSrting ());

    Solve it.

  • How to convert int to String

    How to convert int to String. I get the error 'cannot convert integer to int.

    Dim str As String = "abc";

    int NB = Integer.valueOf (str);

    Use Integar.parseInt (). But make sure your str contains the integer value (like str = '123') otherwise you will get the exception.

    String str = "123"; int num = Integer.parseInt(str);
    

    Concerning

    Bika

  • How to use the input as VC Atttibutes string?

    Hello everyone,

    I'm discovering VCO. And I need your help.

    How can I use input string as a VC attributes at the end? Then, use this return as input for another workflow.

    The workflow that I am putting in place is:

    1-name of the VM to search in vCenter: input String (example: 'TOTO')

    2-search 'TOTO' virtual machine in the vCenter, if found then

    3 - use this result to clone a VM TOTO

    For stage 1 and 2, it works, I can search based on the input of the chain and get a result.

    But for step 3, I use another workflow 'Create virtual machine' and we must put a VC:VirtualMachine.

    And it does not work because the type I get to step 2 is not compatible with the entry for step 3.

    Progressive input signal 3 waiting for VC:VirtualMachine

    And the output of step 2 is the table / VC:VirtualMachine.

    I tried to change the input type for step 3 as table / VC:VirtualMachine.

    Whenever I got the error message:

    TypeError: Cannot find the cloneVM_Task function in the DynamicWrapper (Instance) subject: [VcVirtualMachine]-[class com.vmware.vmo.plugin.vi4.model.VimVirtualMachine] - VALUE: VirtualMachine, vm-907 > "LYNC01." (Name of the dynamic Script Module: cloneVM_1 #13)

    I don't want the workflow using the VC search plugin, but I need to set the input parameter.

    If someone has an idea.

    Thank you all.

    Keep the entry for step 3 as VcVirtualmachine (only one), but add an extra step:

    2.5: get the first (or last, should not question: I hope that you will find only one :-)) table.)

    You can do it in Javascript, using the method. pop() from an array.

    var sourceVM = foundVMs.pop () / / sourceVM is of type VcVirtualMachine, foundVMs table/VcVirtualMachine

    See you soon,.

    Joerg

Maybe you are looking for

  • App messages in Sierra

    Hello The messages continued in the Sierra with a new version. (version 10) He loses a part of the functionality last iChat that the application was initially based on. This means that it isn't is no longer video and Audio Chats in the application. T

  • How to connect to _old_ Sync one and only device with the new operating system

    Howdy, I own a "device" (laptop) and have used Sync to store my bookmarks and passwords online as a way of not having to worry about backups for these courses of frequent relocations due to the OS-experiences etc. Yesterday, my HARD drive crashed har

  • iCloud, sharing photos - Photo Editing Workflow

    I have all my photos on my desktop Mac saved to iCloud and Time Machine. I have shared libraries of selected images. I need to edit these images on an iPad. This IS the workflow? (1) discovered the Photo shared on the iPad. 2) record on the iPad. 3 c

  • Frustrating upgrades

    Whenever my computer automatically updated my settings are screwed up.  This time, I lost my taskbar and cannot make it reappear.  I tried to adjust the parameters of the task bar, but nothing happens.  Even looking at Web pages there is no taskbar,

  • Why Smartphones blackBerry email no new icon after I put up the email?

    Why no new email icon after I set up e-mail? I have 4 email accounts, but only 3 of them have icons.  If I change to a different theme (background on the screen), all e-mail accounts icon appears.  I currently use the default theme that is missing em