Files in Java
Java has a class called File, which actually represents not a file you can read or write, but rather a filename. Using this class is highly recommended instead of simple strings, because it makes your file naming operating-system independent. You can easily find out wether a filename is relative or absolute, it strips trailing slashes on directory names and replaces the path separator char with the correct one for the OS.
Some useful methods:
File getAbsoluteFile() Returns the absolute form of this abstract pathname.
String getAbsolutePath() Returns the absolute pathname string of this abstract pathname.
Most of the time you do not need any fancy stuff. You just want to open a file, and then read it, one line at a time. Or write to it, with println. What you call file handles in other languages, in Java its Streams. This is the way to do it:
InputStreams and OutputStreams
These are inconvenient, old stuff. Their incarnations FileInputStream and FileOutputStream read an unstructured flow of bytes. To use them with characters you have to wrap them in InputStreamReader and OutputStreamWriter. You only would need this cumbersome technique to specify a character-encoding different from the Standard used by the normal Readers/Writers.
Readers and Writers
These new, abstract classes we used in their incarnations for files, FileReader and FileWriter. They read an unstructered flow of characters. They eat a String or a File Object to find their target in the Operating System - but File also uses a String to connect to its target of course. More on that later. Readers and Writers are better for human-readable data, but still not optimal. For ease of use, we wrapped them in BufferedReader and PrintWriter respectively.
Like the name suggests contains a buffer for the data read and thus makes it possible to have methods like readline(), which - you guessed it - reads a line of data from the file (assuming it's standard encoded), and returns null if there are no more lines to read. The BufferedReader can be seen as a handle to the file we want to read from.
This is the opposite to BufferedReader, a Wrapper Class that represents a file handle for writing standard-encoded chars to some Stream or Writer and has a bunch of useful methods like print(), println(). Actually the well-known out-Stream of Sytem.out.print() uses this.
In all of this we didn't mention the File class. It takes some String and constructs a File Object from it,which can be used as an Argument to various other Classes like Readers/Writers, and which has a lot of other useful methods which check properties of the file or do Operating System work like
This contains the first character of the environment variable file.separator, which should be the file separator (/ on Unix, \ on Windows). You can use it to keep your code platform independend (and you should!).
|All times are GMT +5.5. The time now is 20:57.|