【发布时间】:2015-01-26 14:27:14
【问题描述】:
我已经构建了一个简单的 Java 程序来从 FRX 属性文件中读取数据。然而,我遇到的问题是我需要能够只从文件中读取二进制文件的特定部分。更具体地说,我需要从与给定十六进制值对应的值开始从文件中读取,并在给定文本字符串的 ASCII 字符停止处结束读取。
我可以使用以下程序在 C# 中做到这一点:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
public class GetFromFRX
{
public static void Main()
{
StringBuilder buffer = new StringBuilder();
using (BinaryReader b = new BinaryReader(File.Open("frmResidency.frx", FileMode.Open)))
{
try
{
b.BaseStream.Seek(641, SeekOrigin.Begin);
int length = b.ReadInt32();
for (int i = 0; i < length; i++)
{
buffer.Append(b.ReadChar());
}
}
catch (Exception e)
{
Console.WriteLine( "Error obtaining resource\n" + e.Message);
}
}
Console.WriteLine(buffer);
}
}
这是我的 Java 程序,我相信我可以使用 DataInputStream 来做我需要的事情,但是我不确定如何使用它的方法来寻找一个十六进制位置来开始读取字节并正确设置长度.如果我运行这个当前代码,我的新文本文件中没有输出,我希望输出超过前 10 个字节,所以我想我不理解 ReadInt() 或 skipBytes 正确:
import java.io.*;
import java.util.*;
public class Tester3 {
public static void main(String[] args) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
DataInputStream din = null;
DataOutputStream dout = null;
try {
in = new FileInputStream("frmResidency.frx");
din = new DataInputStream(in);
out = new FileOutputStream("disisworkinlikeacharm.txt");
dout = new DataOutputStream(out);
din.skipBytes(10);
int length = din.readInt();
int c;
for(c = 0 ; c < length; c++){
out.write(c);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
if (dout != null) {
dout.close();
}
if (din != null) {
din.close();
}
}
}
}
我的问题是,有没有一种简单的方法可以在我的代码中实现寻找某个十六进制位置并将二进制文件读取到一定长度,或者我应该使用类似 RandomAccessFile 完成这个...
【问题讨论】:
标签: java c# binary-data fileinputstream datainputstream