简体   繁体   English

如何从 jpg 文件中正确获取文件内容?

[英]How to get file content properly from a jpg file?

I'm trying to get content from a jpg file so I can encrypt that content and save it in another file that is later decrypted.我正在尝试从 jpg 文件中获取内容,以便我可以加密该内容并将其保存在稍后解密的另一个文件中。

I'm trying to do so by reading the jpg file as if it were a text file with this code:我试图通过读取 jpg 文件来做到这一点,就好像它是一个带有以下代码的文本文件:

   String aBuffer = "";
   try {
        File myFile = new File(pathRoot);
        FileInputStream fIn = new FileInputStream(myFile);
        BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
        String aDataRow = "";
        while ((aDataRow = myReader.readLine()) != null) {
            aBuffer += aDataRow;
        }
        myReader.close();
        } catch (FileNotFoundException e) {
              e.printStackTrace();
        } catch (IOException e) {
              e.printStackTrace();
        }

But this doesn't give the content the file has, just a short string and weirdly enough it also looks like just reading the file corrupts it.但这并没有给出文件的内容,只是一个短字符串,奇怪的是,它看起来也只是读取文件损坏了它。

What could I do so I can achieve the desired behavior?我该怎么做才能实现所需的行为?

Image files aren't text - but you're treating the data as textual data.图片文件不是文本-但你处理数据的文本数据。 Basically, don't do that.基本上,不要这样做。 Use the InputStream to load the data into a byte array (or preferably, use Files.readAllBytes(Path) to do it rather more simply).使用InputStream将数据加载到字节数组中(或者最好使用Files.readAllBytes(Path)来更简单地执行此操作)。

Keep the binary data as binary data.将二进制数据保留二进制数据。 If you absolutely need a text representation, you'll need to encode it in a way that doesn't lose data - where hex or base64 are the most common ways of doing that.如果您绝对需要文本表示,则需要以不会丢失数据的方式对其进行编码 - 其中 hex 或 base64 是最常见的方式。

You mention encryption early in the question: encryption also generally operates on binary data.您在问题的早期提到了加密:加密通常对二进制数据进行操作。 Any encryption methods which provide text options (eg string parameters) are just convenience wrappers which encode the text as binary data and then encrypt it.任何提供文本选项(例如字符串参数)的加密方法都只是将文本编码为二进制数据然后对其进行加密的便利包装器。

and weirdly enough it also looks like just reading the file corrupts it.奇怪的是,它看起来也只是读取文件损坏了它。

I believe you're mistaken about that.我相信你错了。 Just reading from a file will not change it in any way.仅从文件中读取不会以任何方式改变它。 Admittedly you're not using try-with-resources statements, so you could end up keeping the file handle open, potentially preventing another process from reading it - but the content of the file itself won't change.诚然,您没有使用 try-with-resources 语句,因此您最终可能会保持文件句柄打开,这可能会阻止另一个进程读取它——但文件本身的内容不会改变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM