Display text file in servlet with preserved formatting(newlines, etc)

how do i display a text file in servlet, but all the blanks and newlines are preserved.
this is what i did:
RandomAccessFile text = new RandomAccessFile("D:/FYP/tempMessage.txt","r");
long length = text.length();
byte[] bytes = new byte[(int)length];
//Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead=deCiphered.read(bytes, offset, bytes.length-offset)) >= 0) {
offset += numRead;
// Close the input stream and return bytes
text.close();
String plainText=new String(bytes);
//display in servlet
pw.println("<center>Plain text: " + plainText + "</center>");
the problem here is the newlines are seem to be omitted when they're displayed in a web browser, rendering the displayed text in a mess.
any help are greatly appreciated. thanks in advance :)

display text in between <pre></pre> tags.
or display it inside a text area,dont worry abt the text area border, u can change that using style sheets.

Similar Messages

  • Email attachment for text file using ABAP with funny format output

    Hi All,
    I am developing an ABAP program to generate an email to an external email address by using Function Module FUNCTION 'SO_DOCUMENT_SEND_API1. There is an attachment included in this program. The attachment is generated by reading through a data file from an Application Server and place it in the internal table before attaching it to the function module.
    Currently when I download the data file through SO01, I found that the data file looks a bit funny as below. It seems that all the letters are separated with an additional space in between.
    Funny Output:
    A B C D  1 2 3  A B C
    Suppose Output:
    ABCD 123 ABC
    I am not too sure if there is any output format that I need to set in order to make it works?

    hi Sree Ram,
    Thanks for your quick reply. The following is my code. I am not too sure if your reply will help to change the format of my data file or attachment sent through email.
    Thanks.
      CALL FUNCTION 'SO_DOCUMENT_SEND_API1'
        EXPORTING
          document_data              = w_doc_data
          put_in_outbox              = 'X'
          sender_address             = ld_sender_add
          sender_address_type        = ld_sender_add_type
          commit_work                = 'X'
        IMPORTING
          sent_to_all                = w_sent_all
        TABLES
          packing_list               = t_packing_list
          contents_bin               = t_attachment
          contents_txt               = it_message
          receivers                  = t_receivers
        EXCEPTIONS
          too_many_receivers         = 1
          document_not_sent          = 2
          document_type_not_exist    = 3
          operation_no_authorization = 4
          parameter_error            = 5
          x_error                    = 6
          enqueue_error              = 7
          OTHERS                     = 8.

  • I was given an assingment, but have no idea where to begin. The assingment is to create a text file using notepad with all of my digital inputs and some how make those imputs show up on my digital indicators on my control pannel

    I was given an assingment, but have no idea where to begin. The assingment is to create a text file using notepad with all of my digital inputs and some how make those imputs show up on my digital indicators on my control pannel.
    When it was explained to me it didn't sound to hard of a task, I have no LabVIEW experience and the tutortial sucks.

    StevenD: FYI, I did NOT give you the one star rating. I would never do that!
    StevenD wrote:
    Ow. Someone is grumpy today.
    Well, this is an assignment, so it is probably homework.
    Why else would anyone give HIM such an assigment, after all he has no LabVIEW experience and the tutorials are too hard for him?
    This would make no sense unless all of it was just covered in class!
    This is not a free homework service with instant gratification.
    OK! Let's do it step by step. I assume you already have a VI with the digital indicators.
    "...but have no idea where to begin".
    open notepad.
    decide on a format, possibly one line per indicator.
    type the document.
    close notepad.
    open LabVIEW.
    Open the existing VI with all the indicators.
    (are you still following?)
    look at the diagram.
    Who made the program?
    Does the code make sense so far?
    Is it a statemachine or just a bunch of crisscrossed wires?
    Where do you want to add the file read?
    How should the file be read (after pressing a read button, at the start of the program ,etc.)
    See how far you get!
    Message Edited by altenbach on 06-24-2008 11:23 AM
    LabVIEW Champion . Do more with less code and in less time .

  • How to modify the contents of a text file stored along with a midlet

    Hi,
    I have been developing a application in j2me wherein i need to first read the contents of the text file stored along with the midlet and later erase the existing content and update it with some text.
    I was able to read the file in the following manner
    InputStream is = getClass().getResourceAsStream("myfile.txt");
    Now i need to erase the contents and then update it the new content, how do i do it. Kinldy please help me out. It is very urgent.
    Thanks

    Didn't you hear me the first time?
    http://forum.java.sun.com/thread.jspa?threadID=701360&messageID=4068435#4068435

  • How to display text file text in aTextArea component

    Hello
    ive managed to display the text file text in the console, but i want it to show up in the textArea component i have in a frame,
    it seems to display the last character . in the text area
    wheres the rest of the text...this was a lot easier in VB.NET
    any help would be much appreciated
    heres my code...
    private void openButtonActionPerformed(java.awt.event.ActionEvent evt)  {//GEN-FIRST:event_openButtonActionPerformed
    // TODO add your handling code here:
         FileNameExtensionFilter filter = new FileNameExtensionFilter("Text Files Only","txt");
         editorFileChooser.setFileFilter(filter);
         int returnVal = editorFileChooser.showOpenDialog(this);
         if (returnVal == JFileChooser.APPROVE_OPTION){
              System.out.println("You chose to open this file: " + editorFileChooser.getSelectedFile().getName());
              openFileName = editorFileChooser.getSelectedFile().getName();
              openFile = new File(openFileName);
              try {
                   this.readFile = new FileReader(openFile);
              } catch (FileNotFoundException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              int inputCharacters;
         try {
         while ((inputCharacters = readFile.read()) != -1){
              System.out.print((char)inputCharacters);
              char[]CHARAARAY = {(char)inputCharacters};
              s3 = new String(CHARAARAY );
              this.editorTextArea.setLineWrap(true);
         this.editorTextArea.setText(s3.toString());
         readFile.close();
         catch(IOException ex){
              System.out.println();
    }//GEN-LAST:event_openButtonActionPerformed

    >
    wheres the rest of the text...this was a lot easier in VB.NET>If you only need to code for Windows, use VB. For code that works on computers, learn the Java idioms, especially with regard to X-plat issues with Files.
    >
    heres my code...>That was a code snippet. You will get better chance of help around these parts, if you can prepare an SSCCE. The code below* is an SSCCE.
    There was a basic problem in the logic of that code, that resulted in the assumption (by the JRE) that every file the user attempted to load, was located in the 'current directory'. It was fixed by abandoning the String based file name of the file, and instead setting openFile to the selected file in the chooser. I also demolished the loading code by replacing the JTextArea with a JEditorPane (much easier).
    * Altered code;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.filechooser.*;
    import java.io.*;
    class TestLoadFile extends JPanel {
      JFileChooser editorFileChooser;
      File openFile;
      JEditorPane editorTextArea;
      TestLoadFile() {
        super(new BorderLayout());
        editorTextArea = new JEditorPane();
        add(
          new JScrollPane(editorTextArea),
          BorderLayout.CENTER );
        JButton load = new JButton("Load File");
        load.addActionListener( new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
              openButtonActionPerformed(ae);
        add( load, BorderLayout.SOUTH );
        editorFileChooser = new JFileChooser();
      public static void main(String[] args) {
        TestLoadFile tlf = new TestLoadFile();
        JOptionPane.showMessageDialog(null, tlf);
      Dimension preferredSize = new Dimension(600,400);
      public Dimension getPreferredSize() {
        return preferredSize;
      private void openButtonActionPerformed(java.awt.event.ActionEvent evt)  {
        //GEN-FIRST:event_openButtonActionPerformed
      // TODO add your handling code here:
        FileNameExtensionFilter filter = new
          FileNameExtensionFilter("Text Files Only","txt");
        editorFileChooser.setFileFilter(filter);
        int returnVal = editorFileChooser.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION){
          System.out.println("You chose to open this file: " +
            editorFileChooser.getSelectedFile().getName());
          // wrong!
          //openFileName = editorFileChooser.getSelectedFile().getName();
          //openFile = new File(openFileName);
          // right!
          openFile = editorFileChooser.getSelectedFile();
          try {
            editorTextArea.setPage(openFile.toURI().toURL());
          } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
      }//GEN-LAST:event_openButtonActionPerfor
    }

  • Duplicate text files being created with ~ appended

    Whenever I edit a text file with TextEditor and save it, a duplicate file is created with a ~ appended to the end of the name.
    Example:
    After editing and saving my_file.txt my_file~.txt is also created.
    The result is I get two files with exactly the same contents.
    my_file.txt
    my_file~.txt
    I would really like to stop it from doing this. It clutters up everything. It has done this since I first installed the OS. My file system format is Mac OS Extended (Journaled). Any suggestions?

    I looked through the preferences for TextEditor. I had "Delete the automatic backup file unchecked". I think checking this option will fix the problem.

  • Displaying text file in dreamweaver

    I'm designing a website in MX 2004. I have a main page
    designed in Photoshop and brought into Dreamweaver. Links on left
    side, using HotMap - that works fine. For the coaches, when I click
    on their name, I want a bio to come up in a section in the middle
    of the page. Two problems: first, because it's a text file, there
    is no formatting and it looks terrible. Can I format the text
    inside Dreamweaver? Is there an easier way than using .txt files
    and SSI's?

    Hi,
    The ReportView control is updated with the contents of the Report Object. Inside of the process models, eg. SequentialModel.seq, you will see a step that calls Report.Reset API method to set the report objects contents to a string. Once the Report object has been set, the ReportView control should now contain the information (string) you set the report object to (you may need to call ReportView.UpdateFromExecution method).
    So, to get your custom report into the ReportView control, you should call Report.Reset or Report.Load and load the text file you wish to view. Keep in mind that the Report object belongs to an execution, for which there can be only one report object. So, you will either need to concatenate your report string, or set and reset th
    e report object with the report you wish to view.
    Bob

  • How to display text file in  swing

    hello,
    I have screen where user enters batch number and number.
    when key is pressed a list is displayed on the screen.how to do this and how to relate my actionlistener with the function that generates the list...

    Hi,
    It is simple. Just create a button and add it to the action listener as button.addActionListener(this);
    Your class should extend ActionListener. and also there should be a method named - actionPerformed(ActionEvent avt) in your class
    Now inside this method, just compare the action as:
    if(avt.getSource()==button)
    // in this method, hjust take your file contents and display it on the same window, or create a new Frame here and display it in that window.
    If you want to display the file contents in the same window, then do the following.
    Declare a public JLabel variable for the class and create the JLabel along with the other components as usual but without giving any values. Now in the action part of the button, read the file contents in a string variable, and set the string to the jlabel as folows:
    label.setText(string);
    Hope it helps,
    Cochu.

  • Can I combine two text files into ine with ZEN

    I have to append a really long character string onto an existing txt file.
    I tried to modify the file in ZEN but the app blows up when it runs. Is
    there a way I could concatenate these two txt files together with ZEN
    instead?

    Another option would be to create two environment variables each holding
    1/2 the string. Then use the Text file section to write the two strings
    to the one file.
    Robin Witkop-Staub wrote:
    > oh - good idea...
    >
    > "Anders Gustafsson" <[email protected]> wrote in message
    > news:[email protected]..
    >> Robin Witkop-Staub,
    >>> I have to append a really long character string onto an existing txt
    >>> file.
    >>> I tried to modify the file in ZEN but the app blows up when it runs. Is
    >>> there a way I could concatenate these two txt files together with ZEN
    >>> instead?
    >>>
    >> Spawn a batchfile that concatenates the files, ie copy file1+file2 file3
    >>
    >> - Anders Gustafsson, Engineer, CNE6, ASE
    >> NSC Volunteer Sysop
    >> Pedago, The Aaland Islands (N60 E20)
    >>
    >> Novell does not monitor these forums officially.
    >> Enhancement requests for all Novell products may be made at
    >> http://support.novell.com/enhancement
    >>
    >> Using VA 5.51 build 315 on Windows 2000 build 2195
    >>
    >
    >
    Craig Wilson
    Novell Product Support Forum Sysop
    Master CNE, MCSE 2003, CCN

  • Loading "fixed length" text files in UTF8 with SQL*Loader

    Hi!
    We have a lot of files, we load with SQL*Loader into our database. All Datafiles have fixed length columns, so we use POSITION(pos1, pos2) in the ctl-file. Till now the files were in WE8ISO8859P1 and everything was fine.
    Now the source-system generating the files changes to unicode and the files are in UTF8!
    The SQL-Loader docu says "The start and end arguments to the POSITION parameter are interpreted in bytes, even if character-length semantics are in use in a datafile....."
    As I see this now, there is no way to say "column A starts at "CHARACTER Position pos1" and ends at "Character Position pos2".
    I tested with
    load data
    CHARACTERSET AL32UTF8
    LENGTH SEMANTICS CHARACTER
    replace ...
    in the .ctl file, but when the first character with more than one byte encoding (for example ü ) is in the file, all positions of that record are mixed up.
    Is there a way to load these files in UTF8 without changing the file-definition to a column-seperator?
    Thanks for any hints - charly

    I have not tested this but you should be able to achieve what you want by using LENGTH SEMANTICS CHARACTER and by specifying field lengths (e.g. CHAR(5)) instead of only their positions. You could still use the POSITION(*+n) syntax to skip any separator columns that contain only spaces or tabs.
    If the above does not work, an alternative would be to convert all UTF8 files to UTF16 before loading so that they become fixed-width.
    -- Sergiusz

  • Displaying *.pdf file on browser with servlet

    hi all
    this RAMESH,struggling to display a pdf file on browser from a remote mechine
    earlier i tried with servlet
    response.setContentenType("application/pdf")
    out.println();
    by this i am getting only some data as below
    endobj
    4 0 obj
    <<
    /ProcSet [ /PDF /Text /ImageB ]
    /Font << /Fo0 21 0 R /Fo12 24 0 R /Fo13 27 0 R /Fo16 30 0 R /Fo18 33 0 R /Fo19 36 0 R >>
    >>
    endobj
    For this purpose i have gone thru www.lowagie.com
    and gone thru all examples but i am not getting how to display on browser or at least awt frame
    please requesting all for suggest me some way
    tanks all
    -Ramesh

    are you trying to
    a) create a PDF dynamically
    b) send an existing PDF

  • How to display text file in JSP?

    Hi,
    I am new to servlet/JSP/java programming.
    I have been able to download a file using ftp. I dont know who to display it in JSP.
    Here is my code. Any help will be appreciated...
    <%@ page import="java.util.*" %>
    <%@ page import="java.lang.*" %>
    <%@ page import="java.net.*" %>
    <%@ page import="java.io.*" %>
    <%@ page import="com.dmhistory.*" %>
    <html>
    <head>
    <title>Untitled</title>
    </head>
    <body>
    <%
    byte[] bytes = new byte[4096];
    URL theUrl = new URL("ftp://user:passwd@host/migr/Movers_for_Ora8/BG/logs/FLD-PAC3-20020311.log");
    BufferedInputStream in = new BufferedInputStream(theUrl.openStream());
    BufferedOutputStream outstream = new BufferedOutputStream(new FileOutputStream( new File( "D:/temp/log.txt" )));
    int pos = in.read( bytes );
    while ( pos != -1) {
    outstream.write( bytes, 0, pos );
    pos = in.read( bytes );
    %>
    <%
    in.close();
    %>
    DONE!!!
    </body>
    </html>
    How can i display this downloaded file in the browser?
    I want to display it in the original format i.e which new line and carriage returns...line by line..
    Thanks,

    Hi,
    I finally go it to display. but now I have new problem. The browser shows the text without the /n/r.
    But when I view the source using 'view->source', if see that the text has got proper format with newline and carriage returns.
    Any ideas how to display it correctly in the browser?
    <%
                   URL theUrl = new URL("ftp://user:pwd@host/migr/Movers_for_Ora8/BG/logs/FLD-PAC3-20020311.log");
                   //URL theUrl = new URL("ftp://dbcmaint:[email protected]/migr/Movers_for_Ora8/SNP/logs/SNP-PAC2-20020314.log");
                   URLConnection uc = theUrl.openConnection();
                   InputStream content = uc.getInputStream();
                   BufferedInputStream in = new BufferedInputStream (content);
                   LineNumberReader lnr = new LineNumberReader (new InputStreamReader (in));
                   String tempStr = "";
                   String str = "";
                   while ((tempStr = lnr.readLine()) != null) {
                   str += (tempStr);
                        %>
                        <%=tempStr%>
                        <%tempStr = "";
                        %>
                   <%
                   in.close();
                   lnr.close();
              %>
    Thanks

  • When I try to display .pdf file in browser (with proprietry extension .dnax) I get the error message "A plugin is needed to display this content".

    I am trying to display a .pdf file within Firefox on a Vista PC. I have changed the extension from .pdf to .dnax to differentiate this .pdf file from others. I get an error message as above.
    The file is displayed using Firefox on another PC with a Linux OS without problem.
    Any advice out there?

    Firefox typically judges the nature of a document or download based on the content-type header send by the web server. Usually a server has a catalog associating file extensions with content types. When you choose a new file extension, the server may send the generic "it's some kind of binary file" header ("application/octet-stream") which Firefox will not associate with a particular program.
    Now, when you open a file from the local system, there is no web server, so Firefox may look to the file extension to ascertain the content type. Obviously that is not working in your case. What happens when you want to open the file from My Computer or Windows Explorer? Does Windows have an application assigned to it? If you can associate it with Adobe Reader in Windows, Firefox may be able to pick that up from the Windows registry.

  • How to know a line of text file is ending with line feed or return?

    hi all, i have a program that read log file that generated by other service (apache http server for example), i want to know that each line is ending with "\r", "\n" or "\r\n" so i can skip them in the next time, like this:
    int char_counter=0;
    BufferedReader reader = new BufferedReader(new FileReader(logFileName));
    while((line=reader.readLine())!=null){
           char_counter+=line.length()+x_value;
    }and the next time read the log file, i will skip all the lines that read in previous time.
    BufferedReader reader = new BufferedReader(new FileReader(logFileName));
    reader.skip(char_counter);
    while((line=reader.readLine())!=null){
           char_counter+=line.length()+x_value;
    }with x_value is 1 or 2 depended on line end with "\n" or "\r\n".
    so, how to know which is the char line ending with?
    Edited by: secmask on Feb 21, 2009 5:46 AM

    Alright, the BufferedReader method readLine() reads all text until it finds a \n character. And then next time you call it it will automatically continue from where it left out.
    try this out it should show it as an example
    import java.io.*;
    public class readLineTest {
        static FileOutputStream filename;
        static BufferedReader input;
        public static void main(String[] args)
            try
                filename = new FileOutputStream("logFile.txt", false);
            catch (IOException e)
                //blank
            PrintStream output = new PrintStream(filename);
            output.println("this is the first line");
            output.println("this is the second line");
            output.println("this is the third line");
            try
                input = new BufferedReader(new FileReader("logFile.txt"));
            catch(IOException e)
                //blank
            for(int i = 0; i < 3; i++)
                try
                    System.out.println(input.readLine());
                catch(IOException e)
                    //blank
    }

  • File to Mail with report format

    Hi
    I have a requirement in which I have to send the email to the user and all the information should be present in the email content no attachment.
    I have to pick the xml file for the FTP location and then send the email to the user in the specific format which is mention below.
    FTP.........................XI..........................MAIL (No Attachment)
    Example
    abc.xml
    Output must be in this format
    Original File name.             Original Creation date and time     Customer ID     File level Ack  Name     File level Ack 
    xxxxxxx                                     xxxxxxxxx                                xxxxxx               xxxxx                    xxx     
    xxxxxxx                                     xxxxxxxxx                                xxxxxx               xxxxx                    xxx     
    xxxxxxx                                     xxxxxxxxx                                xxxxxx               xxxxx                    xxx     
    Creation date and time     Total number of trasnsactions     Status code      Error Description
    xxxxxxxxx                            xxxxxx                                         xxxxx          SYNTAX ERROR
    xxxxxxxxx                            xxxxxx                                         xxxxx          SYNTAX ERROR
    xxxxxxxxx                            xxxxxx                                         xxxxx          SYNTAX ERROR
    Can somebody please tell me how to generate the output like that. I am concatenating all the fields but I have to do too many padding to generate the output like that which I think is not the correct way to generate the output.
    Is there any way to generate the required output with UDF or any other way except concat.
    Is there any way I can convert the output in Excel or Word file.
    Thanks,

    Hi Kumar,
    Could you please tell me the complete UDF
    My Requirement is to generate the output in 1 or multi line along with the heading.
    Original File name.      Original Creation date and time     Customer ID     File level Ack Name     File level Ack
    Where ....... represent the values.

Maybe you are looking for

  • Acrobat X update disables Adobe plug-in in Chrome.

    After locally installing Adobe Acrobat X and running the update in our lab environment, the Acrobat plug-in in Google Chrome becomes disabled and requires the user to download the PDF rather then viewing it within the browser window. Since Chrome has

  • Storage / Backup Question

    As this relates to how I work with my files whilst using FCE, I suspect this is probably the right board to post on....here's my question.... I'm starting to produce more and more videos for work - I capture with a small Sony HD camera, import the fi

  • Access Connections - Autostart Programs - Always Twice

    Hi, I'm using AC for automatically starting programs (Outlook, Firefox) in my work environment. It's done by a cmd file that works great. But: It really often happens (maybe always), that the cmd file is beeing executed twice, so I'm seeing two windo

  • Help! need to make flash 5 script work for flash 8

    hey guys, I have a menu bar slider that was created in flash 5 - but of course once I bring into flash 8 the action script ceases to work correctly. its probably very quick fix, but im a bit lost here, tried everything. anyone able to quickly skim ov

  • How I can watch *.avi files on OS9.2.2?

    Can anybody tell me, how I can watch *.avi files on OS9.2.2? I've installed plenty of codecs (DivX, 3ivx) for QuickTime, but have only video WITHOUT sound! Somebody says, that I need AC3... I've tryed install it too, but without result... My system: