yasgur99 yasgur99 - 4 months ago 19
Java Question

Does a file object support all files (keyboards, directories, files, etc.)?

In Linux, everything is a file: keyboards, directories, text files, USB devices, etc.

In java, what would happen if I used a File object to take in something like a keyboard (or anything that isn't your typical "file". Would it work? If not, how come?

If it would work, would I be able to do anything significant with it or are there limitations?


Yes, the Java File class works the same way for all files. It will also work for directories (those will return true for isDirectory) and special files like keyboards and USB devices (those will return false for isFile).

FileReader, FileInputStream, and classes like that will work on regular and special files, but will not work on directories.

As an example, here's a simple program (error handling removed for simplicity) that reads random bytes from the '/dev/random' device and writes them to the audio output at '/dev/dsp'. (It's loud and horrible, mind your ears!)

import java.io.*;

public class Main {
    public static void main(String[] args) throws Exception {
        File random = new File("/dev/random");
        File audio = new File("/dev/dsp");

        InputStream in = new FileInputStream(random);
        OutputStream out = new FileOutputStream(audio);

        while (true) {

Something to keep in mind is that 'special' files like these usually do not allow you to seek, that is, go forwards and backwards in the file. You can't, for example, read what they keyboard will send ten minutes from now.