使用java从文件中打印每行16字节的二进制数据?

问题描述 投票:0回答:3

我也在复制代码和输出,我想知道为什么在提供较大的数据文件作为输入时执行程序需要花费这么多时间。

请仔细阅读代码并给我建议并尝试执行。

java程序:

FileInputStream fis = new FileInputStream("rose.jpg"); //use your own binary file name
DataInputStream dis = new DataInputStream(fis);
try {
    byte buffer[] = new byte[16];

    while((line = dis.read(buffer)) != -1)
    {
        for(int i = 0; i < line; i++)
        {

                value = Integer.toHexString(0xFF & buffer[i] | 0x100).substring(1);
                nextvalue = nextvalue+""+value;

        }
            if(a == 0)
            {
                incValue = nextvalue.substring(0, 32);
                System.out.println(incValue);
            }
            else
            {
                counter = counter + 32;
                incValue = nextvalue.substring(counter, counter + 32);
                System.out.println(incValue);
            }
            a++;

输出:

ffd8ffe000104a464946000101020025
00250000ffdb00430002010101010102
01010102020202020403020202020504
04030406050606060506060607090806
0709070606080b08090a0a0a0a0a0608
0b0c0b0a0c090a0a0affdb0043010202
02020202050303050a0706070a0a0a0a
0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a

输出的每一行都有 16 个字节的值。

请帮我解决这个程序,我必须修改和更改哪些内容,以便程序快速执行。

java inputstream fileinputstream
3个回答
1
投票

您应该做的两件事:1)将文件输入流包装在 BufferedInputStream 中。

InputStream bis = new BufferedInputStream( fileInputStream, 1024*1024 );

这将减少您从存储中读取的次数。 2) 通过附加到 StringBuffer 来缓冲输出,而不是直接写入输出。请注意,如果您的文件非常大,您可能需要写入字符串缓冲区并定期重置它......当然取决于文件有多大。


0
投票

使用

new BufferedInputStream(new FileInputStream(...))

请勿使用

String nextValue
,而是使用
StringBuilder
。弦
+
速度大大减慢。

你可能会使用

String.format("%02x", buffer[i] & 0xFF);

0
投票

你让

nextvalue
变得越来越大。对它的子串操作变得昂贵。子字符串是一个 O(n) 操作。

而不是

            if(a == 0)
            {
                incValue = nextvalue.substring(0, 32);
                System.out.println(incValue);
            }
            else
            {
                counter = counter + 32;
                incValue = nextvalue.substring(counter, counter + 32);
                System.out.println(incValue);
            }
            a++;

为什么不只是:

System.out.println(nextvalue);
nextvalue = "";
© www.soinside.com 2019 - 2024. All rights reserved.