How do Print TXT file in JAVA...?

Dear sir,
i have a program for printing txt file.... i tried below program..
1. This code executed without exception... but its not printing.... when i saw print buffer, file is add but not printing
2. Please help me out.... or give me some clue.... where i doing wrong....?
Note:- am trying remote printing
          try {
               FileInputStream fin = new FileInputStream(".\\file\\down.txt");
               // set up attributes set
               PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
               pras.add(new Copies(1)); // number of copies
               // find the priner service
               PrintService pss = PrintServiceLookup.lookupDefaultPrintService();
               if (pss == null)
                    throw new RuntimeException("No printer services available.");
               PrintService ps = pss;
               System.out.println("Printing to " + ps);
               // create print job
               DocPrintJob job = ps.createPrintJob();
               // print data
               Doc doc = new SimpleDoc(fin, DocFlavor.INPUT_STREAM.AUTOSENSE, null);
               // print it
               job.print(doc, pras);
               // close file
               fin.close();
          } catch (IOException ie) {
               ie.printStackTrace();
          } catch (PrintException pe) {
               pe.printStackTrace();
          }Thank you
boss134

Hi ,
i m asking if you got a solution for your problem ;
i need solution to the same problem
thx in advance

Similar Messages

  • How to print PDF files using java print API

    Hi,
    I was goign throw lot of discusion and reading lot of forums related to print pdf files using java api. but nothing seems to be working for me. Can any one tell me how to print pdf files using java api.
    Thanks in advance

    Mike,
    Can't seem to get hold of the example described in your reply below. If you could let us have the URL to get then it would be great.
    My GUI application creates a pdf document which I need to print. I want to achieve this using the standard Java class PrinterJob (no 3rd party APIs I'm afraid, commercial restraints etc ..). I had a stab at it using the following code. When executed I get the pretty printer dialog then when I click ok to print, nothing happens!
    boolean showPrintDialog=true;
    PrinterJob printJob = PrinterJob.getPrinterJob ();
    printJob.setJobName ("Contract.pdf");
    try {
    if (showPrintDialog) {
    if (printJob.printDialog()) {
    printJob.print();
    else
    printJob.print ();
    } catch (Exception PrintException) {
                   PrintException.printStackTrace();
    Thank you and a happy new year.
    Cheers,
    Chris

  • How to print  Excel file in java?

    Hi, all
    I had written a program to generate a Report with Excel in java using the jexcelapi_2_5_7 . But I don't know how to print it in java program. It seems that java print Service don�t support Excel flavor. How should I do? It will be a great appreciate for me if anyone could help me.
    Regards
    David

    Hi ,
    i m asking if you got a solution for your problem ;
    i need solution to the same problem
    thx in advance

  • How to print PDF file from java application?

    Hi,
    I have a java application that needs to print an PDF files. Could any one provide me links to tutorial/sample codes for doing this?

    http://onesearch.sun.com/search/onesearch/index.jsp?qt=print+pdf+files&subCat=&site=dev&qp=&chooseCat=javaall&col=developer-forums

  • Printing TXT files with java

    Hi !!
    I�m trying to send the content of a .txt file to the default printer whith the next code; I read the file, and this method accept a String with the content I must print.
    // I�ve read the code in this forum, and I only made little changes....
    public void PrintFileString(String fileContent){
    DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
    PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
    // getting PrintService
    PrintService service = PrintServiceLookup.lookupDefaultPrintService();
    if (service != null){
    System.out.println("Default Printer: " + service.getName());
    // Creating DocPrintJob
    DocPrintJob job = service.createPrintJob();
    try{
    // String to InputStream
    ByteArrayInputStream bais = new ByteArrayInputStream(fichero.getBytes());
    Doc doc = new SimpleDoc(bais,flavor,null);
    job.print(doc,aset);
    catch(Exception a){
    System.out.println(a + "error");
    I can print, in the default printer, but I need to change properties of printed document, like orientation, margins, number of copies, etc....
    Can I do it ??
    Really Thanks

    Please, help !!!
    I need to print a file in landscape mode.
    My code is:
    public class BasicPrint {
        public static void main(String[] args) {
            try {
                // Open the  file
                InputStream is = new BufferedInputStream(
                    new FileInputStream("c:\\diego.txt"));
                // Find the default service
                DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
                PrintService service = PrintServiceLookup.lookupDefaultPrintService();
                // put landscape mode
                PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
                aset.add(OrientationRequested.LANDSCAPE);
                // Create the print job
                DocPrintJob job = service.createPrintJob();
                Doc doc = new SimpleDoc(is, flavor, null);
                try {
              job.print(doc, aset);
             } catch (PrintException e1) {
              e1.printStackTrace();
                // It is now safe to close the input stream
                is.close();
            } catch (IOException e) {
    }The text always is printed in the default orientation (portrait)
    I�ve tried with an image file (gif) changing the lines
      // Open the  file
      InputStream is = new BufferedInputStream(
                    new FileInputStream("c:\\diego.txt"));
      // Find the default service
                DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;by
      // Open the  file
      InputStream is = new BufferedInputStream(
                    new FileInputStream("c:\\image.gif"));
      // Find the default service
                DocFlavor flavor = DocFlavor.INPUT_STREAM.GIF;and works fine !!!
    but not with text. Why ???
    The line
    aset.add(new Copies(2));
    to print 2 copies, don�t work.
    Please, some help ???

  • How do i search for a string in a txt file using java??

    How do i search for a string in a txt file using java??
    could you please help thanks
    J

    Regular expressinos work just fine, especially when
    searching for patterns. But they seem to be impying
    it's a specific group of characters they're looking
    for, and indexOf() is much faster than a regex.If he's reading from a file, the I/O time will likely swamp any performance hit that regex introduces. I think contains() (or indexOf() if he's not on 5.0 yet) is preferable to regex just because it's simpler. (And in the case of contains(), the name makes for a very clear, direct mapping between your intent and the code that realizes it.)

  • How to compare two files in java & uncommon text should print in text file.

    Hi,
    Can any one help me to write Core java program for this.
    How to compare two files in java & uncommon text should print in other text file.
    thanks
    Sam

    Hi All,
    i m comparing two HTML file.. thats why i am getting problem..
    import java.io.BufferedReader;
    import java.io.FileReader;
    public class textmatch{
    public static void main(String[] argv)
    throws Exception{
    BufferedReader fh =new BufferedReader(new FileReader("internal.html"),1024);
    BufferedReader sh = new BufferedReader(new FileReader("external.html"),1024);
    String s;
    String y;
    while ((s=fh.readLine())!=null)
    if ( s.equals(y=sh.readLine()) ){    
    System.out.println(s + " " + y); //REMOVE THIS PRINTLN STATEMENT IF YOU JUST WANT TO SHOW THE SIMILARITIES
    sh.close();
    fh.close(); }
    thanks
    Sam

  • How to compare two files in Java & uncommon text should print in Diff text

    Hi All,
    can any one help me to write a java program..
    How to compare two files in Java & uncommon text should print in Diff text file..
    Thanks
    Sam

    Hi All,
    i m comparing two HTML file.. thats why i am getting problem..
    import java.io.BufferedReader;
    import java.io.FileReader;
    public class textmatch{
    public static void main(String[] argv)
    throws Exception{
    BufferedReader fh =new BufferedReader(new FileReader("internal.html"),1024);
    BufferedReader sh = new BufferedReader(new FileReader("external.html"),1024);
    String s;
    String y;
    while ((s=fh.readLine())!=null)
    if ( s.equals(y=sh.readLine()) ){    
    System.out.println(s + " " + y); //REMOVE THIS PRINTLN STATEMENT IF YOU JUST WANT TO SHOW THE SIMILARITIES
    sh.close();
    fh.close(); }
    thanks
    Sam

  • How to store a data on txt file through java program

    that means i want a coding for write data on txt file using java program.that storing data is stored like this formate,
    sathees
    krishnan
    rama
    suresh
    Stored on one by one. not like this
    sathees krishnan rama suresh.........

    import java.io.*;
    import org.w3c.dom.Document;
    import org.w3c.dom.*;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.DocumentBuilder;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    public class rsk1{
    public static void main (String argv []){
    try {
    String sr[] = new String[100];
                   String s1=" ";
                   int j=0;
                   DataInputStream in = new DataInputStream(System.in);
                   OutputStream f1 = new FileOutputStream("file1.txt");
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    Document doc = docBuilder.parse (new File("book.xml"));
    // normalize text representation
    doc.getDocumentElement ().normalize ();
    System.out.println ("Root element of the doc is " +
    doc.getDocumentElement().getNodeName());
    NodeList listOfPersons = doc.getElementsByTagName("person");
    int totalPersons = listOfPersons.getLength();
    System.out.println("Total no of people : " + totalPersons);
    for(int s=0; s<listOfPersons.getLength() ; s++){
    Node firstPersonNode = listOfPersons.item(s);
    if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE){
    Element firstPersonElement = (Element)firstPersonNode;
    NodeList firstNameList = firstPersonElement.getElementsByTagName("first");
    Element firstNameElement = (Element)firstNameList.item(0);
    NodeList textFNList = firstNameElement.getChildNodes();
    sr[++j]=((Node)textFNList.item(0)).getNodeValue().trim();
    NodeList lastNameList = firstPersonElement.getElementsByTagName("last");
    Element lastNameElement = (Element)lastNameList.item(0);
    NodeList textLNList = lastNameElement.getChildNodes();
    sr[++j]=((Node)textLNList.item(0)).getNodeValue().trim();
    NodeList ageList = firstPersonElement.getElementsByTagName("age");
    Element ageElement = (Element)ageList.item(0);
    NodeList textAgeList = ageElement.getChildNodes();
    sr[++j]=((Node)textAgeList.item(0)).getNodeValue().trim();
    NodeList stuList = firstPersonElement.getElementsByTagName("stu");
    Element stuElement = (Element)stuList.item(0);
    NodeList textstuList = stuElement.getChildNodes();
    sr[++j]=((Node)textstuList.item(0)).getNodeValue().trim();
    }//end of if clause
    }//end of for loop with s var
    System.out.println("Process completed");
    for(int i=1;i<=j;i++)
                   byte buf[] = sr.getBytes();
                                       byte buf1[] = s1.getBytes();
         f1.write(buf);
                                       f1.write(buf1);
    f1.close();
    }catch (SAXParseException err) {
    System.out.println ("** Parsing error" + ", line "
    + err.getLineNumber () + ", uri " + err.getSystemId ());
    System.out.println(" " + err.getMessage ());
    }catch (SAXException e) {
    Exception x = e.getException ();
    ((x == null) ? e : x).printStackTrace ();
    }catch (Throwable t) {
    t.printStackTrace ();
    }//end of main

  • How to print *.PRN file without print Dialog from Java

    hi friends
    I need to print *.PRN file from java code.*
    I need to print directely without open printer dialog box when i select .PRN file then it should able to direct print to default printer.
    Here is the Dos command to directely print the PRN file
    COPY C:\\PrintFile.prn /B \\java103\\HPLaserJ
    (source: http://filext.com/faq/print_from_prn_file.php)
    i try to run that dos command through Process p = Runtime.getRuntime().exec("COPY C:\\PrintFile.prn /B \\java103\\HPLaserJ");
    But is show that
    Here is the LOG of ERROR
    \\java103\HP LaserJet M1120 MFP
    java.io.IOException: Cannot run program "COPY": CreateProcess error=2, The system cannot find the file specified
         at java.lang.ProcessBuilder.start(Unknown Source)
         at java.lang.Runtime.exec(Unknown Source)
         at java.lang.Runtime.exec(Unknown Source)
         at java.lang.Runtime.exec(Unknown Source)
         at Print2Printer.GetDefaultPrinter.main(GetDefaultPrinter.java:17)
    Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
         at java.lang.ProcessImpl.create(Native Method)
         at java.lang.ProcessImpl.<init>(Unknown Source)
         at java.lang.ProcessImpl.start(Unknown Source)
         ... 5 more
    Here is the Source
    import java.io.IOException;
    import javax.print.PrintService;
    import javax.print.PrintServiceLookup;
    public class GetDefaultPrinter {
         public static void main(String args[]){
              PrintService printer = PrintServiceLookup.lookupDefaultPrintService();
              System.out.println(printer.getName());
              try {
                   Process p = Runtime.getRuntime().exec("COPY C:\\PrintFile.prn /B \\java103\\HPLaserJ");
                   System.out.println(p);
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();

    you need to specify which program you want to execute in Runtime.getRuntime().exec(). So try this one
    try {
    Process p = Runtime.getRuntime().exec("cmd.exe COPY C:\\PrintFile.prn /B \\java103\\HPLaserJ");
    System.out.println(p);
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

  • How to call external files from java?

    How to call external files in java. For example how to call a *.pdf file to open in its default editor(say Acrobat), or a *.html file to open in the default browser or a *.txt file in a notepad etc..,
    In my program i have *.chm (Compiled Windows HTML Help) help file. how to open it in its default editor it?

    Jayarathina_Madharasan wrote:
    no one answered my questionHi what wrong did i do...basically insulted all the volunteers here who took the time to consider your question and try to offer you help. Other than that, you did nothing wrong.
    From JavaRanch :
    And even if an answer doesn't solve your problem, even if it should totally miss the point - the best thing to do to motivate others to continue trying to help you is showing respect and gratitude for the investment of time that was put into dealing with your issue.
    Edited by: Encephalopathic on Apr 14, 2008 10:01 AM

  • Problem with printing txt file

    I have a problem with printing txt file. My code looks like :
    String filename = something.txt";
    DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
    PrintService[] services = PrintServiceLookup.lookupPrintServices(
              flavor, null);
    PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
    pras.add(PrintQuality.DRAFT);
    pras.add(new Copies(1));
    pras.add(MediaSizeName.ISO_A4);
    pras.add(Sides.ONE_SIDED);
    pras.add(Chromaticity.MONOCHROME);
    PrintService service = ServiceUI.printDialog(null, 200, 200,
              services, services[0],
              null,
              pras);
    if (service != null)
    try
    DocPrintJob job = service.createPrintJob();
    FileInputStream fis = new FileInputStream(filename);
    DocAttributeSet das = new HashDocAttributeSet();
    Doc doc = new SimpleDoc(fis, flavor, das);
    job.print(doc, pras);
    Thread.sleep(10000);
    catch(FileNotFoundException e)
    catch(PrintException e1)
    catch(InterruptedException e2)
    It doesn't work :(
    What is my purpose: I would like to print .txt file but I would like to get PrintDialog where I can choose PrintQuality, Chromaticity etc. I found also that I should use DocFlavor.INPUT_STREAM.TEXT_PLAIN_HOST but I don't know how.
    I will be very gratefull for help :)

    I tested it on 3 printers (different models of hp). 2 of them don't give me any error but when it started print priter stoped (just as it dosesn't have a paper), but 1 of them doesn't react (there were no errors), i thought tahat something was wrong with printers but when I change DocFlavor.INPUT_STREAM.AUTOSENSE to DocFlavor.GIF and filename to dog.gif it works so mybe there is another way to print txt file

  • How to open/read file using Java in Unix?

    Hi Friends,
    Can you please help me out how to open/read file using java in unix os? I have create one text file in "/home/test.txt" in unix environment. How to open the same file & read using java code?
    - Hiren Modi

    http://java.sun.com/docs/books/tutorial/essential/io/index.html

  • How to run SQL files from Java?

    Hi,
    Can someone point me towards a link on how to run sql files in Java? Thanks.
    P.S...if I've been completely blind please go easy on me!

    Sorry forgot the formating code thingy
    public static boolean executeScript(File script, Connection conn){
        boolean success = true;
        success = script.exists();
        if(success){
          DEBUG.print("ES::READING SCRIPT:" + script.getAbsolutePath());
          StringBuffer buffer = new StringBuffer();
          success=readScript(script,buffer);
          if(success){
            try{
              String creationScript = buffer.toString();
              Statement st = conn.createStatement();
              int start = 0;
              int end = 0;
              while (end != -1 && start < creationScript.length()) {
                end = creationScript.indexOf("GO", start);
                if (end != -1) {
                  DEBUG.print(creationScript.substring(start, end));
                  st.executeUpdate(creationScript.substring(start, end));
                  start = end + 2; //2 is the length of "GO"
              st.close();
            }catch(Exception e){
              success=false;
              DEBUG.printStackTrace(e);
        }else{
          DEBUG.print("ES::SCRIPT FILE DOES NOT EXISTS");
          success=false;
        return success;
      public static boolean readScript(File script, StringBuffer buffer){
        boolean success = true;
        DEBUG.print("RS:: reading file :" + script.getAbsolutePath());
        try{
          InputStreamReader isr = new InputStreamReader(new FileInputStream(script),"UTF16");
          int ch;
          while ( (ch = isr.read()) > -1) {
            buffer.append( (char) ch);
          if (isr != null)
            isr.close();
        }catch(Exception e){
          success=false;
          DEBUG.printStackTrace(e);
        return success;
      }

  • How to print a text in java?

    How to print a text in java?

    of corse, i have JTextField in my frame that i want to extract the text and print it on a paper with a printer.

Maybe you are looking for

  • When I try back up my ipod it says error cant back up

    I connected my ipod to itunes and pressed the backup button on it and it started and stoped and said error so i restored it that didnt work reinstaled itunes but still it didnt work please help

  • My iPhone 5 delays texts being received for an hour and sometimes days at a time. What can I do to fix that?

    So I have had the iPhone 5 since the day it came out in September. I have noticed, randomly, it will delay texts from individuals and in group messages. It has delayed for an hour or more, and more than once it has delayed for more than a day. I have

  • Error message on step 1....wizard cannot modify this MSI package

    Using the Adobe Customization Wizard, when I choose File > Copy Package, and enter in the appropriate fields, I am getting this error at the end: And although it looks like it copies the package to the location I specify, I cannot open it (I get the

  • RECORDING WITH BUILT IN MIC

    i am trying to record some vocals using garage band and my built in mic on my macbook but there is a clicker noise produced every time i start the recording, like, click, 2 seconds, click, 2 seconds, click etc. haha. nothing is interfering, i think,

  • Windows 7 - 64 bit- Should I Upgrade?

    Does the new PE version 9 perform better than PE 8? Currently using PE8 ( many projects) and the "new" computer will be arriving with Windows Pro 7 -  64 bit Trying to decide if an upgrade makes sense. Cost is not an issue.