Java: what is the class for the isBinary-method?
I am accustomed to java.io.* and java.util.* but not to the tree:
com.starbase.util
Class FileUtils
java.lang.Object
|
+--com.starbase.util.FileUti开发者_开发百科ls
Source.
So which class should I import to use the isBinary-method? Do I do "import java.lang.Object;" or "import java.lang.Object.com.starbase.util.FileUtils;"?
You would do import com.starbase.util.FileUtils;
or import static com.starbase.util.FileUtils.*
. The hierarchy is just showing that the class FileUtils
extends Object
(as do all classes).
You do also have to have the .jar file/API to access this class.
EDIT: Added possible standalone implementation:
If you want to implement this yourself (I noticed your own 'trivial' answer), you could do something like this:
public static boolean isBinary(String fileName) throws IOException {
return isBinary(new File(fileName));
}
public static boolean isBinary(File file) throws IOException {
InputStream is = new FileInputStream(file);
try {
byte[] buf = new byte[4096];
int bytesRead;
while ((bytesRead = is.read(buf)) >= 0)
{
for (int i = 0; i < bytesRead; i++) {
if (buf[i] == (byte) 0)
return true;
}
}
return false;
} finally {
is.close();
}
}
Please note, I have not tested this.
I should add that this is the trivial implementation. There are many kinds of text files that would be considered binary with this. If you were to allow text to be Unicode and/or UTF-8 (or other text encoding) then this quickly becomes very difficult. Then you need to develop some kinds of heuristics to differentiate between the kinds of files and this would not be 100% accurate. So, it really depends on what you are trying to do with this.
You never have to import java.lang.Object, it's imported implicitely and is the class that every other class is derived from. When you import another class, you import it based on the package it's in. So for the class you want to use it would be:
import com.starbase.util.FileUtils;
com.starbase.util.FileUtils
is not in the standard packaged Java SDK, but instead the StarTeam SDK which you would need to download in order to use the FileUtils#isBinary
method.
Once installed, you would just need to add:
import com.starbase.util.FileUtils;
However, if you do not want to use a third-party SDK, let us know how isBinary
would be helpful to you and we could find a standard Java equivalent.
Also to clarify, import.java.lang.Object.com.starbase.util.FileUtils
is not a valid import, you are concatenating two different packages together.
It has to be either import java.lang.Object
or import com.starbase.util.FileUtils
.
Totally trivial and perhaps easiest but very unreliable!
if( filename.toLowerCase().trim().endsWith(".bin"))
return "Binary";
精彩评论