Search code examples
javafilerandomaccessfile

Create a file of a given size and type in java


I'm using this code to generate a file of a given size in java:

File file = new File(basedir, filePath);
file.getParentFile().mkdirs();
RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.setLength(sizeInBytes);
raf.close();

I'm creating a .jar file, but the mime type is text/plain(According to its magic header), and I need the file to be application/java-archive. Is there any way for me to set the correct header for this RandomAccessFile?


Solution

  • Got it finally. The magic number for a jar file is (50 4b 03 04) Taken from here

    File file = new File(basedir, filePath);
    file.getParentFile().mkdirs();
    RandomAccessFile raf = new RandomAccessFile(file, "rw");
    raf.setLength(sizeInBytes);
    byte[] magicHeader = new byte[4];
    magicHeader[0] = 0x50;
    magicHeader[1] = 0x4b;
    magicHeader[2] = 0x03;
    magicHeader[3] = 0x04;
    raf.write(magicHeader, 0, 4);
    raf.close();