在java中覆盖文件的二进制值

时间:2011-04-22 09:12:34

标签: java file binary

我参与了一个项目,我们通过修改指定位置的字节来隐藏mp3文件中的信息。我发现在线代码可以让我写和读字节,我正在用它来读取mp3文件中的前10个字节。

但是有一个问题,它会一直持续到第4个字节,然后程序结束。换句话说,在我的for循环中,它只会持续到i = 4.

这是我得到的输出。

Read 0th character of file: I
Read 1th character of file: D
Read 2th character of file: 3
Read 3th character of file: 
Read 4th character of file: 
Process completed.

循环以某种方式结束,如果你注意到程序应该以system.out消息结束,该消息是“程序结束”但是甚至没有出现。代码如下。我试过几个mp3文件,结果相同。

可能是什么问题?为什么我的程序结束时甚至没有给我一个错误信息?

import java.io.File;
import java.io.RandomAccessFile;
import java.io.IOException;

public class Edit {

private static void doAccess() { try { //Reads mp3 file named a.mp3 File file = new File("a.mp3"); RandomAccessFile raf = new RandomAccessFile(file, "rw"); //In this part I try to read the first 10 bytes in the file byte ch; for (long i = 0; i < 10 ; i++) { raf.seek(i); //position ourselves at position i ch = raf.readByte(); //read the byte at position i System.out.println("Read "+ i + "th character of file: " + (char)ch); //print the byte at that position //repeat till position 10 } System.out.println("End of program"); raf.close(); } catch (IOException e) { System.out.println("IOException:"); e.printStackTrace(); } } public static void main(String[] args) { doAccess(); } }

提前致谢!

3 个答案:

答案 0 :(得分:2)

我刚试过你的代码,它对我有用。问题在于IDE处理'\0'个字符的方式(第4个字节为'\0')。为了看到实际输出,将print语句(在循环内)更改为:

System.out.println("Read " + i + "th character of file: " + ch);

(即:省略char (char)施法)。然后,您将获得此输出:

Read 0th character of file: 73
Read 1th character of file: 68
Read 2th character of file: 51
Read 3th character of file: 3
Read 4th character of file: 0
Read 5th character of file: 0
Read 6th character of file: 0
Read 7th character of file: 0
Read 8th character of file: 15
Read 9th character of file: 118
End of program

除此之外,我建议如下:

  • 考虑使用预先制作的库来回溯/编写MP3元数据。这比从头开始实现这个逻辑要好得多。
  • 你不需要在循环中寻找()。当你打开文件时,你处于位置0,每个readByte()将位置提前1。
  • 如果在循环内移动ch变量的定义,代码将更具可读性。如果你只在循环中使用它,就没有理由在外面定义它。

答案 1 :(得分:1)

我看不出代码有什么问题,我不明白它是如何产生你报告的输出的。

我怀疑您运行的是与您向我们展示的源代码不匹配的类文件。


实际上该程序存在一些问题:

  1. 您应该在finally子句中关闭RAF。
  2. byte投射到char是狡猾的。显然,一些字节与可打印字符不对应。我猜他们中的一个可能是JCreator解释为文件结尾字符的某个字符...

答案 2 :(得分:1)

我已经运行了你的程序,它运行正常。如果您不确定自己在做什么,我建议不要使用IDE作为初学者。而是使用命令行。

Edit.javaa.mp3放在同一个文件夹中。然后,键入以下内容:

javac Edit.java
java Edit

这应该产生正确的输出。