Read from a file into a JSP

Okay, so I'm trying to make a JSP for an ePortfolio for school. I'm setting it up so that if a user clicks on a link to one of my papers, the JSP (text.jsp) takes the parameter "ptitle" from the get or post request and retrieves the appropriate text from a pure text file stored in the same folder. (I know, I know, I should use a DB (?), but I'm pretty sure I don't have access right now.) Also, since this is heavy on the Java and light on the HTML, I'd like to use a servlet, but I'm not sure about my host's capabilities. So as a test, I've set up the following:
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <%@ page import="java.io.*" %>
    <%   
        // String pageTitle = pageContext.getAttribute("ptitle");
        String pageTitle = "text.txt"; // this file is in the same folder as text.jsp
        String pageText = "If you are seeing this text, contact the webmaster at...";
        File pageFile = new File(pageTitle); // trying to wrap this file... I haven't worked with files like this much; if this is poorly done, let me know
        FileReader pageReader; // I'm using this for supposed convenience; I'll later change to Channels, I think
        char[] pageBuffer;
        StringBuffer pageTextBuffer;
        if(!pageFile.exists()) {
    %>
    <jsp:forward page="error.jsp">
        <jsp:param name="error" value="Page not found"/>
    </jsp:forward>
    <%
        else {
            pageReader = new FileReader(pageFile);
            pageBuffer = new char[100];
            pageTextBuffer = new StringBuffer();
            while(pageReader.read(pageBuffer) > (75)) { // better way?
                pageTextBuffer.append(pageBuffer);
            out.println(pageTextBuffer); // test the output; I get the error page. Oddly enough, it says that the value for parameter "error" is null (from the session and pageContext).
    %>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>JSP Page</h1>
    </body>
</html>As commented, I get the error page. (It's wierd, because it has the text from the error page, but the URL is still ".../text.jsp" which is cool. Is the problem with the file reader, the JSP, or something else? Thanks for the help.
theAmerican

I would suggest not to use plain old io - quite evil and works quite unpredictably in web applications.
File paths in web apps should always be relative to the context root of your application rather than paths relative to the location of the file in the hard disk.
There are 2 ways to go about this - the inputstream linking to the file can be retrieved in 2 ways.
1. Using the ServletContext object's getResourceAsStream("filepath") method. The 'filepath' here is always relative to the root of your web application (which in turn is denoted by / ).
Thus if your file is stored in a folder called myFiles, which in turn is under your root folder (i.e, on the same level as WEB-INF) and your file is called, say, 'myText.txt', here's how you would obtain an InputStream object.
InputStream is = application.getResourceAsStream("/myFiles/myText.txt"); //in jsps
or
InputStream is = getServletContext().getResourceAsStream("/myFiles/myText.txt"); //in servlets2. Use the getResourceAsStream(filepath) method of the java.lang.Class object. This method picks up files as it picks up classes (i.e it searches the classpath). Now since the classes folder inside WEB-INF is by default included in the classpath, you will have to have your myFiles directory inside the classes folder. Then,
InputStream is = this.getClass().getResourceAsStream("/myFiles/myText.txt"); //in both jsps and servletswould return you an InputStream to that file.
Having got a handle to the InputStream using either #1 or #2, it's now a simple matter of wrapping up the streams for the 'read' functionality.
StringBuffer pageTextBuffer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(is)); //wrap your streams
String eachLine = null;
while((eachLine = reader.readLine()) != null){
        pageTextBuffer.append(eachLine);
out.println(pageTextBuffer);cheers,
ram.

Similar Messages

  • Convert a line read from text file into string

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

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

  • Problem with reading from bin file into Vector

    What am I doing wrong? It works fine to write the vector to the bin file and then read from it. But if I try just to read from the file it wont work.
    Does anybody has any good advice to give when it comes to reading data form a bin file??
    import javax.swing.*;
    import java.util.*;
    import java.io.*;
    class Binaerfil
         public static void main (String [] args) throws IOException, ClassNotFoundException{
              ObjectOutputStream utFil = new ObjectOutputStream (new FileOutputStream("HighScoreLista.bin"));
              int po = 50;
              Spelare s;
              Spelare s1, s2, s3, s4, s5,s6,s7,s8,s9,s10;
              String f�rNamn;
              Vector v = new Vector();
              s1 = new Spelare("Mario", 100);
              s2 = new Spelare("Tobias",90 );
              s3 = new Spelare("Sanja", 80 );
              s4 = new Spelare("Marko", 70 );
              s5 = new Spelare("Sofia", 60 );
              s6 = new Spelare("Kalle", 50 );
              s7 = new Spelare("Lisa", 40 );
              s8 = new Spelare("Pelle", 30 );
              s9 = new Spelare("Olle", 20 );
              s10 = new Spelare("Maria",10 );
              v.add(s1);
              v.add(s2);
              v.add(s3);
              v.add(s4);
              v.add(s5);
              v.add(s6);
              v.add(s7);
              v.add(s8);
              v.add(s9);
              v.add(s10);
              System.out.println ("Before writing to file");
              System.out.println(v);
              //Write to file
              utFil.writeObject (v);
              utFil.close();
         ObjectInputStream inFil = new ObjectInputStream (new FileInputStream("HighScoreLista.bin"));     
              v =(Vector) inFil.readObject();
         System.out.println (v);
              inFil.close();
    }

    Because what you are writing to the file is a vector, that is all you can get out. You are actually reading a single Object from the file which you can cast to a Vector, from which you can access the data stored inside. If you want to read the Spelare instances from the file, you will have to save them individually to the file. You will have to implement Serializable and look up the API to do that.

  • Open and read from text file into a text box for Windows Store

    I wish to open and read from a text file into a text box in C# for the Windows Store using VS Express 2012 for Windows 8.
    Can anyone point me to sample code and tutorials specifically for Windows Store using C#.
    Is it possible to add a Text file in Windows Store. This option only seems to be available in Visual C#.
    Thanks
    Wendel

    This is a simple sample for Read/Load Text file from IsolateStorage and Read file from InstalledLocation (this folder only can be read)
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Windows.Storage;
    using System.IO;
    namespace TextFileDemo
    public class TextFileHelper
    async public static Task<bool> SaveTextFileToIsolateStorageAsync(string filename, string data)
    byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(data);
    StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
    var file = await local.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
    try
    using (var s = await file.OpenStreamForWriteAsync())
    s.Write(fileBytes, 0, fileBytes.Length);
    return true;
    catch
    return false;
    async public static Task<string> LoadTextFileFormIsolateStorageAsync(string filename)
    StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
    string returnvalue = string.Empty;
    try
    var file = await local.OpenStreamForReadAsync(filename);
    using (StreamReader streamReader = new StreamReader(file))
    returnvalue = streamReader.ReadToEnd();
    catch (Exception ex)
    // do somthing when exception
    return returnvalue;
    async public static Task<string> LoadTextFileFormInstalledLocationAsync(string filename)
    StorageFolder local = Windows.ApplicationModel.Package.Current.InstalledLocation;
    string returnvalue = string.Empty;
    try
    var file = await local.OpenStreamForReadAsync(filename);
    using (StreamReader streamReader = new StreamReader(file))
    returnvalue = streamReader.ReadToEnd();
    catch (Exception ex)
    // do somthing when exception
    return returnvalue;
    show how to use it as below
    async private void Button_Click(object sender, RoutedEventArgs e)
    string txt =await TextFileHelper.LoadTextFileFormInstalledLocationAsync("TextFile1.txt");
    Debug.WriteLine(txt);
    在現實生活中,你和誰在一起的確很重要,甚至能改變你的成長軌跡,決定你的人生成敗。 和什麼樣的人在一起,就會有什麼樣的人生。 和勤奮的人在一起,你不會懶惰; 和積極的人在一起,你不會消沈; 與智者同行,你會不同凡響; 與高人為伍,你能登上巔峰。

  • Read from Measurement File Express VI - Time information

    I need some assistance with a small problem with building reports of collected data. I don't see it very relevant, but I'm collecting data from several modules on a 9074 cRIO. I'm not using the cRIO the way it is intended, but it is perfect for my needs. Anyway, I'm collecting the different types of data in RT, then using the express VI "Write to Measurement File" with TDMS option selected and one time column only selected. Also one header, etc. Nothing fancy.
    In another VI I want to use this collection of .tdms files to create an Excel report. Everything is working good however I need a time column for reporting my data. When I view the .tdms file using Excel Importer, the time column is there and perfect, with the next column a relative time (or iteration) and then columns with the signal names at top and all the data below. Perfect.
    I'm similarly using the "Read from Measurement File" Express VI to get the data back the same way it went in. I have everything in it's correct place on building the Excel Report, but I haven't been able to find any way to include the first time column in my import. I can use "Get Attributes" Express VI to get the signal names from the read, but that's not going to help with the time data. How is it possible that Labview allows to put the time data there, but not retrieve it? I'm aware of the warnings that Timestamps aren't supported by TDMS file format vs LVM, but there MUST be a way to retrieve that time information if "Excel Importer" can do it.
    If that time column in the TDMS file is somehow computed using the start timestamp and dt, can someone explain how to compute that for my report?
    Unfortunately, I can't use the LVM format because I need to allow the users of these VI's the backup of using Excel Importer to see this data if my report generation VI is not functional.
    I'll attach one of the TDMS files for illustration. The first column of the second worksheet is exactly the data I need for my report.
    Attachments:
    TDMS Imported.xls ‏28 KB

    DylanC,
    Your solution works as needed. Thank You.
    I think I found a better solution though. Apparently if you convert a signal from the Express VI "Read from Measurement File" into a waveform the time data required is included, then you can convert to a string with a for loop and insert it as a row header into a table. The result gives me what I need. I attached a screenshot if someone is interested.
    AWyers
    Attachments:
    TableFromTDMS.JPG ‏61 KB

  • How to read from and write into the same file from multiple threads?

    I need to read from and write into a same file multiple threads.
    How can we do that without any data contamination.
    Can u please provide coding for this type of task.
    Thanks in advance.

    Assuming you are using RandomAccessFile, you can use the locking functionality in the Java NIO library to lock sections of a file that you are reading/writing from each thread (or process).
    If you can't use NIO, and all your threads are in the same application, you can create your own in-process locking mechanism that each thread uses prior to accessing the file. That would take some development, and the OS already has the capability, so using NIO is the best way to go if you can use JDK 1.4 or higher.
    - K
    I need to read from and write into a same file
    multiple threads.
    How can we do that without any data contamination.
    Can u please provide coding for this type of task.
    Thanks in advance.

  • To read data from exel file into sap

    hi all,
    How to read data from exel file into the internal table in abap?
    Regards,
    sugeet.

    Hi Sugeet,
    Use the following code.
    DATA : BEGIN OF tbl_asset occurs 0,
             anlkl LIKE anla-anlkl,          " Asset Class
             bukrs LIKE anla-bukrs,          " Company Code
             ranl1 LIKE ra02s-ranl1,         " Asset #
             txt50 LIKE anla-txt50,          " Description 1
             txa50 LIKE anla-txa50,          " Description 2
             sernr LIKE anla-sernr,          " Serial #
             invnr LIKE anla-invnr,          " Inventory #
             menge LIKE anla-menge,          " Quantity
             meins LIKE anla-meins,          " Base UOM
             inken LIKE anla-inken,          " Inventory
    END OF tbl_asset.
    DATA : w_filename TYPE IBIPPARMS-path,
           w_file     TYPE string.
    start-of-selection.
    *popup for file path from user
    CALL FUNCTION 'F4_FILENAME'
    EXPORTING
       PROGRAM_NAME        = SYST-CPROG
       DYNPRO_NUMBER       = SYST-DYNNR
    IMPORTING
       FILE_NAME           = w_filename          .
    MOVE w_filename TO w_file .
    * upload data
    CALL FUNCTION 'GUI_UPLOAD'
      EXPORTING
        FILENAME                      =  w_file
        FILETYPE                      = 'ASC'
        HAS_FIELD_SEPARATOR           = 'X'
      TABLES
        DATA_TAB                      = tbl_asset
      EXCEPTIONS
       FILE_OPEN_ERROR               = 1
       FILE_READ_ERROR               = 2
       NO_BATCH                      = 3
       GUI_REFUSE_FILETRANSFER       = 4
       INVALID_TYPE                  = 5
       NO_AUTHORITY                  = 6
       UNKNOWN_ERROR                 = 7
       BAD_DATA_FORMAT               = 8
       HEADER_NOT_ALLOWED            = 9
       SEPARATOR_NOT_ALLOWED         = 10
       HEADER_TOO_LONG               = 11
       UNKNOWN_DP_ERROR              = 12
       ACCESS_DENIED                 = 13
       DP_OUT_OF_MEMORY              = 14
       DISK_FULL                     = 15
       DP_TIMEOUT                    = 16
       OTHERS                        = 17
    IF SY-SUBRC <> 0.
    * MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    *         WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    ENDIF.
    for HAS_FIELD_SEPARATOR Use
    'X': Fields are separated by tabs.
    SPACE: Fields are not separated by tabs. In this case, the table must contain only one column or all columns must be contained in the file in their entire length.
    Hope it helps...
    Lokesh
    Pls. reward appropriate points

  • How to  read from excel file and write it using implicit jsp out object

    our code is as below:Please give us proper solution.
    we are reading from Excel file and writing in dynamicaly generated Excel file.it is writing but not as original excel sheet.we are using response.setContentType and response.setHeader for generating pop up for saveing the original file in to dynamically generated Excel file.
    <%@ page contentType="application/vnd.ms-excel" %>
    <%     
         //String dLoadFile = (String)request.getParameter("jspname1");
         String dLoadFile = "c:/purge_trns_nav.xls" ;
         File f = new File(dLoadFile);
         //set the content type(can be excel/word/powerpoint etc..)
         response.setContentType ("application/msexcel");
         //get the file name
         String name = f.getName().substring(f.getName().lastIndexOf("/") + 1,f.getName().length());
         //set the header and also the Name by which user will be prompted to save
         response.setHeader ("Content-Disposition", "attachment;     filename="+name);
         //OPen an input stream to the file and post the file contents thru the
         //servlet output stream to the client m/c
              FileInputStream in = new FileInputStream(f);
              //ServletOutputStream outs = response.getOutputStream();
              int bit = 10;
              int i = 0;
              try {
                        while (bit >= 0) {
                        bit = in.read();
                        out.write(bit) ;
    } catch (IOException ioe) { ioe.printStackTrace(System.out); }
              out.flush();
    out.close();
    in.close();     
    %>

    If you want to copy files as fast as possible, without processing them (as the DOS "copy" or the Unix "cp" command), you can try the java.nio.channels package.
    import java.nio.*;
    import java.nio.channels.*;
    import java.io.*;
    import java.util.*;
    import java.text.*;
    class Kopy {
         * @param args [0] = source filename
         *        args [1] = destination filename
        public static void main(String[] args) throws Exception {
            if (args.length != 2) {
                System.err.println ("Syntax: java -cp . Kopy source destination");
                System.exit(1);
            File in = new File(args[0]);
            long fileLength = in.length();
            long t = System.currentTimeMillis();
            FileInputStream fis = new FileInputStream (in);
            FileOutputStream fos = new FileOutputStream (args[1]);
            FileChannel fci = fis.getChannel();
            FileChannel fco = fos.getChannel();
            fco.transferFrom(fci, 0, fileLength);
            fis.close();
            fos.close();
            t = System.currentTimeMillis() - t;
            NumberFormat nf = new DecimalFormat("#,##0.00");
            System.out.print (nf.format(fileLength/1024.0) + "kB copied");
            if (t > 0) {
                System.out.println (" in " + t + "ms: " + nf.format(fileLength / 1.024 / t) + " kB/s");
    }

  • UPDATE : Toshiba Recovery Wizard 'cannot read from source file or disk' error (satellite L500)

    UPDATE 2: Phoned Toshiba tech support again, guided by techie to begin the recovery again. Just before phoning I was able to go into recovery options and view the drive setup and all the files that couldn't be read are on the CD so I've no idea why the error kept occuring, and neither did the techie. Fingers crossed it works this time but I'm not overly hopefully given that we've just done exactly the same as I did before.  UPDATE 1: I got into the BIOS and reset everything back to defaults and yay, my toshiba recovery wizard now starts! :-D  On the down side, when trying to do a factory default software / out of the box recovery I continually get error messages with regards to copying the files, for example 
    cannot read from source file or disk
    7z.dll
    Type application extension
    size 585kb
    date modified 7/14/2009 10.26pm
    other read / copy errors include PREINST6.SWM, BOOT_32, BOOTPRIORITY, CHECKMAXPTSIZE, CHGBOOT, CPU, CPUCHECK, CREATEPARTITION, CTRLDRVINFO, DISKWIPE, DMI, DPINST32, EBLIB.DLL, ERRORDIALOG, EW3BOOTSEQ, FWLINK, FWLINK.SYS, GETHDDINFO, GETKEYSTATE, IMAGEX, INFILED, INITRECAREA, KRAIADAPI.DLL ..... at which point I decided to 'skip all' :-/
    Any explanations as to what's going on and how I might be able to fix it would be very much appreciated! :-)  Thank you!
    I have a two and half year old satellite L500 with an Intel i-3 and 4 gigs of RAM, on which I was running Windows 7.
    Admittedly it’s had rather a hard life (I ran some very demanding CAD / graphics software on it) but it had always performed well until just recently, when after suffering several BSOD (which had never happened before), the hard drive failed.
    I partitioned and formatted a brand new hard drive (which is perfectly fine and functions normally when hooked up to another laptop with a SATA to USB cable) and obtained system recovery discs from Toshiba.  Unfortunately, when I try and run the first disc, windows starts to load files but then generates an error screen with the message Error F3-F100-0003 and a request to turn the computer off.  
    When I use the windows Memory Diagnostic to get into the Windows Boot Manager Screen I get the following;
    Windows failed to start.  A recent hardware / software change might be the case.
    To fix the problem
    Insert your windows installation disc and restart your computer
    Choose your language settings and click ‘next’
    Click ‘repair your computer’
    File: \boot\memtest.exe
    Status: 0xc000000f
    Info: the selected entry could not be loaded because the application is missing or corrupt.
    I can also use F8 on startup to get into the advanced boot options but selecting any of them simply results in the F3-F100-0003 error message.  I’ve run a memory test using the UBCD, which tells me the memory is fine, and tried another hard drive (which also works perfectly well in another laptop) but no joy.  On phoning Toshiba support the techie said my hard drive had failed, but as I say, both hard drives are perfectly fine / usable when hooked up to another laptop.  I’m now completely stuck as to what the problem is and how I might resolve it – any advice / suggestions would be most gratefully received! Thank you in advance :-)

    Satellite L655-S5096
    Downloads here.
    the second disc gives me the the "cannot read from source file or disk PREINST8.SWM"
    My best guess is that the disc is not readable. Try copying it to another. Sometimes that works.
    Otherwise, order new discs from Toshiba.
    -Jerry

  • Trying to parse a file-read from text file.vi

    I'm attempting to read a txt file that has tab separated data. In the fourth (or any) column is the only data I need. The data is a string of numbers (23.454).
    I've used the Read from Text File.vi and the Read From Spreadsheet.vi and I just don't seem to have enough LV background to extract the pertinent  data into a graph. any suggestions?

    (It is silly to use "delete from array" if all you want is a column. The correct function is "index array")
    Joe's idea above basically works fine. Here's a quick adapdation (the node before the graph is "index array" from the array palette.).
    Message Edited by altenbach on 06-11-2007 11:57 AM
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    FileRead.png ‏11 KB

  • Read from text file vi won't read file...

    I am very new to LV programming so I hope you forgive any stupid mistakes I am making.   I am using Ver. 8.2 on an XP machine.
    I have a small program that stores small data sets in text files and can update them individually or read and update them all sequentially, sending the data out a USB device.   Currently I am just using two data sets, each in their own small text file.  The delimiter is two commas ",,".
    The program works fine as written when run in the regular programming environment.   I noticed, however, as soon as I built it into a project that the one function where it would read each file sequentially to update both files the read from text file vi would return an empty data set, resulting in blank values being written back into the file.   I read and rewrite the values back to the text file to place the one updated field (price) in it'sproper place.  Each small text file is identified and named with a 4 digit number "ID".   I built it twce, and get the same result.  I also built it into an installer and unfortunately the bug travelled into the installation as well.
    Here is the overall program code in question:
    Here is the reading and parsing subvi:
    If you have any idea at all what could cause this I would really appreciate it!
    Solved!
    Go to Solution.

    Hi Kiauma,
    Dennis beat me to it, but here goes my two cents:
    First of all, it's great to see that you're using error handling - that should make troubleshooting a lot easier.  By any chance, have you observed error 7 when you try to read your files and get an empty data set?  (You've probably seen that error before - it means the file wasn't found)
    If you're seeing that error, the issue probably has something to do with this:
    Relative paths differ in an executable.  This knowledge base document sums it up pretty well. To make matters more confusing, if you ever upgrade to LabVIEW 2009 the whole scheme changes.  Also, because an installer contains the executable, building the installer will always yield the same results.
    Lastly, instead of parsing each set of commas using the "match pattern" function, there's a function called "spreadsheet string to array" (also on the string palette) that does exactly what you're doing, except with one function:
    I hope this is helpful...
    Jim

  • Scenario to read from txt-file and create a sales order

    Hi,
    i have started creating a scenario to read from an txt-file and to create a sales order.
    When i activate my scenario, i get the following message :
        no scenario step (vBIU) associated for this step for the incoming system (SysId)
    When i look into the detailed xml-file i see that all the records are read from the file, but there is no next step to be treated.
    Has somebody any idea how this come ?
    -<Msg MessageLog="true" msglogexcl="false" logmsg="0009" recording="true" BeginTimeStamp="20111202095144" MessageId="11120209514499820828C0A801674F24" xmlns="urn:com.sap.b1i.vplatform:entity">-<Header><msglog b1ifactive="true" always="false" step="Default message log"/>-<Resumption><starter ipo="/vP.0010000138.in_FEAN/com.sap.b1i.vplatform.runtime/INB_FI_EXST_ASYN_NAM/INB_FI_EXST_ASYN_NAM.ipo/proc"/></Resumption><IPO tid="11120205535899820808C0A801678C54" Id="INB_FI_EXST_ASYN_NAM"/><Sender Id="0010000138"/><Inbound file="ORDERS_TEST" ext="csv" path="C:\TEMP\In" pltype="txt" wrap="" deli=";"/></Header>-<Body><Payload Type="File exist" Role="T"/>-<Payload Role="S">-<io xmlns="urn:com.sap.b1i.bizprocessor:bizatoms" pltype="txt">
    -<row>
    <col>OH</col>
    <col>0000087077</col>
    <col>201110041205</col>
    <col>220</col>
    <col>9</col>
    <col>201110191702</col>
    <col>8710624300012</col>
    <col>8714252008609</col>
    <col>8710624300012</col>
    <col>8714252008609</col>
    <col>8710624300012</col>
    <col>N</col>
    <col>N</col>
    <col>N</col>
    </row>
    -<row>
    <col>OL</col>
    <col>1</col>
    <col>8711715844378</col>
    <col>20</col>
    </row>-<row>
    <col>OL</col>
    <col>2</col>
    <col>8711715844392</col>
    <col>60</col>
    </rowrow>
    <col>OL</col>
    <col>16</col>
    <col>8710251791092</col>
    <col>280</col>
    </row>
    </io>
    </Payload>
    </Body>
    </Msg>
    This is my final atom :
    <?xml version="1.0" encoding="UTF-8"?><xsl:stylesheet xmlns:b1e="urn:com.sap.b1i.sim:b1event" xmlns:b1ie="urn:com.sap.b1i.sim:b1ievent" xmlns:bfa="urn:com.sap.b1i.bizprocessor:bizatoms" xmlns:jdbc="urn:com.sap.b1i.adapter:jdbcadapter" xmlns:rfc="urn:sap-com:document:sap:rfc:functions" xmlns:sim="urn:com.sap.b1i.sim:entity" xmlns:utils2="com.sap.b1i.bpc_tools.Utilities" xmlns:vpf="urn:com.sap.b1i.vplatform:entity" xmlns:xci="urn:com.sap.b1i.xcellerator:intdoc" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" bfa:force="" vpf:force="" jdbc:force="" rfc:force="" b1ie:force="" b1e:force="" xci:force="" sim:force="" utils2:force=""><xsl:output method="xml" encoding="UTF-8" indent="yes"></xsl:output><xsl:param name="atom"></xsl:param><xsl:param name="sessionid"></xsl:param><xsl:variable name="msg" select="/vpf:Msg/vpf:Body/vpf:Payload[./@Role=&apos;S&apos;]"></xsl:variable><xsl:variable name="vpSender" select="/vpf:Msg/vpf:Header/vpf:Sender/@Id"></xsl:variable><xsl:variable name="vpObject" select="/vpf:Msg/vpf:Header/vpf:Sender/@ObjId"></xsl:variable><xsl:variable name="vpReceiver" select="/vpf:Msg/vpf:Header/vpf:ReceiverList/vpf:Receiver[./@handover=&apos;P&apos;]/@Id"></xsl:variable><xsl:template match="/">
    <Msg xmlns="urn:com.sap.b1i.vplatform:entity">
    <xsl:copy-of select="/vpf:Msg/@*"></xsl:copy-of>
    <xsl:copy-of select="/vpf:Msg/vpf:Header"></xsl:copy-of>
    <Body>
    <xsl:copy-of select="/vpf:Msg/vpf:Body/*"></xsl:copy-of>
    <Payload Role="R" id="{$atom}">
    <xsl:call-template name="transform"></xsl:call-template>
    </Payload>
    </Body>
    </Msg>
    </xsl:template><xsl:template name="transform">
    <FinalAtomResult xmlns="">
    <BOM>
    <BO>
    <AdmInfo>
    <Object>17</Object>
    <Version>2</Version>
    </AdmInfo>
         <Documents>
         <row>
         <DocDate>
              <xsl:copy-of select="$msg/io/row[0]/col[2]/text()"></xsl:copy-of>
         </DocDate>
         <DocDueDate>
              <xsl:copy-of select="$msg/io/row[0]/col[5]/text()"></xsl:copy-of>
         </DocDueDate>
         <CardCode>KD10251</CardCode>
         <NumAtCard>
              <xsl:copy-of select="$msg/io/row[0]/col[1]/text()"></xsl:copy-of>
         </NumAtCard>
         <U_PMX_JD_COMP>32</U_PMX_JD_COMP>
         </row>
                          </Documents>
         <Document_Lines>
         <xsl:for-each select="$msg/io/row">
         <row>
         <BarCode>
              <xsl:copy-of select="$msg/io/row[*]/col[2]/text()"></xsl:copy-of>
         </BarCode>
         <Quantity>
              <xsl:copy-of select="$msg/io/row[*]/col[3]/text()"></xsl:copy-of>
         </Quantity>
         </row>
         </xsl:for-each>
         </Document_Lines>

    Mike,
    you were right, you may not specify the extension of a file.
    Another thing i detected is that the loop of my data start with the index 1 instead of 0 !!!
    In this scenario, i have to read all the lines of the file and each time i should do a SQL-query,
    so that i can use the result to build my sales document.
    Do you know if it this is possible or have you any idea how to do this ?
    thx,
    Mario

  • How to print the content in Reverse which is read from the file

    i have written a program to display the content of the file using files concept. now the task is how to display it in reverse order i.e from last to first which is read from the file.

    If it will all fit in memory read the file as you are doing now appending everything into a StringBuilder. Then use the reverse() method of that class to obtain your output.
    http://java.sun.com/javase/6/docs/api/java/lang/StringBuilder.html#reverse()

  • How to read/write .CSV file into CLOB column in a table of Oracle 10g

    I have a requirement which is nothing but a table has two column
    create table emp_data (empid number, report clob)
    Here REPORT column is CLOB data type which used to load the data from the .csv file.
    The requirement here is
    1) How to load data from .CSV file into CLOB column along with empid using DBMS_lob utility
    2) How to read report columns which should return all the columns present in the .CSV file (dynamically because every csv file may have different number of columns) along with the primariy key empid).
    eg: empid report_field1 report_field2
    1 x y
    Any help would be appreciated.

    If I understand you right, you want each row in your table to contain an emp_id and the complete text of a multi-record .csv file.
    It's not clear how you relate emp_id to the appropriate file to be read. Is the emp_id stored in the csv file?
    To read the file, you can use functions from [UTL_FILE|http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14258/u_file.htm#BABGGEDF] (as long as the file is in a directory accessible to the Oracle server):
    declare
        lt_report_clob CLOB;
        l_max_line_length integer := 1024;   -- set as high as the longest line in your file
        l_infile UTL_FILE.file_type;
        l_buffer varchar2(1024);
        l_emp_id report_table.emp_id%type := 123; -- not clear where emp_id comes from
        l_filename varchar2(200) := 'my_file_name.csv';   -- get this from somewhere
    begin
       -- open the file; we assume an Oracle directory has already been created
        l_infile := utl_file.fopen('CSV_DIRECTORY', l_filename, 'r', l_max_line_length);
        -- initialise the empty clob
        dbms_lob.createtemporary(lt_report_clob, TRUE, DBMS_LOB.session);
        loop
          begin
             utl_file.get_line(l_infile, l_buffer);
             dbms_lob.append(lt_report_clob, l_buffer);
          exception
             when no_data_found then
                 exit;
          end;
        end loop;
        insert into report_table (emp_id, report)
        values (l_emp_id, lt_report_clob);
        -- free the temporary lob
        dbms_lob.freetemporary(lt_report_clob);
       -- close the file
       UTL_FILE.fclose(l_infile);
    end;This simple line-by-line approach is easy to understand, and gives you an opportunity (if you want) to take each line in the file and transform it (for example, you could transform it into a nested table, or into XML). However it can be rather slow if there are many records in the csv file - the lob_append operation is not particularly efficient. I was able to improve the efficiency by caching the lines in a VARCHAR2 up to a maximum cache size, and only then appending to the LOB - see [three posts on my blog|http://preferisco.blogspot.com/search/label/lob].
    There is at least one other possibility:
    - you could use [DBMS_LOB.loadclobfromfile|http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14258/d_lob.htm#i998978]. I've not tried this before myself, but I think the procedure is described [here in the 9i docs|http://download.oracle.com/docs/cd/B10501_01/appdev.920/a96591/adl12bfl.htm#879711]. This is likely to be faster than UTL_FILE (because it is all happening in the underlying DBMS_LOB package, possibly in a native way).
    That's all for now. I haven't yet answered your question on how to report data back out of the CLOB. I would like to know how you associate employees with files; what happens if there is > 1 file per employee, etc.
    HTH
    Regards Nigel
    Edited by: nthomas on Mar 2, 2009 11:22 AM - don't forget to fclose the file...

  • Reading from a file. How to ask the user for file name at run time????

    I have the code to read from a file but my problem is how to prompt the user for the file name at run time.
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.InputMismatchException;
    import java.util.Scanner;
    public class FileRead {
        public static void main(String args[]) {
            Scanner scan = null;
            File file = new File("Results.txt");
            String number;
            try {
                scan = new Scanner(file);
                while (scan.hasNext()){
                number = scan.next();
                System.out.println(number);}
            catch (FileNotFoundException ex1){
                System.out.println("No such file");
            catch (IllegalStateException ex2){
                System.out.println("Did you close the read by mistake");
            catch (InputMismatchException ex){
                System.out.println("File structure incorrect");
            finally{
                scan.close();}
    }Any hints would be greatly appreciated. Thank you in advance

    I have read through some of the tutorials that you have directed me too and they are very useful, thank you. however there are still a few things that i am not clear about. I am using net beans 5.0 I have placed a text file named Results.txt into the project at the root so the program can view it.
    When I use the code that you provided me with, does it matter where the file is, or will it look through everywhere on the hard drive to find a match?
    This code compiles but at run time it comes up with this error
    run-single:
    java.lang.NoClassDefFoundError: NamedFile
    Exception in thread "main"
    Java Result: 1
    BUILD SUCCESSFUL (total time: 3 seconds)
    import java.util.Scanner;
    import java.io.*;
    class NamedFileInput
      public static void main (String[] args) throws IOException
        int num, square;   
        // this Scanner is used to read what the user enters
        Scanner user = new Scanner( System.in );
        String  fileName;
        System.out.print("File Name: ");
        fileName = user.nextLine().trim();
        File file = new File( fileName );     // create a File object
        // this Scanner is used to read from the file
        Scanner scan = new Scanner( file );     
        while( scan.hasNextInt() )   // is there more data to process?
          num = scan.nextInt();
          square = num * num ;     
          System.out.println("The square of " + num + " is " + square);
    }his is the code that i used. It is the same as the code you posted for me (on chapter 23 I/O using Scanner and PrintStream) Sorry im just really stuck on this!!

Maybe you are looking for

  • Converter not working correctly

    I have been using PDF converter for a while now with no problems, but when I tried to convert a PDF file today, it is not working properly. The formatting is all mucked up and the letters are in 5 different types of font/size. I have uninstalled & re

  • Integration problem between ACS 5 and AD 2012

    Hi Guys, ACS 5.5 is installed on SNS-3415 appliance. Integration with Active Directory 2012 has been successfully completed. The problem which I'm facing that i can't see all the groups of AD under ACS, i see only few of them. Also if i created new G

  • Two emails one must require password entered

    I have two hotmail email accounts ...one must be private password protected with its own contact address file..  How do I set up the private one?  The non private one is set up and appears when I touch "mail"

  • .php files downloading rather then displaying

    I have an X Serve with OS x 10.5.6 Apache is running fine, I have created a test .php file and put it in WebServer/Documents. When I try to view it through a browser, it DOWNLOADS the php file rather then just displaying it in Safari. It opens in Tex

  • Default programs list windows 7

    Firefox does not appear in the list of default programs in Windows 7 so I cannot select it to be my default browser. How do I add Firefox to the list so that I may select it?