How do I print a file using the default registered application?

The example code below shows you how to print a file using the default registered application’s print command for the corresponding file type. As an example, on Windows notepad.exe is the default application for printing a .txt file.

To print a file using the default registered application we call the java.awt.Desktop.print(File) method. The print() method takes a parameter of File, which is the reference to a file to be printed. The code snippet below, when run on Windows, will open notepad.exe and print the data.txt file.

package org.kodejava.awt;

import java.awt.*;
import java.io.File;
import java.io.IOException;

public class RunningDefaultAppPrint {
    public static void main(String[] args) {
        File file = new File("data.txt");
        try {
            Desktop desktop = Desktop.getDesktop();

            // Prints a file with the native desktop printing facility, 
            // using the associated application's print command.
            desktop.print(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Wayan

1 Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.