How to print a text file contents using java.

Using Input and Output streams I can add and retrive the contents to/from text file. But how to send this file contents to the printer or how to print the file.

Example from my code:
   private void printErrorReport()
      PrintJob pjob = getToolkit().getPrintJob(m_frame,null,null);
      if (pjob != null) {
        Graphics pg = pjob.getGraphics();
        if (pg != null) {
          String s = detailsArea.getText();
          printLongString (pjob, pg, s);
          pg.dispose();
        pjob.end();
// Utility method needed
   void printLongString (PrintJob pjob, Graphics pg, String s) {
     int pageNum = 1;
     int linesForThisPage = 0;
     int linesForThisJob = 0;
     // Note: String is immutable so won't change while printing.
     if (!(pg instanceof PrintGraphics)) {
       throw new IllegalArgumentException ("Graphics context not PrintGraphics");
     StringReader sr = new StringReader (s);
     LineNumberReader lnr = new LineNumberReader (sr);
     String nextLine = "       ";
     int pageHeight = pjob.getPageDimension().height;
     pageHeight -= 20;
     Font helv = new Font("Arial", Font.PLAIN, 12);
     //have to set the font to get any output
     pg.setFont (helv);
     FontMetrics fm = pg.getFontMetrics(helv);
     int fontHeight = fm.getHeight();
     int fontDescent = fm.getDescent();
     int curHeight = 0;
     try {
       do {
         nextLine = lnr.readLine();
         if (nextLine != null) {
           if ((curHeight + fontHeight) > pageHeight) {
             // New Page
             System.out.println ("" + linesForThisPage + " lines printed for page " + pageNum);
             pageNum++;
             linesForThisPage = 0;
             pg.dispose();
             pg = pjob.getGraphics();
             if (pg != null) {
               pg.setFont (helv);
             curHeight = 0;
           curHeight += fontHeight;
           if (pg != null) {
             pg.drawString (nextLine, 0, curHeight - fontDescent);
             linesForThisPage++;
             linesForThisJob++;
           } else {
             System.out.println ("pg null");
       } while (nextLine != null);
     } catch (EOFException eof) {
       // Fine, ignore
     } catch (Throwable t) { // Anything else
       t.printStackTrace();
     System.out.println ("" + linesForThisPage + " lines printed for page " + pageNum);
     System.out.println ("pages printed: " + pageNum);
     System.out.println ("total lines printed: " + linesForThisJob);
     }

Similar Messages

  • How to print a text file using Java

    How can I print a text file using Java without converting the output to an image format. Is there anyway I can send the characters in the text file as it is for a print job? I did get a listing doing this ... but that converted the text to an image format before printing....
    THanks,.

    Hi I had to write a print api from scratch, and I did not convert the output to image. Go and read up on the following code. I know there is a Tutorial on Sun about the differant sections of the snippet.
    private void printReport()
         Frame tempFrame = new Frame(getName());
         PrintJob printerJob = Toolkit.getDefaultToolkit().getPrintJob(tempFrame, "Liesltext", null);
         Graphics g = printerJob.getGraphics();
                    //I wrote the method below for calculations
         printBasics(g);
         g.dispose();
         printerJob.end();
    }This alone wont print it you have to do all the calculations in the printBasics method. And as I said I wrote this from scratch and all I did was research first the tutorial and the white papers
    Ciao

  • How to print a text file with long lines?

    I am trying to print a text file which contains many long lines. I find that the long lines are truncated on the printouts. How do I wrap up these long lines? Could you give me some examples?
    Thank you very much!

    Here's an example. The "\n" makes anything after it go to the next line. I hope this helps. Look at the Private void getTable() section.
    import java.awt.*;
    import java.awt.event.*;
    import java.sql.*;
    public class LabNine extends Frame implements ActionListener, WindowListener {
         private TextField txtInfo;
         private List lstInfo;
         private Button btnAddInfo;
         private BorderLayout borderlayout;
         private Connection databaseConnection;
         Statement statement;
         ResultSet resultSet;
    public LabNine( ) {
         super("Lab Nine");
         // addWindowListener to close application
         addWindowListener(this);
         // create layout
         borderlayout = new BorderLayout();
         setLayout(borderlayout);
         // create text field so the file input that is selected will be seen in here
         txtInfo = new TextField();
         txtInfo.setEnabled(false);
         Color color = new Color(255, 136, 183);
         txtInfo.setBackground(color);
         add(txtInfo, BorderLayout.NORTH);
         // create list so the file input can be populated in here
         lstInfo = new List();
         add(lstInfo, BorderLayout.CENTER);
         // create button to add selected input file in the text field
         btnAddInfo = new Button("Add Info");
         btnAddInfo.setBackground(Color.cyan);
         btnAddInfo.setFont(new Font("TimesRoman", Font.BOLD, 16));
         btnAddInfo.addActionListener( this );          
         add(btnAddInfo, BorderLayout.SOUTH);
         // set frame attributes
         setSize(450, 250);
         setResizable( false );
         show();
         // get the table/ get the query
         loadConnection();
         getTable();
    public void actionPerformed(java.awt.event.ActionEvent e) {
         // if add button is pushed then it will check to see if an item was selected.
         // if not, then an error message will be displayed else the selected item will be in the text box
         if ( e.getSource() == btnAddInfo ) {
              if ( lstInfo.getSelectedIndex() == -1 ) {
                   System.out.print( "You have not selected an item" );
              else {
                   txtInfo.setText(( lstInfo.getSelectedItem() ));
    private void getTable() {
         try {
              String query = "SELECT FIRST, LAST, EMAIL FROM Names";
              statement = databaseConnection.createStatement();
              resultSet = statement.executeQuery( query );
              while ( resultSet.next() ) {
                   lstInfo.add( resultSet.getString( "FIRST" ) + " " + resultSet.getString( "LAST") + " " +
                        resultSet.getString( "EMAIL" ) + "\n" );
              statement.close();     
         catch ( Exception e ) {
              System.err.println( e );
    private void loadConnection() {
         // define the data source for the driver
         String sourceURL = "jdbc:odbc:people";
         String username = "";
         String password = "";
         // load the driver
         try {
              // load the drive class
              Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
              // create a connection through the drivermanager
              databaseConnection = DriverManager.getConnection( sourceURL , username, password );     
         catch( ClassNotFoundException cnfe ) {
              System.err.println( cnfe );
         catch( SQLException sqle ) {
              System.err.println( sqle );
    public static void main(java.lang.String[] args) {
         LabNine aLabNine = new LabNine( );
    public void windowActivated(java.awt.event.WindowEvent e) {
    public void windowClosed(java.awt.event.WindowEvent e) {
         // closes the application
         System.exit( 0 );
    public void windowClosing(java.awt.event.WindowEvent e) {
         // closes the application
         System.exit( 0 );

  • How to print the texts retrived by using READ_TEXT fun module in Smartform

    Please tell me how to print the text which is rertrived by using the READ_TEXT function module in smartform.
    I have coded all things in the program lines and in that i am retriveing the long texts.
    I am getting the text lines in my internal table clearly, the thing is that I am not able to pass these lines to the text.
    I have to print the trouble ticket. in that the notes log I have to pass.
    its urgent. Points will be rewarded for any type of clue. whether it will work or not.

    There are a few ways to do it. If you need to take all of the text in the text type, in your SF text element choose "Include Text".
    Populate the fields with the data that corresponds to the text type. It is similar to the interface to the FM "Read_Text.
    Text Name
    Text Obje
    Text ID 
    Language
    Encase any variables with the "&" symbol.
    If you have already coded the call to the FM "READ_TEXT" and loaded the text into an internal table, create a loop and loop through the itab. Inside of the loop create a text element and add a variable in the text element for the field you are looking to output.

  • How to convert a text file content to String in JSP?

    Hi,
    I need to read the content of a text file and convert it into String and display it on to a JSP file.
    But the codings below don't work. Please advise me on how can i display the text file content.
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    File adCheck = new File("list.txt");
    fis = new FileInputStream(adCheck);
    int Length = adCheck.length();
    byte arr[] = new byte[Length];
    int dataRead = 0;
    int totalData = 0;
    while(totalData <Length)
         dataRead = fis.read(arr,totalData,Length);
         totalData += dataRead;
    String Content = new String(arr);//byte array converted to String
    arr = null;

         InputStreamReader in=new InputStreamReader(fis);
          StringWriter out=new StringWriter();
          char[] buffer=new char[8192];
          int sizeRead;
          while ( ( sizeRead=in.read(buffer, 0, 8192) ) != -1 )
            out.write(buffer, 0, sizeRead);
         String content=out.toString();

  • How to print a text file with pagebreak.......

    hi to all,
    i am new in java and i want to do print a text file with page break. that text file is converted from html view page with help of htmlconveter class and i want to set page break in the text file.ASCII 12 is not work properly.its not break a page in proper manner.plz reply soon.

    hi to all,
    i am new in java and i want to do print a text file with page break. that text file is converted from html view page with help of htmlconveter class and i want to set page break in the text file.ASCII 12 is not work properly.its not break a page in proper manner.plz reply soon.

  • How to open a text file without using dialog box

    I can open a file using dialog box but I want to open a file without using any dialog box for writing.
    With the following commands a new file is created.
    File outputFile = new File("outagain.txt");
    FileWriter out = new FileWriter(outputFile);
    I want to open an existing file and put some more text in it using FileWriter or any other object
    rgds,
    Arsalan

    import java.io.*;
    class UReader
        BufferedReader in;
        BufferedReader input;
        String fileName;
        public UReader(String fileName)
            this.fileName = null;
            this.fileName = fileName;
            try
                in = new BufferedReader(new FileReader(fileName));
                input = new BufferedReader(new FileReader("A.b"));
            catch(IOException _ex) { }
        public final String getContent()
            String txt = "";
            try
                while(in.ready())
                    txt = txt + in.readLine();
                    txt = txt + "\n";
                in.close();
                txt.trim();
            catch(IOException _ex) { }
            return txt;
        public final String getLine(int row)
            try
                input = new BufferedReader(new FileReader(fileName));
            catch(IOException _ex) { }
            String txt = null;
            if(row <= getRows()) {
                try
                    for(int i = 0; i < row; i++)
                        txt = input.readLine();
                    input.close();
                catch(IOException _ex) { }
            } else {
                txt = "Index out of Bounds";
            return txt;
        public final int getRows()
            try
                input = new BufferedReader(new FileReader(fileName));
            catch(IOException _ex) { }
            String txt = null;
            int rows = 0;
            try
                while(input.ready())
                    txt = input.readLine();
                    rows++;
                input.close();
            catch(IOException _ex) { }
            return rows;
    import java.io.*;
    import java.util.*;
    class UWriter
        PrintWriter out;
        String fileName;
        String[] txt;
        static int NEW_LINE = 1;
        static int APPEND = 0;
        public UWriter(String s)
            fileName = null;
            txt = null;
            fileName = s;
            try
                out = new PrintWriter(new BufferedWriter(new FileWriter(s, true)));
            catch(IOException ioexception) { }
        public final void addContent(String s, int i)
            int l = 0;
            StringBuffer sb = new StringBuffer(s);
            s.replaceAll("\n\n", "\n###\n");
            StringTokenizer str = new StringTokenizer(s, "\n");
            String token = null;
            while (str.hasMoreTokens()) {
                ++l;
                token = str.nextToken();
            str = new StringTokenizer(s, "\n");
            txt = new String[l];
            int k = 0;
            String test;
            while (str.hasMoreTokens()) {
                test = str.nextToken();
                if (test.equals("###")) test = "";
                txt[k++] = test;
            if(i == 0) {
                try
                    for (int j = 0; j < txt.length; ++j) {
                        out.println(txt[j]);
                    out.close();
                catch(Exception ioexception) { }
            } else {
                try
                    out.println();
                    for (int j = 0; j < txt.length; ++j) {
                        out.println(txt[j]);
                    out.close();
                catch(Exception ioexception1) { }
        public final void writeContent(String s)
            int l = 0;
            s.replaceAll("\n\n", "###");
            StringTokenizer str = new StringTokenizer(s, "\n");
            String token = null;
            while (str.hasMoreTokens()) {
                ++l;
                token = str.nextToken();
            str = new StringTokenizer(s, "\n");
            txt = new String[l];
            int k = 0;
            String test;
            while (str.hasMoreTokens()) {
                test = str.nextToken();
                if (test.equals("###")) test = "";
                txt[k++] = test;
            try
                PrintWriter bufferedwriter = new PrintWriter(new BufferedWriter(new FileWriter(fileName, false)));
                for (int j = 0; j < txt.length; ++j) {
                    bufferedwriter.println(txt[j]);
                bufferedwriter.close();
            catch(IOException ioexception) { }
    }Maybe they are not the best codes, i wrote them a long time ago, so dont ask why i did anything wierd. :D
    But anyway it works.

  • How to print list of file contents of a HDD

    Hi Everyone!
    (Sorry for using a quote---The copy/paste  from my old Text Editor does not work here.... why not?  Only if I am doing a quote)
    I have a Mac G4 (yes) with Tiger 10.4.11 (yes still)  and I have two backup drives.... They should be evenly "filled" but there is over 26 GB difference so that one is going to be running out of space sooner than I want it to.  I have 100's of files... I need some program that works under Tiger to either:
    1. Print the contents of the HDD (the file names/sizes, etc---there is something that does this in Windows, why not Mac?).
    or
    2.  A program that compares the contents automatically between the two HDD's.  Again I have used one on PC's but its really old and company no longer makes it for PC's.  Is there one for Mac? I have no idea how to express it to look it up.  (I never have both of the HDD's all hooked up by Firewire at same time---afraid of overloading old Mac).... so only if there is a program that does this working under Tiger would I then come back here to ask a question for how to get the two drives hooked up to compare the contents and find out what is taking up extra space.
    Mostly the drives have iPhoto items in it so it could be simply a double-entered iPhoto Roll/Album---but never thinking I'd have to compare them---most of the titles begin the same exact way---too difficult to go over unless I can cross off a printed sheet to compare the two drives---or have a computer do that for me.
    Any suggestions? 
    Thanks for reading me!
    Mac_Help

    Tex-Edit Plus
    Universal Version 4.10.2
    Mac OS 10.4 thru 10.10
    File Size: 10703K
    Tex-Edit Plus
    PPC Version 4.9.8
    Mac OS 10.1 thru 10.3
    File Size: 3970K
    Tex-Edit Plus
    Classic Version 4.1.3
    Mac OS 7 thru 9
    File Size: 5294K
    Tex-Edit
    Legacy Version 2.7.2
    Mac OS 6
    File Size: 257K
    Tex-Edit Plus (beta)
    Pre-release Version 4.10.3 b2
    Mac OS 10.4 thru 10.10
    File Size: 10705K
    Hi BDAqua!
    Thanks for the links!  I'll take both of them!  (If they fit in my old HD)
    Explaining a bit more----I'm using a "PC" to write these questions (yes I have a bunch more) about the old Tiger Mac 10.4.11 G4.
    I only have working TenFourFox7450 and OmniWeb as my only two ways to get online now.  Very slow.  Very limited windows I can open at once to compare or research things, so I'm back on the PC to do all that and copy and paste quotes here for you. Seems once I pass the first question, the only thing Quote does is quote your message---I managed to cheat a bit and got what I wanted to copy from the Tex-Edit page to show up instead..
    You recommended that I choose Tex-Edit Plus PPC Version 4.9.8---but as you see above that is only for 10.1 to 10.3 versions..... is there some reason why the  Tex-Edit Plus (Beta) above is bad for me?  It says 10.4 or higher.
    Or why not use the "Universal" Tex-Edit Plus?  Seems that covers 10.4?
    I got both TextWrangler and Tex-Edit Plus "Universal" Edition to work on the Mac!
    Page numbers on the Tex-Edit!  Wow!
    Thanks!
    Also (saving address for later)    that page has Eliza on it.. which I had long time ago.... but lost somewhere among all the other programs. So thanks for showing me I can find and add it in later on when I get more space on HDD
    I'll type now my reply to your earlier message/posting!
    Mac_Help

  • How to load a text file in a Java swings application

    hi,
    I am trying to retrieve a Java code(or say any text from an existing file) and display it in a swing application.
    I am not able to do so.
    Please help me.

    public String readFile(File f){
              try {
                   BufferedReader read = new BufferedReader(new FileReader(f));
                   String line = read.readLine();
                   String total = "";
                   while(line != null){
              //          System.out.println(line);
                        total += line;
                        line = read.readLine();
                   read.close();
                   return total;
              } catch (Exception e){
                   e.printStackTrace();
              return "";
         }that will read a file into a string, i hope you can figure out the rest

  • How to read text file content in portal application?

    Hi,
    How do we read text file content in portal application?
    Can anyone forward the code to do do?
    Regards,
    Anagha

    Check the code below. This help you to know how to read the text file content line by line. You can display as you require.
    IUser user = WPUMFactory.getServiceUserFactory().getServiceUser("cmadmin_service");
    IResourceContext resourceContext = new ResourceContext(user);
    String filePath = "/documents/....";
    RID rid = RID.getRID(filePath);
    IResource resource = ResourceFactory.getInstance().getResource(rid,resourceContext);
    InputStream inputStream = resource.getContent().getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    String line = reader.readLine();
    while(line!=null) {
          line = reader.readLine();
         //You can append in string buffer to get file content as string object//
    Regards,
    Yoga

  • Reading word doc contents using java

    hi
    can u tell me how to read the word doc contents using java and print it
    sameer

    HDF (Horrible Document Format)
    HDF is our port of the Microsoft Word 97 file format to pure Java. It supports read and write capability. Please see the HDF project page for more information. This component is in the early stages of design. Jump in!
    LOL :)

  • How to send a text file to a printer?

    Hi, I'm in dark on how to send a text file to a printer through Java Stored Procedure.
    Here are what I tried so far (OS: win 2000, Oracle: 817 or 9i2):
    1, Enable DOS command in Java Stored Proc. and try to send PRINT command there:
    public static String Run(String Command){
    try{
    Runtime.getRuntime().exec(Command);
    System.out.println("Command: " + Command);
    return("0");
    catch (Exception e){
    System.out.println("Error running command: " + Command +
    "\n" + e.getMessage());
    return(e.getMessage());
    public static void main(String args[]){
    if (args.length == 1)
    Run("print /D:\\\\enterprise\\john " + args[0]);
    else System.out.println("Usage: java OSCommand filename");
    PL/SQL wrapper:
    CREATE OR REPLACE FUNCTION OSCommand_Run(p1 IN VARCHAR2) RETURN VARCHAR2 AUTHID CURRENT_USER AS LANGUAGE JAVA NAME 'OSCommand.Run(java.lang.String) return java.lang.String';
    SQL command:
    //print /D:\\machine\printer test.txt
    I loaded the Java Stored Procedure into SYSDBS account, it failed silently, even though piece of code works fine in external JVM.
    2, Use filePrinter:
    public static String print(String printString) {
    try{
    String printerUNC = "\\\\machine\\printer";
    FileWriter fw = new FileWriter(printerUNC);
    PrintWriter pw = new PrintWriter(fw);
    pw.println(printString);
    fw.close();
    return "OK";
    }catch(Exception e){
    e.printStackTrace();
    return "Exception: " + e.getMessage();
    public static void main(String[] args) {
    try{
    String printerUNC = "\\\\machine\\printer";
    String printString = "Hello World";
    FileWriter fw = new FileWriter(printerUNC);
    PrintWriter pw = new PrintWriter(fw);
    pw.println(printString);
    fw.close();
    }catch(Exception e){e.printStackTrace();}
    I loaded it into SYSDBS too, and tried with this:
    SQL> select MY_PRINT.PRINT('HELLO from Oracle') from dual;
    MY_PRINT.PRINT('HELLOFROMORACLE')
    Exception: No such file or directory
    SQL> show user
    USER is "SYS"
    It works in external JVM too.
    What's wrong with this?
    Thanks for any help in advance,
    Charles

    Avi:
    Thanks for your response!
    I put the java code in SYS, 'cause I assume that account has max privilege. If the test is successful, I will move that to some user schema and then to deal with those privilege settings... But I'm unlucky.
    I checked Ask Tom, this is what I got from http://asktom.oracle.com/pls/ask/f?p=4950:8:1619723::NO::F4950_P8_DISPLAYID,F4950_P8_CRITERIA:38012348052,%7Bprinter%7D:
    ... Print file from PL/SQL ...
    If you are using Oracle8i, release 8.1 -- much can be done with Java. java
    would be able to print directly from the server.
    Looks like using Java to print out file is better than PL/SQL. But there's no more hint there! And, no new question can be asked there today either...
    I'm wondering whether we can create a socket to a printer and send the characters there directly... Anyone has experience on this?
    Thanks for all the help in advance,
    Charles

  • How to create a text file or XML file  and add content through  code into it...

    Hi Everyone,
    How to create a text file and add content through the code to the text file eform javascript ......orelse can we create a text file in life cycle designer...
    Else say how to create a new XML file through the code and how some content like Example "Hello World".

    You can create a text file as a file attachment (data object) using the doc.createDataObject and doc.setDataObjectContents:
    http://livedocs.adobe.com/acrobat_sdk/9.1/Acrobat9_1_HTMLHelp/JS_API_AcroJS.88.450.html
    http://livedocs.adobe.com/acrobat_sdk/9.1/Acrobat9_1_HTMLHelp/JS_API_AcroJS.88.528.html
    You can then export the file with the doc.exportDataObject method:
    http://livedocs.adobe.com/acrobat_sdk/9.1/Acrobat9_1_HTMLHelp/JS_API_AcroJS.88.463.html
    This won't work with Reader if it hasn't been given the file attachment usage right with LiveCycle Reader Extensions.

  • How to print a HTML file in browser look using DocPrintJob

    Hello guys,
    Does anyone know how to print HTML output/file into browser look?
    I'm using DocPrintJob and the DocFlavor set to DocFlavor.INPUT_STREAM.AUTOSENSE.
    posted below is my code :
    public class BasicPrint {
        public static void main(String[] args) {
            try {
                // Open the image file
                String testData = "C:/new_page_1.html";
                InputStream is = new BufferedInputStream(new FileInputStream(testData));
                DocFlavor flavor =  DocFlavor.INPUT_STREAM.AUTOSENSE;
                // Find the default service
                PrintService service = PrintServiceLookup.lookupDefaultPrintService();
                System.out.println(service);
                // Create the print job
                DocPrintJob job = service.createPrintJob();
                Doc doc= new SimpleDoc(is, flavor, null);
                // Monitor print job events; for the implementation of PrintJobWatcher,
                // see e702 Determining When a Print Job Has Finished
                PrintJobWatcher pjDone = new PrintJobWatcher(job);
                // Print it
                job.print(doc, null);
                // Wait for the print job to be done
                pjDone.waitForDone();
                // It is now safe to close the input stream
                is.close();
            } catch (PrintException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
        static class PrintJobWatcher {
            // true iff it is safe to close the print job's input stream
            boolean done = false;
            PrintJobWatcher(DocPrintJob job) {
                // Add a listener to the print job
                job.addPrintJobListener(new PrintJobAdapter() {
                    public void printJobCanceled(PrintJobEvent pje) {
                        allDone();
                    public void printJobCompleted(PrintJobEvent pje) {
                        allDone();
                    public void printJobFailed(PrintJobEvent pje) {
                        allDone();
                    public void printJobNoMoreEvents(PrintJobEvent pje) {
                        allDone();
                    void allDone() {
                        synchronized (PrintJobWatcher.this) {
                            done = true;
                            PrintJobWatcher.this.notify();
            public synchronized void waitForDone() {
                try {
                    while (!done) {
                        wait();
                } catch (InterruptedException e) {
    }the printed ouput for this code will be look like this
    <html>
    <body>
    <div style="page-break-after:'always';
                background-color:#EEEEEE;
                width:400;
                height:70">
         testPrint</div>
    ABCDEFGHIJK<p>
     </p>
    </body>
    </html>however, the output that i want is the HTML in browser look not HTML code itself.
    i've tried to change the DocFlavor into any TEXT_HTML type but it gives error:
    sun.print.PrintJobFlavorException: invalid flavor if you guys has any idea or solution, can you share with me... already search in Google but still not found any solution
    Thanks in advanced.

    hi,
    do the following
    URL url = null;
    try
         url = new URL("http://www.xyz.com");
    catch (MalformedURLException e)
          System.out.println("URL not correct " + e.toString());
    if (url != null)
           getAppletContext().showDocument(url,"_blank"); //shows the page in a new unnamed top level browser instance.
    }hope that helpz
    cheerz
    ynkrish

  • 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.

Maybe you are looking for