1

我需要能够从android中的文件中读取字节。

我到处看,似乎FileInputStream应该用来从文件中读取字节,但这不是我想要做的。

我希望能够读取包含(编辑)要保存到数组的字节宽数值(/edit)的文本表示的文本文件。我想转换为字节数组的文本文件示例如下:

0x04 0xF2 0x33 0x21 0xAA

最终文件会更长。UsingFileInputStream获取每个字符的值,我想在其中保存一个长度为 5 的数组以获得上面列出的值。我希望像这样处理数组:

ExampleArray[0] = (byte) 0x04;
ExampleArray[1] = (byte) 0xF2;
ExampleArray[2] = (byte) 0x33;
ExampleArray[3] = (byte) 0x21;
ExampleArray[4] = (byte) 0xAA;

在文本文件上使用FileInputStream会返回字符的 ASCII 值,而不是我需要写入数组的值。

4

3 回答 3

0

最简单的解决方案是使用 FileInputStream.read(byte[] a) 方法将字节从文件传输到字节数组。

于 2013-09-26T13:29:21.613 回答
0

编辑:看来我误读了要求。所以该文件包含字节的文本表示。

Scanner scanner = new Scanner(new FileInputStream(FILENAME));
String input;
while (scanner.hasNext()) {
    input = scanner.next();
    long number = Long.decode(input);
    // do something with the value
}

旧答案(对于这种情况显然是错误的,但我会把它留给后代):

使用 aFileInputStreamread(byte[])方法。

FileInputStream in = new FileInoutStream(filename);
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = in.read(buffer, 0, buffer.length);
于 2013-09-26T13:29:33.127 回答
-1

您只是将字节存储为文本。绝不!因为 0x00 可以写为文件中的一个字节,也可以写为字符串,在这种情况下(十六进制)占用了 4 倍的空间。如果您需要这样做,请讨论这个决定会有多糟糕!
如果你能提供一个合理的理由,我编辑我的答案。

您只会将内容保存为实际文本,如果:

  • 它更容易(不是这样)
  • 它增加了价值(如果文件大小增加超过 4(空间计数)增加了价值,那么是的)
  • 如果用户应该能够编辑文件(那么您将省略“0x”...)

你可以这样写字节:

public static void writeBytes(byte[] in, File file, boolean append) throws IOException {
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(file, append);
        fos.write(in);
    } finally {
        if (fos != null)
            fos.close();
    }
}

并像这样阅读:

public static byte[] readBytes(File file) throws IOException {
    return readBytes(file, (int) file.length());
}

public static byte[] readBytes(File file, int length) throws IOException {
    byte[] content = new byte[length];
    FileInputStream fis = null;

    try {
        fis = new FileInputStream(file);

        while (length > 0)
            length -= fis.read(content);
    } finally {
        if (fis != null)
            fis.close();
    }

    return content;
}

因此有:

public static void writeString(String in, File file, String charset, boolean append)
        throws IOException {
    writeBytes(in.getBytes(charset), file, append);
}

public static String readString(File file, String charset) throws IOException {
    return new String(readBytes(file), charset);
}

写入和读取字符串。

请注意,我不使用 try-with-resource 构造,因为 Android 当前的 Java 源代码级别太低了。:(

于 2013-09-26T14:02:27.120 回答