开发者

How to get the name of a File that is in a Scanner Object in java?

Hello: I was given a Scanner that is a File. Something like this:

Scanner theScan = new Scanner(new File("name.file"));

I was wondering if there 开发者_StackOverflow中文版is a way to get the name of the file from the Scanner object. I tried:

theScan.getName();

but that just works for File objects. Thanks for your input.


The first thing the Scanner(File) constructor does is to call another constructor, like this:

this((ReadableByteChannel)(new FileInputStream(source).getChannel()));

so once the scanner has been constructed, there is no way to recover which file, and thus which filename, a scanner is reading from.

You'll simply have to keep track of this yourself on the outside. You could for instance encapsulate this into a FileScanner which extends Scanner but saves the file used when constructing it in a field.


API is your friend

A scanner can read text from any object which implements the Readable interface. If an invocation of the underlying readable's Readable.read(java.nio.CharBuffer) method throws an IOException then the scanner assumes that the end of the input has been reached. The most recent IOException thrown by the underlying readable can be retrieved via the ioException() method.

For example, here are some of them:

    Scanner sc1 = new Scanner("some string");
    Scanner sc2 = new Scanner(System.in);

It would not make any sense asking: from what file the input comes from.

Fix

Encapsulating file and scanner in the Filescanner instance. Example:

public static class FileScanner {
    private final Scanner _sc;
    private final File _file;
    public Scanner get_sc() {return _sc;}
    public File get_file() {return _file;}

    public FileScanner(File f) throws 
           FileNotFoundException, NullPointerException  {
        super();
        this._sc = new Scanner(f);
        this._file = f;
    }
}

In this case FileScanner is aware of the file existence. Don't forget to call fs.get_sc().close();, when you are done using the scanner.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜