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 get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024
The code above did not work on debian linux. Do you have any suggestion to make it work?