Reading & writing to file using ArrayList String incorrectly (2)

I have been able to store two strings (M44110|T33010, M92603|T10350) using ArrayList<String>, which represent the result of some patient tests. Nevertheless, the order of these results have been stored correctly.
E.g. currently stored in file Snomed-Codes as -
[M44110|T33010, M92603|T10350][M44110|T33010, M92603|T10350]
Should be stored and printed out as -
M44110|T33010
M92603|T10350
Below is the detail of the source code of this program:
import java.io.*;
import java.io.IOException;
import java.lang.String;
import java.util.regex.*;
import java.util.ArrayList;
public class FindSnomedCode {
    static ArrayList<String> allRecords = new ArrayList<String>();
    static public ArrayList<String> getContents(File existingFile) {
        StringBuffer contents = new StringBuffer();
        BufferedReader input = null;
        int line_number = 0;
        int number_of_records = 0;
        String snomedCodes = null;
        ArrayList<String> complete_records = new ArrayList<String>();
        try {
            input = new BufferedReader( new FileReader(existingFile) );
            String current_line = null;
            while (( current_line = input.readLine()) != null) {
                // Create a pattern to match for the "\"
                Pattern p = Pattern.compile("\\\\");
                // Create a matcher with an input string
                Matcher m = p.matcher(current_line);
                boolean beginning_of_record = m.find();
                if (beginning_of_record) {
                    line_number = 0;
                    number_of_records++;
                } else {
                    line_number++;
                if ( (line_number == 2) && (current_line.length() != 0) ) {
                    snomedCodes = current_line;
                    System.out.println(snomedCodes);
                    complete_records.add(current_line);
        catch (FileNotFoundException ex) {
            ex.printStackTrace();
        catch (IOException ex){
            ex.printStackTrace();
        finally {
            try {
                if (input!= null) {
                    input.close();
            catch (IOException ex) {
                ex.printStackTrace();
        return complete_records;
    static public void setContents(File reformatFile, ArrayList<String> snomedCodes)
                                 throws FileNotFoundException, IOException {
       Writer output = null;
        try {
            output = new BufferedWriter( new FileWriter(reformatFile) );
              for (String index : snomedCodes) {
                  output.write( snomedCodes.toString() );
        finally {
            if (output != null) output.close();
    static public void printContents(File existingFile) {
        StringBuffer contents = new StringBuffer();
        BufferedReader input = null;
        int line_number = 0;
        int number_of_records = 0;
        String snomedCodes = null;
        try {
            input = new BufferedReader( new FileReader(existingFile) );
            String current_line = null;
            while (( current_line = input.readLine()) != null)
                System.out.println(current_line);
        catch (FileNotFoundException ex) {
            ex.printStackTrace();
        catch (IOException ex){
            ex.printStackTrace();
        finally {
            try {
                if (input!= null) {
                    input.close();
            catch (IOException ex) {
                ex.printStackTrace();
    public static void main (String args[]) throws IOException {
        File currentFile = new File("D:\\dummy_patient.txt");
        allRecords = getContents(currentFile);
        File snomedFile = new File( "D:\\Snomed-Codes.txt");
        setContents(snomedFile, allRecords);
        printContents(snomedFile);
}There are 4 patient records in the dummy_patient.txt file but only the 1st (M44110|T33010) & 3rd (M92603|T10350) records have results in them. The 2nd & 4th records have blank results.
Lastly, could someone explain to me the difference between java.util.List & java.util.ArrayList?
I am running Netbeans 5.0, jdk1.5.0_09 on Windows XP, SP2.
Many thanks,
Netbeans Fan.

while (snomedCodes.iterator().hasNext())
  output.write( snomedCodes.toString() );
}Here you have some kind of a list or something (I couldn't stand to read all that unformatted code but I suppose you can find out). It has an iterator which gives you the entries of the list one at a time. You keep asking if it has more entries -- which it does -- but you never get those entries by calling the next() method, so it always has all the entries still available.
And your code inside the loop is independent of the iterator, so it's rather pointless to iterate over the entries and output exactly the same data for each entry. Even if you were iterating correctly.

Similar Messages

  • Reading & writing to file using ArrayList String incorrectly

    Hi Java Experts,
    I am running out of ideas on why my findSnomedCodes.java program is filling up the output file (Snomed-Codes.txt) with the
    same information ([M44110|T33010, , M92603|T10350, ]) continuously. This program goes through a dummy patient result file
    and pickup the 3rd line of each record and insert it into an ArrayList of String before writing it into a Snomed-Codes.txt
    file. A followed up method prints out everything from Snomed-Codes.txt.
    Below is the source code of findSnomedCodes.java program:
    import java.io.*;
    import java.io.IOException;
    import java.lang.String;
    import java.lang.Character;
    import java.util.regex.*;
    import java.util.ArrayList;
    import java.util.List;
    public class FindSnomedCode {
    static List<String> complete_records = new ArrayList<String>();
    static public void getContents(File existingFile) {
    StringBuffer contents = new StringBuffer();
    BufferedReader input = null;
    int line_number = 0;
    int number_of_records = 0;
    String snomedCodes = null;
    try {
    input = new BufferedReader( new FileReader(existingFile) );
    String current_line = null;
    while (( current_line = input.readLine()) != null) {
    // Create a pattern to match for the "\"
    Pattern p = Pattern.compile("\\\\");
    // Create a matcher with an input string
    Matcher m = p.matcher(current_line);
    boolean beginning_of_record = m.find();
    if (beginning_of_record) {
    line_number = 0;
    number_of_records++;
    } else {
    line_number++;
    if (line_number == 2) {
    snomedCodes = current_line;
    System.out.println(snomedCodes);
    complete_records.add(current_line);
    catch (FileNotFoundException ex) {
    ex.printStackTrace();
    catch (IOException ex){
    ex.printStackTrace();
    finally {
    try {
    if (input!= null) {
    input.close();
    catch (IOException ex) {
    ex.printStackTrace();
    static public void setContents(File reformatFile, List snomedCodes)
    throws FileNotFoundException, IOException {
    Writer output = null;
    try {
    output = new BufferedWriter( new FileWriter(reformatFile) );
    while (snomedCodes.iterator().hasNext())
    output.write( snomedCodes.toString() );
    finally {
    if (output != null) output.close();
    static public void printContents(File existingFile) {
    //...checks on existingFile are elided
    StringBuffer contents = new StringBuffer();
    BufferedReader input = null;
    int line_number = 0;
    int number_of_records = 0;
    long total_number_of_lines = 0;
    String snomedCodes = null;
    try {
    input = new BufferedReader( new FileReader(existingFile) );
    String current_line = null;
    while (( current_line = input.readLine()) != null)
    System.out.println(current_line);
    catch (FileNotFoundException ex) {
    ex.printStackTrace();
    catch (IOException ex){
    ex.printStackTrace();
    finally {
    try {
    if (input!= null) {
    input.close();
    catch (IOException ex) {
    ex.printStackTrace();
    public static void main (String args[]) throws IOException {
    File currentFile = new File("D:\\AP Data Conversion\\1988\\dummy_test_records.txt");
    getContents(currentFile);
    File snomedFile = new File( "D:\\AP Data Conversion\\1988\\Snomed-Codes.txt");
    setContents(snomedFile, complete_records);
    printContents(snomedFile);
    The output from Netbeans/Java is as follows:
    M44110|T33010
    M92603|T10350
    Exception in thread "main" java.io.IOException: There is not enough space on the disk
    at java.io.FileOutputStream.writeBytes(Native Method)
    at java.io.FileOutputStream.write(FileOutputStream.java:260)
    at sun.nio.cs.StreamEncoder$CharsetSE.writeBytes(StreamEncoder.java:336)
    at sun.nio.cs.StreamEncoder$CharsetSE.implClose(StreamEncoder.java:427)
    at sun.nio.cs.StreamEncoder.close(StreamEncoder.java:160)
    at java.io.OutputStreamWriter.close(OutputStreamWriter.java:222)
    at java.io.BufferedWriter.close(BufferedWriter.java:250)
    at FindSnomedCode.setContents(FindSnomedCode.java:90)
    at
    FindSnomedCode.main(FindSnomedCode.java:134)---------------------------------------------------------------------------------
    The content of Snomed-Codes.txt file is filled with continuous lines of [M44110|T33010, , M92603|T10350, ] as follows:
    [M44110|T33010, , M92603|T10350, ][M44110|T33010, , M92603|T10350, ][M44110|T33010, , M92603|T10350, ][M44110|T33010, ,
    M92603|T10350, ][M44110|T33010, , M92603|T10350, ][M44110|T33010, , M92603|T10350, ][M44110|T33010, , M92603|T10350,
    ][M44110|T33010, , M92603|T10350, ][M44110|T33010, , M92603|T10350, ][M44110|T33010, , M92603|T10350, ][M44110|T33010, ,
    M92603|T10350, ][M44110|T33010, , M92603|T10350, ][M44110|T33010, , M92603|T10350, ][M44110|T33010, , M92603|T10350,
    I must have done something wrong with the ArrayList.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    while (snomedCodes.iterator().hasNext())
      output.write( snomedCodes.toString() );
    }Here you have some kind of a list or something (I couldn't stand to read all that unformatted code but I suppose you can find out). It has an iterator which gives you the entries of the list one at a time. You keep asking if it has more entries -- which it does -- but you never get those entries by calling the next() method, so it always has all the entries still available.
    And your code inside the loop is independent of the iterator, so it's rather pointless to iterate over the entries and output exactly the same data for each entry. Even if you were iterating correctly.

  • Reading/Writing .xlsx files using Webdynpro for Java

    Dear All
    I have a requirement to read/write excel files in .xlsx format. I am good in doing it with .xls format using jxl.jar. The jxl.jar doesn't support .xlsx format. Kindly help me in understanding how do I need to proceed on reading/writing .xlsx files using Webdynpro for Java.
    Thanks and Regards
    Ramamoorthy D

    i am using jdk 1.6.22 and IBM WebSphere
    when i use poi-3.6-20091214.jar and poi-ooxml-3.6-20091214.jar  to read .xlsx file. but i am getting following errors
    The project was not built since its classpath is incomplete. Cannot find the class
    file for java.lang.Iterable. Fix the classpath then try rebuilding this project.
    This compilation unit indirectly references the missing type java.lang.Iterable
    (typically some required class file is referencing a type outside the classpath)
    how can i resolve it
    here is the code that i have used
    public class HomeAction extends DispatchAction {
         public ActionForward addpage(
                             ActionMapping mapping,
                             ActionForm form,
                             HttpServletRequest request,
                             HttpServletResponse response)
                             throws Exception {     
                             String name = "C:/Documents and Settings/bharath/Desktop/Book1.xlsx";
               FileInputStream fis = null;
               try {
                   Object workbook = null;
                    fis = new FileInputStream(name);
                    XSSFWorkbook wb = new XSSFWorkbook(fis);
                    XSSFSheet sheet = (XSSFSheet) wb.getSheetAt(0);
                    Iterator rows = sheet.rowIterator();
                    int number=sheet.getLastRowNum();
                    System.out.println(" number of rows"+ number);
                    while (rows.hasNext())
                        XSSFRow row = ((XSSFRow) rows.next());
                        Iterator cells = row.cellIterator();
                        while(cells.hasNext())
                    XSSFCell cell = (XSSFCell) cells.next();
                    String Value=cell.getStringCellValue();
                    System.out.println(Value);
               } catch (IOException e) {
                    e.printStackTrace();
               } finally {
                    if (fis != null) {
                         fis.close();
                return mapping.findForward("returnjsp");

  • Reading/writing PDF files using JAVA

    how to read/write a PDF file using java,
    while i read a pdf file using BUfferedReader class it gives a list of char. which is not readable.
    how to convert those files to readable format.?
    is there any special class for doin that.?
    plz explain..?

    is there any special class for doin that.?Yes, I'm sure Google knows a few libraries that ca do that.

  • Read an avi file using "Read from binary file" vi

    My question is how to read an avi file using "Read from binary file" vi .
    My objective is to create a series of small avi files by using IMAQ AVI write frame with mpeg-4 codec of 2 second long (so 40 frames in each file with 20 fps ) and then send them one by one so as to create a stream of video. The image are grabbed from USB camera. If I read those frames using IMAQ AVI read frame then compression advantage would be lost so I want to read the whole file itself.
    I read the avi file using "Read from binary file" with unsigned 8 bit data format and then sent to remote end and save it and then display it, however it didnt work. I later found that if I read an image file using "Read from binary file" with unsigned 8 bit data format and save it in local computer itself , the format would be changed and it would be unrecognizable. Am I doing wrong by reading the file in unsined 8 bit integer format or should I have used any other data types.
    I am using Labview 8.5 and Labview vision development module and vision acquisition module 8.5
    Your help would be highly appreciated.
    Thank you.
    Solved!
    Go to Solution.
    Attachments:
    read avi file in other data format.JPG ‏26 KB

    Hello,
    Check out the (full) help message for "write to binary file"
    The "prepend array or string size" input defaults to true, so in your example the data written to the file will have array size information added at the beginning and your output file will be (four bytes) longer than your input file. Wire a False constant to "prepend array or string size" to prevent this happening.
    Rod.
    Message Edited by Rod on 10-14-2008 02:43 PM

  • How to read a text file using Java

    Guys,
    Good day!
    Please help me how to read a text file using Java and create/convert that text file into XML.
    Thanks and God Bless.
    Regards,
    I-Talk

         public void fileRead(){
                 File aFile =new File("myFile.txt");
             BufferedReader input = null;
             try {
               input = new BufferedReader( new FileReader(aFile) );
               String line = null;
               while (( line = input.readLine()) != null){
             catch (FileNotFoundException ex) {
               ex.printStackTrace();
             catch (IOException ex){
               ex.printStackTrace();
         }This code is to read a text file. But there is no such thing that will convert your text file to xml file. You have to have a defined XML format. Then you can read your data from text files and insert them inside your xml text. Or you may like to read xml tags from text files and insert your own data. The file format of .txt and .xml is far too different.
    cheers
    Mohammed Jubaer Arif.

  • "encoding = UTF-8" missing while writing XML file using file Adapter

    Hi,
    We are facing an unique problem writing xml file using file adapter. The file is coming without the encoding part in the header of xml. An excerpt of the file that is getting generated:
    <?xml version="1.0" ?>
    <customerSet>
    <user>
    <externalID>51017</externalID>
    <userInfo>
    <employeeID>51017</employeeID>
    <employeeType>Contractor</employeeType>
    <userName/>
    <firstName>Gail</firstName>
    <lastName>Mikasa</lastName>
    <email>[email protected]</email>
    <costCenter>8506</costCenter>
    <departmentCode/>
    <departmentName>1200 Corp IT Exec 8506</departmentName>
    <businessUnit>1200</businessUnit>
    <jobTitle>HR Analyst 4</jobTitle>
    <managerID>49541</managerID>
    <division>290</division>
    <companyName>HQ-Milpitas, US</companyName>
    <workphone>
    <number/>
    </workphone>
    <mobilePhone>
    <number/>
    </customerSet>
    </user>
    So if you see the header the "encoding=UTF-8" is missing after "version-1.0".
    Do we need to configure any properties in File Adapter?? Or is it the standard way of rendering by the adapter.
    Please advice.
    Thanks in advance!!!

    System.out.println(nodeList.item(0).getFirstChild().getNodeValue());

  • Read a excel file using swings

    Does anyone know about reading an excel file using swings?
    Right now, I am using com.f1j.ss.*. But looking for more examples like reading and writing a excel file.
    Please suggest me with some good examples?

    1- Swing allows you to design a graphical user interface (to display data from a db or excel file for example)
    2- [Here |http://www.rgagnon.com/javadetails/java-0516.html] several ways to read/write excel.

  • Read an excel file using JSP in MII 12.1

    Hi,
    I want to read an excel file using jsp page. I dont want to use the UDS or ODBC for connecting to excel.
    I am trying to use org.apache.poi to read the excel file in jsp page.
    While running, its showing a compilation error "package org.apache.poi.hssf.usermodel does not exist"
    I have the jar files for it, where do we need to upload it so that jsp page works.
    Thanks a lot
    Regards,
    Neha Maheshwari

    The user doesn't want to save the excel file in server.
    I want to upload file and save its contents in database.
    I have the code to read and save excel data in database but not able to get the location to deploy the jar file.
    In general, if we are creating a jsp page in MII workbench which is using some jar file.
    Whats the location to upload this jar file so that the jsp page works correctly?

  • How to read two text files using the Read from spreadsheet.vi and then plot it

    I need to read two text files using the read from spreadsheet function and then plot these files over time.
    The file with the .res extention is the RMS values (dt and df) and the second file contains the amplitude of a frequency spectrum.
    I really appreciate any help..thanks
    Attachments:
    RMS.txt ‏1 KB
    FREQUENCY.txt ‏1 KB

    From NI Example Finder:
    Write to Text File.vi
    Read from Text File.vi
    Jean-Marc
    LV2009 and LV2013
    Free PDF Report with iTextSharp

  • Exception thrown while reading an XML file using Properties

    Exception thrown while reading an XML file using Properties.
    Exception in thread "main" java.util.InvalidPropertiesFormatException: org.xml.sax.SAXParseException:
    The processing instruction target matching "[xX][mM][lL]" is not allowed.
    at java.util.XMLUtils.load(Unknown Source)
    <?xml version="1.0"?>
    <Config>
         <Database>
              <Product>FX.O</Product>
              <URL>jdbc:oracle:thin:@0.0.0.0:ABC</URL>
         </Database>
    </Config>Am I missing anything?

    Thanks a lot for all yr help.I have got the basics of
    the DTD
    However,when I say thus
    <!DOCTYPE Config SYSTEM "c:/PartyConfig">
    ?xml version="1.0"?>
    <Config>
         <Database>
              <Product>FX</Product>
              <URL>jdbc:oracle:thin:@0.0.0.0:ABC</URL>
         </Database>
    </Config>I get the error
    Invalid system identifier: file:///c:/ParyConfig.dtd
    Please advise?for goodness sake, how many times do I have to tell you that you can't just expect the Properties class to accept arbitrary XML in any format? it reads XML in the format I linked to, and nothing else. Properties is not a general purpose XML binding. you can't do what you're trying to do with it. read this and in particular pay attention to the following
    The XML document must have the following DOCTYPE declaration:
    <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
    Furthermore, the document must satisfy the properties DTD described above.
    you are not reading my answers properly, are you? kindly do so

  • Where can I find an example of a vi which reads a xml file using the Labview schema (LVXMLSchema.xsd)?

    Where can I find an example of a vi which reads a xml file using the Labview schema (LVXMLSchema.xsd)?
    �Unflatten From XML� is of little use in parsing because it requires the data type. So it seems that the user has to parse each data value, and then �Unflatten From XML� can help a little.
    I would like to see NI provide a VI for parsing it�s own schema.

    LabVIEW's XML functions are another way of saving data from controls and indicators that is in a more standardized format. If you look at the Unflatten From XML shipping example, it shows taking the data that you would normally send to a Digital Wveform Graph and converting it to XML instead. This data is then unflattend from XML and wired to the graph. Since you know what you wrote to the file, this is an easy thing to do. If what you are looking for is a way to look at any data in any LabVIEW XML file, then you are right, there is not a VI for that. However, I do not believe that that was the intention of the XML functions in the first place.
    By wiriting data in XML, this allows other applications outside of LabVIEW to parse and recognize the dat
    a. In LabVIEW, you would already know the types and can place a generic item of that type. The issue of knowing the type is that you need to know the type of the wire that comes out of the Unflatten function so that the VI will compile correctly. You could always choose a variant value to unflatten and then do some parsing to take the variant a part. Maybe this will help you out.
    See this example for using the Microsoft parser for XML. (http://venus.ni.com/stage/we/niepd_web_display.DISPLAY_EPD4?p_guid=B123AE0CB9FE111EE034080020E74861&p_node=DZ52050&p_submitted=N&p_rank=&p_answer=)
    Randy Hoskin
    Applications Engineer
    National Instruments
    http://www.ni.com/ask

  • Writing the file using Write to SGL and reading the data using Read from SGL

    Hello Sir, I have a problem using the Write to SGL VI. When I am trying to write the captured data using DAQ board to a SGL file, I am unable to store the data as desired. There might be some problem with the VI which I am using to write the data to SGL file. I am not able to figure out the minor problem I am facing.  I am attaching a zip file which contains five files.
    1)      Acquire_Current_Binary_Exp.vi -> This is the VI which I used to store my data using Write to SGL file.
    2)      Retrive_BINARY_Data.vi -> This is the VI which I used to Read from SGL file and plot it
    3)      Binary_Capture -> This is the captured data using (1) which can be plotted using (2) and what I observed is the plot is different and also the time scare is not as expected.
    4)      Unexpected_Graph.png is the unexpected graph when I am using Write to SGL and Read from SGL to store and retrieve the data.
    5)      Expected_Graph.png -> This is the expected data format I supposed to get. I have obtained this plot when I have used write to LVM and read from LVM file to store and retrieve the data.
    I tried a lot modifying the sub VI’s but it doesn’t work for me. What I think is I am doing some mistake while I am writing the data to SGL and Reading the data from SGL. Also, I don’t know the reason why my graph is not like (5) rather I am getting something like its in (4). Its totally different. You can also observe the difference between the time scale of (4) and (5).
    Attachments:
    Krishna_Files.zip ‏552 KB

    The binary data file has no time axis information, it is pure y data. Only the LVM file contains information about t(0) and dt. Since you throw away this information before saving to the binary file, it cannot be retrieved.
    Did you try wiring a 2 as suggested?
    (see also http://forums.ni.com/ni/board/message?board.id=BreakPoint&message.id=925 )
    Message Edited by altenbach on 07-29-2005 11:35 PM
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    Retrive_BINARY_DataMOD2.vi ‏1982 KB

  • How to best format input read from a file to a string

    I am trying to set up a class to convert input read from an xml-file to a java-string, which I can pass on to a web service.
    My attempt is probably not the smartest, but what I did was to set up a for-loop, which iterates through each line in the xml, appending "\n" to the end of each line, before storing them in a variable, which is loaded into an arraylist. When there are no more lines to read in the xml-file, the for-loop should terminate and the contents of the ArrayList should be written to a string, which is then returned.
    Below is my attempt to implement this - thanks in advance!
    import java.io.*;
    import java.util.*;
    public class RequestBuilder {
         private String _filename, output;
         //Constructor method
         RequestBuilder(String filename){
              String line;
              _filename = filename;
              //Sets up a array to store each line of XML read from a file
              ArrayList<String> lineList;
         lineList = new ArrayList<String>();
              try {
                   //Sets up a filereader and a buffer
                   FileReader fr = new FileReader(_filename);
                   BufferedReader br = new BufferedReader(fr);
                   //Iterates through each element of the arraylist until empty
                   for (String o : lineList){
                   //Stores a single linein a variable and appends a line-break
                   line = br.readLine() + "\n";
                   //Addseach line to the arraylist
                   lineList.add(line);
                   //Closes the filereader
                   fr.close();
                   //Writes the arraylist to a string
                   output = lineList.toString();
              } catch (FileNotFoundException e) {
                   e.printStackTrace();
              } catch (IOException e) {
                   e.printStackTrace();
         public String getRequest(){
              return output;
    }

    799992 wrote:
    Well, the reason for doing an ArrayList was that I had to process each line with line breaks and escape characters, but I know realize that I can do the same thing by summing the lines for each iteration directly intro a string like below - it works :-)
    Apparently the filereader takes care of double-quotes as I don't see any difference in the output when I disable the logic I made, which substitutes " with \", can anyone confirm this?
    The code I ended up using:
         //Sets up a filereader and a buffer
                   FileReader fr = new FileReader(_filename);
                   BufferedReader br = new BufferedReader(fr); 
                   //initializes the output variable with the first line from the file
                   output = br.readLine() + "\n";
                   while (br.ready() == true) {
                        //reads each line, saves it in a variable and appends line breaks
                        line = br.readLine() + "\n";
                        //Replaces adds escape character to any double-quotes (apparently not neccessary?)
                        tmpLine = line.replaceAll("\"", "\\\"");
                        line = tmpLine;
                        //sums each line in the current string
                        output = output + line;
    As EJP said you can directly write to the webservice. If you want to check for yourself what the result looks like just read the file without adding anything.
    public String readFile(){
         String xmlString = "";
              try{
                   String line = null;
                   xmlFile = new File(//file);
                   reader = new BufferedReader(new FileReader(xmlFile));
                        while((line = reader.readLine()) != null){
                             xmlString += line;
              catch(FileNotFoundException e){
                        e.printStackTrace();
              catch(IOException e){
                        e.printStackTrace();
         return xmlString.replaceAll("\\s+"," ").trim();//remove spaces
    }

  • How to read a text file into a String?

    and also write a text file from a String. I searched the forum and found this folowing code:
    // Read and append... by Example
    try{
    String fileName = "text.txt"; // Filename
    // Make the inputfile object
    FileInputStream fi = new FileInputStream(fileName);
    byte inData[] = new byte[fi.available()];
    fi.read(inData); // Read
    fi.close(); // Close
    String text = new String(inData); // Make a textstring...
    // Now, do whatever you want with the data... and append...
    String textToAppend = "kjkjhjhKJ";
    byte outData[] = textToAppend.getBytes();
    // Make the outputfile (whith the 'append' boolean set to true
    FileOutputStream fo = new FileOutputStream(fileName,true);
    fo.write(outData);
    fo.close();
    }catch(Exception oops){}but it returns funny characters to the String from the text file and vice versa in writting the text file. Can anybody please help? Thank you.
    kindo

    See here for info on encodings:
    http://java.sun.com/j2se/1.3/docs/guide/intl/encoding.doc.html
    Some common US encodings and common uses:
    ASCII (DOS)
    Cp1252 (Windows 9x)
    UTF8 (XML)
    import java.io.*;
    public class TextFile extends File
    private static String DEFAULT_ENCODING = "ASCII";
    private File file;
    private String encoding;
    public TextFile(File file, String encoding)
         super(file.getPath());
         this.file = file;
         this.encoding = encoding;
    public TextFile(File file)
         this(file, DEFAULT_ENCODING);
    public String load() throws Exception
         FileInputStream fis = new FileInputStream(file);
         byte[] barr = new byte[fis.available()];
         fis.read(barr);
         fis.close();
         return new String(barr, encoding);
    public void save(String str) throws Exception
         FileOutputStream fos = new FileOutputStream(file);
         fos.write(str.getBytes(encoding));
         fos.close();
    }

Maybe you are looking for

  • How to create a symbol/glyph to signify the end of articles.

    Hello, I'm trying to use a custom symbol I created in Illustrator (CS4) as an "end of article" dealie-bob.  I'd like to use this repeatedly throughout my project.  So far I've had no luck figuring this out--importing the graphic into InDesign (CS4),

  • Custom infotype in various languages

    Hi All, I have created a custom infotype in language 'EN'. But when i log on using a different language ,the screen of the custom infotype which i created is totally deformed. Please let me know what needs to be done Thanks, nsp.

  • Schedule Role Upload in portal

    Hi expert, Just receive a requirment to code an WD application in orde to trigger the Role Upload functionality in portal. Anyone has some idea's how to do this ? Is this possible ? An WD calling a HTMLB application? how ? any code snippets are welco

  • SELinux (RHE 5) and mod_jrun22.so

    I am trying to get CFMX 7 working on RHEL 5 and I have followed the instructions here: http://kb.adobe.com/selfservice/viewContent.do?externalId=b45c298e&sliceId=2 but I still get the following error when trying to start apache: Starting httpd: httpd

  • Encoding a FLV file to MP4

    I am relatively new to Adobe and all of its products, and this is my first exposure to Media Encoder CS5. Quite simply I would like to encode a FLV file to MP4. When I drag the FLV file into AME, it tells me "The source compression type is not suppor