java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to print a file using the default registered application?

The example code below show you how to print a file using the default registered application's print command for the corresponding file type. To do the printing we call the Desktop.print(File file) method.

Running the program on Windows operating system will open for instance a notepad.exe and print the data.txt file.

package com.javacoderanch.example.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();
        }
    }
}