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();
}
}
}
Latest posts by Wayan (see all)
- How do I create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023
The code above did not work on debian linux. Do you have any suggestion to make it work?