Many developers use the toURL() method of the File class to convert a File to a URL. This method however does not handle correctly escaping characters that are illegal in URL’s (such as spaces) and has been deprecated.
To convert a File to a URL you should instead first use the toURI() method to convert the file path to a URI. The URI class has a toURL() method that can then be used to convert the URI to a URL.
File file = new File(path);
URI uri = file.toURI();
URL url = uri.toURL();
// or alternatively in one line
URL url = file.toURI().toURL();
written by objects
\\ tags: convert, file, URI, url
Often you need to read a file line by line. Alternatively sometimes you want to read text word by word (for example to count the occurrence of different words). The Scanner classes next() method can be used for this as shown in the following example.
Scanner input = new Scanner(file);
while(input.hasNext()) {
String word = input.next();
}
written by objects
\\ tags: file, parse, Scanner, text, word
The Desktop class was added in Java 6 to handle launching associated applications on the native desktop.
Following shows how to print a file with the associated native printing facility.
File file = new File("/tmp/file.txt");
Desktop desktop = Desktop.getDesktop();
desktop.print(file);
written by objects
\\ tags: desktop, file, native, print, printing
Recent Comments