1

我追求的是通用的非专业纯文本文件提取器。

首先,在人们大喊 Apache Tika 之前——我的回答是它只支持一些流行的二进制文件格式,如 Office、BMP 等。

回到问题 - 许多二进制文件中嵌入了文本字符串,我想在没有二进制字节噪声的情况下提取它们。这意味着它可以在 exes 等中找到简单的文本字符串序列,结果只包含 ascii 单词。我尝试使用谷歌搜索,但找不到任何这样做的东西。我的基本想法是,如果 TIKA 不处理文件,这个简单的二进制文件处理程序会尽力找到这些文本字符串。

4

2 回答 2

0

以下代码过滤不可打印的 ASCII 字符。

package sandbox;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author yan-cheng.cheok
 */
public class Main {

    // Returns the contents of the file in a byte array.
    public static byte[] getBytesFromFile(File file) throws IOException {
        InputStream is = new FileInputStream(file);

        // Get the size of the file
        long length = file.length();

        // You cannot create an array using a long type.
        // It needs to be an int type.
        // Before converting to an int type, check
        // to ensure that file is not larger than Integer.MAX_VALUE.
        if (length > Integer.MAX_VALUE) {
            // File is too large
        }

        // Create the byte array to hold the data
        byte[] bytes = new byte[(int)length];

        // Read in the bytes
        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length
               && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
            offset += numRead;
        }

        // Ensure all the bytes have been read in
        if (offset < bytes.length) {
            throw new IOException("Could not completely read file "+file.getName());
        }

        // Close the input stream and return bytes
        is.close();
        return bytes;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws Exception {
        File f = new File("c:\\jstock.exe");
        byte[] bs = getBytesFromFile(f);
        List<Byte> list = new ArrayList<Byte>();
        for (byte b : bs) {
            if (b >= 0) {
                // Printable ASCII code.
                list.add(b);
            }
        }

        byte[] output = new byte[list.size()];
        for (int i = 0, size = list.size(); i < size; i++) {
            output[i] = list.get(i);
        }
        System.out.println(new String(output));
    }
}
于 2010-12-24T02:24:52.377 回答
0

我最终编写了我的代码类来解决我的问题。

重要功能/注意事项。

  • 只接受 cr、nl、tab、空格 - char127 -
    • 忽略所有非 ascii 字符
    • 如果文件包含 unicode,那么运气不好。
  • 忽略少于几个字符(可配置)的字符序列。
    • 这意味着被其他非 ASCII 值包围的单个字母的字节将被忽略。
  • 在字符序列之间插入一个空格
    • 这意味着一个字符串、一些字节和另一个字符串在结果中显示为由字符串分隔的两个单词,而不是一个长单词。
于 2010-12-25T02:04:44.143 回答