透视大型数据文件

时间:2011-12-16 17:08:48

标签: java unix pivot transpose

我有一些大的制表符分隔数据文件。这些文件的行数比列数多几个数量级。问题是我想转动这些文件,但在这种情况下,“大”被定义为太大而无法在内存中执行此操作。

我希望能以最快的方式找到一些建议。我主要在UNIX上使用Java,虽然如果出现更快的语言特定解决方案(或使用awk等等),我也会对此持开放态度。

目前我们在内存中这样做,但随着时间的推移,文件超出了我们的内存容量。显然,“买一台更大的机器”是一种解决方案,但目前还不在卡片中。

2 个答案:

答案 0 :(得分:1)

以下内容可能适合您。此代码首先以BufferedReader打开源文件,然后读取第一行并将其与\t分开。

结果数组的长度是目标文件的行数。创建了一个新的FileHolder对象数组,其中FileHolder基本上包含文件描述符和ByteBuffer以用作缓存(以便不写入每个单词)。创建所有持有者后,将写入第一行。

然后再次读取源文件,逐行拆分,直到空,并附加所有文件夹。

完成后,将创建目标文件(最后),并按数组顺序将所有FileHolder实例写入其中,因此按行顺序。

以下是示例代码(LONG,也可用here)。它当然可以得到改善(资源并没有真正关闭在正确的地方等),但它的工作原理。它在大约25秒内转换275 MB文件(四核Q6600,4 GB RAM,x86_64 Linux 3.1.2-rc5),并以“脆弱”默认值64 MB Sun(64位)JDK运行:

package net.sf.jpam;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.Reader;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.regex.Pattern;

public final class Test
{
    private static final Pattern TAB = Pattern.compile("\t");

    private static class FileHolder
    {
        private static final byte TABCHAR[] = "\t".getBytes();
        // Size of the buffer size
        private static final int BUFSZ = 32768;

        // Format string for a file
        private static final String FORMAT = "/home/fge/t2.txt.%d";

        // The ByteBuffer
        private final ByteBuffer buf = ByteBuffer.allocate(BUFSZ);

        // The File object
        private final File fd;

        // RandomAccessFile
        private final RandomAccessFile file;

        FileHolder(final int index)
            throws FileNotFoundException
        {
            final String name = String.format(FORMAT, index);
            fd = new File(name);
            file = new RandomAccessFile(fd, "rw");
        }

        public void write(final String s)
            throws IOException
        {
            final byte[] b = s.getBytes();
            if (buf.remaining() < b.length + TABCHAR.length)
                flush();
            buf.put(b).put(TABCHAR);
        }

        private void flush()
            throws IOException
        {
            file.write(buf.array(), 0, buf.position());
            buf.position(0);
        }

        public void copyTo(final RandomAccessFile dst)
            throws IOException
        {
            flush();
            final FileChannel source = file.getChannel();
            final FileChannel destination = dst.getChannel();
            source.force(false);
            final long len = source.size() - TABCHAR.length;

            source.transferTo(0, len, destination);
            dst.writeBytes("\n");

        }

        public void tearDown()
            throws IOException
        {
            file.close();
            if (!fd.delete())
                System.err.println("Failed to remove file " + fd);
        }

        @Override
        public String toString()
        {
            return fd.toString();
        }
    }

    public static void main(final String... args)
        throws IOException
    {
        long before, after;

        before = System.currentTimeMillis();
        final Reader r = new FileReader("/home/fge/t.txt");
        final BufferedReader reader = new BufferedReader(r);

        /*
         * Read first line, count the number of elements. All elements are
         * separated by a single tab.
         */
        String line = reader.readLine();
        String[] elements = TAB.split(line);

        final int nrLines = elements.length;
        final FileHolder[] files = new FileHolder[nrLines];

        /*
         * Initialize file descriptors
         */
        for (int i = 0; i < nrLines; i++)
            files[i] = new FileHolder(i);


        /*
         * Write first lines, then all others
         */
        writeOneLine(elements, files);

        while ((line = reader.readLine()) != null) {
            elements = TAB.split(line);
            writeOneLine(elements, files);
        }

        reader.close();
        r.close();
        after = System.currentTimeMillis();

        System.out.println("Read time: " + (after - before));

        before = System.currentTimeMillis();
        final RandomAccessFile out = new RandomAccessFile("/home/fge/t2.txt",
            "rw");

        for (final FileHolder file: files) {
            file.copyTo(out);
            file.tearDown();
        }

        out.getChannel().force(false);
        out.close();

        after = System.currentTimeMillis();

        System.out.println("Write time: " + (after - before));
        System.exit(0);
    }

    private static void writeOneLine(final String[] elements,
        final FileHolder[] fdArray)
        throws IOException
    {  
        final int len = elements.length;
        String element;
        FileHolder file;

        for (int index = 0; index < len; index++) {
            element = elements[index];
            file = fdArray[index];
            file.write(element);
        }
    }
}

答案 1 :(得分:0)

@fge: 1)最好使用CharBuffer而不是实例化很多字符串。

2)最好像这样使用模式匹配:

initially..

private Matcher matcher;
Pattern regexPattern = Pattern.compile( pattern );
matcher = regexPattern.matcher("");

and then for matching pattern.. you do this..

matcher.reset(charBuffer).find()

因为,当你看到里面时

Pattern.matcher(CharSequence input) {
 Matcher m = new Matcher(this, input);
}

始终避免编写导致大量实例化或字符串使用的代码。这会导致大量内存使用,从而导致性能下降。