开发者

How to determine given file is a class file?

I need to determine that whether a given file is a class file or not. Suppose I change t开发者_如何学Pythonhe extension to .exe/.xml or some other, I need to determine whether that given file, if a class file will be parsed differently and if it would be some other, it'll be parsed in that manner.

How can I read the class file format?


Java .class files start with HEX: 0xCAFE 0xBABE That's a good start:

CAFE BABE http://a.imageshack.us/img820/2908/capturadepantalla201007k.png


I suspect BCEL lets you do this. Checking now...

EDIT: Yes, it does. You can use the ClassParser class; the parse method will throw a ClassFormatException if the file isn't really a Java class file.

EDIT: Okay, so you need to know from C#. Three options:

  • Check whether the header is 0xcafebabe and leave it at that (it'll be a pretty good heuristic)
  • Port BCEL to C# (just the bits you need, obviously)
  • Try using J# to compile BCEL to .NET directly - that will only work if it doesn't use anything beyond Java 1.1.4, but you may find a really old version of BCEL works fine in that respect. Of course you'll need to get hold of J# as well, which is now discontinued.

The CAFEBABE test is very easy:

public bool IsProbablyJava(string file)
{
    using (Stream stream = File.OpenRead(file))
    {
        return stream.ReadByte() == 0xca &&
               stream.ReadByte() == 0xfe &&
               stream.ReadByte() == 0xba &&
               stream.ReadByte() == 0xbe;
    }
}

It's not exactly pretty... there are alternatives with BinaryReader etc as well.


The class file format says that the first four bytes of a class file will be CA FE BA BE, so you could check for that. Depending on your requirements, that might be a simple enough check.

As an alternative (and possibly better) solution, just try to load the file. If it fails, then it wasn't a class file. If it succeeds, then it was.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜