To Infinity and Beyond …

Simple Tar reader in Java

Posted by: jango on: July 22, 2008


/**
* A simple tar reader
* Just reads through tar file, parses the headers and writes file.
*/
package com.jango.tarreader;

import java.io.IOException;
import java.io.InputStream;

/**
* @author vinu
*
*/
public abstract class AbstractTarReader {

public void read(InputStream in) throws IOException {

while (true) {

Header head = parseHeader(in);

if (head == null)
break;

if (head.isFile && head.filesize > 0) {
int remainder = head.filesize % 512;
int skiplen = 0;
if (remainder != 0)
skiplen = 512 – remainder;

byte[] fileContents = new byte[head.filesize];

in.read(fileContents);
in.skip(skiplen);

createFile(head.filename, fileContents);

} else if (!head.isFile) {
createDir(head.filename);
}

}
}

/**
* Creates the file – dependent on implementation
*
* @param filename
* @param fileContents
* @throws IOException
*/
public abstract void createFile(String filename, byte[] fileContents)
throws IOException;

/**
* Creates the directory as in the tar
*
* @param dirname
*/
public abstract void createDir(String dirname);

// Parses the header
private Header parseHeader(InputStream in) throws IOException {

Header head = new Header();

byte buf[] = new byte[512];

int len = in.read(buf);

// EOF or not fully read
if (len == -1 || len != 512)
return null;

StringBuffer sBufFilename = new StringBuffer();

byte linkIndicator = buf[156];

for (int i = 0; i < 100; i++) {
if (buf[i] != 0) {
sBufFilename.append((char) buf[i]);
}
}

StringBuffer sBufFilesize = new StringBuffer();
for (int i = 124; i < 136; i++) {
sBufFilesize.append((char) buf[i]);
}

head.filename = sBufFilename.toString();
head.filesize = Integer.parseInt(“0″ + sBufFilesize.toString().trim(),8);

if(head.filesize==0 && head.filename.length()==0)
return null;

if ((char) linkIndicator == ’5′) {
head.isFile = false;
}

return head;
}

// To store the header info – Simple for now
// Only the filename
class Header {
String filename;
int filesize;
boolean isFile = true;
}

}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Quote of the moment

Quote

Jango Twitts

Follow

Get every new post delivered to your Inbox.