Questions on the NIO.2 API
Rémi Forax
forax at univ-mlv.fr
Mon Jan 31 07:57:17 PST 2011
Le 31/01/2011 16:30, Martijn Verburg a écrit :
> Hi all,
>
> I've finally come back to this Chapter and am thinking about the
> various rough code samples I've written (running b127 on Windows XP
> SP3 32bit). My next code sample simply takes the reader through some
> of the file system api in order to explore some of the basics.
>
> import java.io.IOException;
> import java.nio.file.*;
>
> public class Listing_2_1
> {
> public static void main(String[] args) throws IOException
> {
> try (FileSystem fileSystem = FileSystems.getDefault())
> {
> Path timeSheetFile
> = fileSystem.getPath("C:/projects/timesheet.txt");
> Path backupDir = fileSystem.getPath("H:/projects/");
> Path backupFile
> = fileSystem.getPath("H:/projects/timesheet.txt");
>
> timeSheetFile.checkAccess(AccessMode.READ);
> backupDir.checkAccess(AccessMode.WRITE);
>
> FileStore backupFileStore = backupDir.getFileStore();
> if (!backupFileStore.type().equals("NTFS"))
> {
> throw new IOException("Suspicious storage type");
> }
>
> CopyOption copyOptions = StandardCopyOption.REPLACE_EXISTING;
> timeSheetFile.copyTo(backupFile, copyOptions);
> }
> }
> }
>
> The code example is a pretty patsy one, but one gotcha in particular
> was noticed by earlier reviewers.
>
> The FileStore object's type is simply a String as opposed to a
> constant, enum or other defined type. This makes it very hard to rely
> on for decision making (as per the if statement I have above). I
> assume this is a limitation of being able to consistently detect the
> underlying storage type?
Yes, the problem is that the string can be easily misspelled.
I wondering if it worth an API like this:
interface FileStoreType {
public String getName();
}
public enum StandardFileStoreType implements FileStoreType {
EXT3, EXT4, FAT32, NTFS;
...
}
public class FileStoreTypes {
public static FileStoreType getFileStoreType(final String name) {
// StandardFileStoreType.valueOf(name)
// otherwise new FileStoreType() {
// public String getName() {
// return name;
// }
//};
}
}
In that case, the code can be rewrite to:
backupFileStore.type().equals(StandardFileStoreType.NTFS)) { ... }
>
> Thanks again all.
> Martijn
> (@java7developer - twitter)
>
Rémi
More information about the nio-dev
mailing list