Java Reference
In-Depth Information
boolean createdOK = f . createNewFile ();
g
d O
e
// Temporary file handling
File tmp = File . createTempFile ( "my-tmp" , ".tmp" );
tmp . deleteOnExit ();
// Directory handling
boolean createdDir = dir . mkdir ();
String [] fileNames = dir . list ();
File [] files = dir . listFiles ();
The File class also has a few methods on it that aren't a perfect fit for the abstrac‐
tion. They largely involve interrogating the filesystem (e.g., inquiring about avail‐
able free space):
long free , total , usable ;
free = f . getFreeSpace ();
total = f . getTotalSpace ();
usable = f . getUsableSpace ();
File [] roots = File . listRoots (); // all available Filesystem roots
Streams
The I/O stream abstraction (not to be confused with the streams that are used when
dealing with the Java 8 Collection APIs) was present in Java 1.0, as a way of dealing
with sequential streams of bytes from disks or other sources.
The core of this API is a pair of abstract classes, InputStream and OutputStream .
These are very widely used, and in fact the “standard” input and output streams,
which are called System.in and System.out , are streams of this type. They are pub‐
lic, static fields of the System class, and are often used in even the simplest pro‐
grams:
System . out . println ( "Hello World!" );
Specific subclasses of streams, including FileInputStream , and FileOutputStream
can be used to operate on individual bytes in a file—for example, by counting all the
times ASCII 97 (small letter a ) occurs in a file:
try ( InputStream is = new FileInputStream ( "/Users/ben/cluster.txt" )) {
byte [] buf = new byte [ 4096 ];
int len , count = 0 ;
while (( len = is . read ( buf )) > 0 ) {
for ( int i = 0 ; i < len ; i ++)
if ( buf [ i ] == 97 ) count ++;
}
System . out . println ( "'a's seen: " + count );
} catch ( IOException e ) {
e . printStackTrace ();
}
Search WWH ::




Custom Search